@payloadcms/plugin-mcp 3.78.0-canary.0 → 3.78.0-canary.1

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 (28) hide show
  1. package/dist/mcp/getMcpHandler.d.ts.map +1 -1
  2. package/dist/mcp/getMcpHandler.js +8 -2
  3. package/dist/mcp/getMcpHandler.js.map +1 -1
  4. package/dist/mcp/tools/global/update.d.ts.map +1 -1
  5. package/dist/mcp/tools/global/update.js +3 -0
  6. package/dist/mcp/tools/global/update.js.map +1 -1
  7. package/dist/mcp/tools/resource/create.d.ts.map +1 -1
  8. package/dist/mcp/tools/resource/create.js +3 -0
  9. package/dist/mcp/tools/resource/create.js.map +1 -1
  10. package/dist/mcp/tools/resource/update.d.ts.map +1 -1
  11. package/dist/mcp/tools/resource/update.js +3 -0
  12. package/dist/mcp/tools/resource/update.js.map +1 -1
  13. package/dist/mcp/tools/schemas.d.ts +2 -2
  14. package/dist/utils/getVirtualFieldNames.d.ts +14 -0
  15. package/dist/utils/getVirtualFieldNames.d.ts.map +1 -0
  16. package/dist/utils/getVirtualFieldNames.js +35 -0
  17. package/dist/utils/getVirtualFieldNames.js.map +1 -0
  18. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +7 -0
  19. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +1 -0
  20. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +20 -0
  21. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +1 -0
  22. package/package.json +3 -3
  23. package/src/mcp/getMcpHandler.ts +22 -2
  24. package/src/mcp/tools/global/update.ts +8 -0
  25. package/src/mcp/tools/resource/create.ts +7 -0
  26. package/src/mcp/tools/resource/update.ts +7 -0
  27. package/src/utils/getVirtualFieldNames.ts +53 -0
  28. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +27 -0
@@ -1 +1 @@
1
- {"version":3,"file":"getMcpHandler.d.ts","sourceRoot":"","sources":["../../src/mcp/getMcpHandler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgC,KAAK,cAAc,EAAkB,MAAM,SAAS,CAAA;AAE3F,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAkC3E,eAAO,MAAM,aAAa,kBACT,qBAAqB,qBACjB,iBAAiB,OAC/B,cAAc,4CA8dpB,CAAA"}
1
+ {"version":3,"file":"getMcpHandler.d.ts","sourceRoot":"","sources":["../../src/mcp/getMcpHandler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgC,KAAK,cAAc,EAAkB,MAAM,SAAS,CAAA;AAE3F,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAA;AAuC3E,eAAO,MAAM,aAAa,kBACT,qBAAqB,qBACjB,iBAAiB,OAC/B,cAAc,4CA6epB,CAAA"}
@@ -3,6 +3,8 @@ import { join } from 'path';
3
3
  import { APIError, configToJSONSchema } from 'payload';
4
4
  import { toCamelCase } from '../utils/camelCase.js';
5
5
  import { getEnabledSlugs } from '../utils/getEnabledSlugs.js';
6
+ import { getCollectionVirtualFieldNames, getGlobalVirtualFieldNames } from '../utils/getVirtualFieldNames.js';
7
+ import { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js';
6
8
  import { registerTool } from './registerTool.js';
7
9
  // Tools
8
10
  import { findGlobalTool } from './tools/global/find.js';
@@ -68,7 +70,9 @@ export const getMCPHandler = (pluginOptions, mcpAccessSettings, req)=>{
68
70
  // Collection Operation Tools
69
71
  enabledCollectionSlugs.forEach((enabledCollectionSlug)=>{
70
72
  try {
71
- const schema = configSchema.definitions?.[enabledCollectionSlug];
73
+ const rawSchema = configSchema.definitions?.[enabledCollectionSlug];
74
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, enabledCollectionSlug);
75
+ const schema = removeVirtualFieldsFromSchema(JSON.parse(JSON.stringify(rawSchema)), virtualFieldNames);
72
76
  const toolCapabilities = mcpAccessSettings?.[`${toCamelCase(enabledCollectionSlug)}`];
73
77
  const allowCreate = toolCapabilities?.create;
74
78
  const allowUpdate = toolCapabilities?.update;
@@ -94,7 +98,9 @@ export const getMCPHandler = (pluginOptions, mcpAccessSettings, req)=>{
94
98
  const enabledGlobalSlugs = getEnabledSlugs(globalsPluginConfig, 'global');
95
99
  enabledGlobalSlugs.forEach((enabledGlobalSlug)=>{
96
100
  try {
97
- const schema = configSchema.definitions?.[enabledGlobalSlug];
101
+ const rawSchema = configSchema.definitions?.[enabledGlobalSlug];
102
+ const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, enabledGlobalSlug);
103
+ const schema = removeVirtualFieldsFromSchema(JSON.parse(JSON.stringify(rawSchema)), virtualFieldNames);
98
104
  const toolCapabilities = mcpAccessSettings?.[`${toCamelCase(enabledGlobalSlug)}`];
99
105
  const allowFind = toolCapabilities?.['find'];
100
106
  const allowUpdate = toolCapabilities?.['update'];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/getMcpHandler.ts"],"sourcesContent":["import type { JSONSchema4 } from 'json-schema'\n\nimport { createMcpHandler } from 'mcp-handler'\nimport { join } from 'path'\nimport { APIError, configToJSONSchema, type PayloadRequest, type TypedUser } from 'payload'\n\nimport type { MCPAccessSettings, PluginMCPServerConfig } from '../types.js'\n\nimport { toCamelCase } from '../utils/camelCase.js'\nimport { getEnabledSlugs } from '../utils/getEnabledSlugs.js'\nimport { registerTool } from './registerTool.js'\n\n// Tools\nimport { findGlobalTool } from './tools/global/find.js'\nimport { updateGlobalTool } from './tools/global/update.js'\nimport { createResourceTool } from './tools/resource/create.js'\nimport { deleteResourceTool } from './tools/resource/delete.js'\nimport { findResourceTool } from './tools/resource/find.js'\nimport { updateResourceTool } from './tools/resource/update.js'\n\n// Experimental Tools\n/**\n * @experimental This tools are experimental and may change or be removed in the future.\n */\nimport { authTool } from './tools/auth/auth.js'\nimport { forgotPasswordTool } from './tools/auth/forgotPassword.js'\nimport { loginTool } from './tools/auth/login.js'\nimport { resetPasswordTool } from './tools/auth/resetPassword.js'\nimport { unlockTool } from './tools/auth/unlock.js'\nimport { verifyTool } from './tools/auth/verify.js'\nimport { createCollectionTool } from './tools/collection/create.js'\nimport { deleteCollectionTool } from './tools/collection/delete.js'\nimport { findCollectionTool } from './tools/collection/find.js'\nimport { updateCollectionTool } from './tools/collection/update.js'\nimport { findConfigTool } from './tools/config/find.js'\nimport { updateConfigTool } from './tools/config/update.js'\nimport { createJobTool } from './tools/job/create.js'\nimport { runJobTool } from './tools/job/run.js'\nimport { updateJobTool } from './tools/job/update.js'\n\nexport const getMCPHandler = (\n pluginOptions: PluginMCPServerConfig,\n mcpAccessSettings: MCPAccessSettings,\n req: PayloadRequest,\n) => {\n const { payload } = req\n const configSchema = configToJSONSchema(payload.config, payload.db.defaultIDType, req.i18n)\n\n // Handler wrapper that injects req before the _extra argument\n const wrapHandler = (handler: (...args: any[]) => any) => {\n return async (...args: any[]) => {\n const _extra = args[args.length - 1]\n const handlerArgs = args.slice(0, -1)\n return await handler(...handlerArgs, req, _extra)\n }\n }\n\n const payloadToolHandler = (\n handler: NonNullable<NonNullable<PluginMCPServerConfig['mcp']>['tools']>[number]['handler'],\n ) => wrapHandler(handler)\n\n const payloadPromptHandler = (\n handler: NonNullable<NonNullable<PluginMCPServerConfig['mcp']>['prompts']>[number]['handler'],\n ) => wrapHandler(handler)\n\n const payloadResourceHandler = (\n handler: NonNullable<NonNullable<PluginMCPServerConfig['mcp']>['resources']>[number]['handler'],\n ) => wrapHandler(handler)\n\n // User\n const user = mcpAccessSettings.user\n\n // MCP Server and Handler Options\n const MCPOptions = pluginOptions.mcp || {}\n const customMCPTools = MCPOptions.tools || []\n const customMCPPrompts = MCPOptions.prompts || []\n const customMCPResources = MCPOptions.resources || []\n const MCPHandlerOptions = MCPOptions.handlerOptions || {}\n const serverOptions = MCPOptions.serverOptions || {}\n const useVerboseLogs = MCPHandlerOptions.verboseLogs ?? false\n\n // Experimental MCP Tool Requirements\n const isDevelopment = process.env.NODE_ENV === 'development'\n const experimentalTools: NonNullable<PluginMCPServerConfig['experimental']>['tools'] =\n pluginOptions?.experimental?.tools || {}\n const collectionsPluginConfig = pluginOptions.collections || {}\n const globalsPluginConfig = pluginOptions.globals || {}\n const collectionsDirPath =\n experimentalTools && experimentalTools.collections?.collectionsDirPath\n ? experimentalTools.collections.collectionsDirPath\n : join(process.cwd(), 'src/collections')\n const configFilePath =\n experimentalTools && experimentalTools.config?.configFilePath\n ? experimentalTools.config.configFilePath\n : join(process.cwd(), 'src/payload.config.ts')\n const jobsDirPath =\n experimentalTools && experimentalTools.jobs?.jobsDirPath\n ? experimentalTools.jobs.jobsDirPath\n : join(process.cwd(), 'src/jobs')\n\n try {\n return createMcpHandler(\n (server) => {\n // Get enabled collections\n const enabledCollectionSlugs = getEnabledSlugs(collectionsPluginConfig, 'collection')\n\n // Collection Operation Tools\n enabledCollectionSlugs.forEach((enabledCollectionSlug) => {\n try {\n const schema = configSchema.definitions?.[enabledCollectionSlug] as JSONSchema4\n\n const toolCapabilities = mcpAccessSettings?.[\n `${toCamelCase(enabledCollectionSlug)}`\n ] as Record<string, unknown>\n const allowCreate: boolean | undefined = toolCapabilities?.create as boolean\n const allowUpdate: boolean | undefined = toolCapabilities?.update as boolean\n const allowFind: boolean | undefined = toolCapabilities?.find as boolean\n const allowDelete: boolean | undefined = toolCapabilities?.delete as boolean\n\n if (allowCreate) {\n registerTool(\n allowCreate,\n `Create ${enabledCollectionSlug}`,\n () =>\n createResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n schema,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowUpdate) {\n registerTool(\n allowUpdate,\n `Update ${enabledCollectionSlug}`,\n () =>\n updateResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n schema,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowFind) {\n registerTool(\n allowFind,\n `Find ${enabledCollectionSlug}`,\n () =>\n findResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowDelete) {\n registerTool(\n allowDelete,\n `Delete ${enabledCollectionSlug}`,\n () =>\n deleteResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n ),\n payload,\n useVerboseLogs,\n )\n }\n } catch (error) {\n throw new APIError(\n `Error registering tools for collection ${enabledCollectionSlug}: ${String(error)}`,\n 500,\n )\n }\n })\n\n // Global Operation Tools\n const enabledGlobalSlugs = getEnabledSlugs(globalsPluginConfig, 'global')\n\n enabledGlobalSlugs.forEach((enabledGlobalSlug) => {\n try {\n const schema = configSchema.definitions?.[enabledGlobalSlug] as JSONSchema4\n\n const toolCapabilities = mcpAccessSettings?.[\n `${toCamelCase(enabledGlobalSlug)}`\n ] as Record<string, unknown>\n const allowFind: boolean | undefined = toolCapabilities?.['find'] as boolean\n const allowUpdate: boolean | undefined = toolCapabilities?.['update'] as boolean\n\n if (allowFind) {\n registerTool(\n allowFind,\n `Find ${enabledGlobalSlug}`,\n () =>\n findGlobalTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledGlobalSlug,\n globalsPluginConfig,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowUpdate) {\n registerTool(\n allowUpdate,\n `Update ${enabledGlobalSlug}`,\n () =>\n updateGlobalTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledGlobalSlug,\n globalsPluginConfig,\n schema,\n ),\n payload,\n useVerboseLogs,\n )\n }\n } catch (error) {\n throw new APIError(\n `Error registering tools for global ${enabledGlobalSlug}: ${String(error)}`,\n 500,\n )\n }\n })\n\n // Custom tools\n customMCPTools.forEach((tool) => {\n const camelCasedToolName = toCamelCase(tool.name)\n const isToolEnabled = mcpAccessSettings['payload-mcp-tool']?.[camelCasedToolName] ?? false\n\n registerTool(\n isToolEnabled,\n tool.name,\n () =>\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.parameters,\n },\n payloadToolHandler(tool.handler),\n ),\n payload,\n useVerboseLogs,\n )\n })\n\n // Custom prompts\n customMCPPrompts.forEach((prompt) => {\n const camelCasedPromptName = toCamelCase(prompt.name)\n const isPromptEnabled =\n mcpAccessSettings['payload-mcp-prompt']?.[camelCasedPromptName] ?? false\n\n if (isPromptEnabled) {\n server.registerPrompt(\n prompt.name,\n {\n argsSchema: prompt.argsSchema,\n description: prompt.description,\n title: prompt.title,\n },\n payloadPromptHandler(prompt.handler),\n )\n if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ✅ Prompt: ${prompt.title} Registered.`)\n }\n } else if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ⏭️ Prompt: ${prompt.title} Skipped.`)\n }\n })\n\n // Custom resources\n customMCPResources.forEach((resource) => {\n const camelCasedResourceName = toCamelCase(resource.name)\n const isResourceEnabled =\n mcpAccessSettings['payload-mcp-resource']?.[camelCasedResourceName] ?? false\n\n if (isResourceEnabled) {\n server.registerResource(\n resource.name,\n // @ts-expect-error - Overload type is not working however -- ResourceTemplate OR String is a valid type\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n payloadResourceHandler(resource.handler),\n )\n\n if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ✅ Resource: ${resource.title} Registered.`)\n }\n } else if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ⏭️ Resource: ${resource.title} Skipped.`)\n }\n })\n\n // Experimental - Collection Schema Modfication Tools\n if (\n mcpAccessSettings.collections?.create &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.create,\n 'Create Collection',\n () =>\n createCollectionTool(server, req, useVerboseLogs, collectionsDirPath, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n if (\n mcpAccessSettings.collections?.delete &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.delete,\n 'Delete Collection',\n () =>\n deleteCollectionTool(server, req, useVerboseLogs, collectionsDirPath, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (\n mcpAccessSettings.collections?.find &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.find,\n 'Find Collection',\n () => findCollectionTool(server, req, useVerboseLogs, collectionsDirPath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (\n mcpAccessSettings.collections?.update &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.update,\n 'Update Collection',\n () =>\n updateCollectionTool(server, req, useVerboseLogs, collectionsDirPath, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n // Experimental - Payload Config Modification Tools\n if (mcpAccessSettings.config?.find && experimentalTools.config?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.config.find,\n 'Find Config',\n () => findConfigTool(server, req, useVerboseLogs, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (\n mcpAccessSettings.config?.update &&\n experimentalTools.config?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.config.update,\n 'Update Config',\n () => updateConfigTool(server, req, useVerboseLogs, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n // Experimental - Job Modification Tools\n if (mcpAccessSettings.jobs?.create && experimentalTools.jobs?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.jobs.create,\n 'Create Job',\n () => createJobTool(server, req, useVerboseLogs, jobsDirPath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.jobs?.update && experimentalTools.jobs?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.jobs.update,\n 'Update Job',\n () => updateJobTool(server, req, useVerboseLogs, jobsDirPath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.jobs?.run && experimentalTools.jobs?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.jobs.run,\n 'Run Job',\n () => runJobTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n // Experimental - Auth Modification Tools\n if (mcpAccessSettings.auth?.auth && experimentalTools.auth?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.auth.auth,\n 'Auth',\n () => authTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.login && experimentalTools.auth?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.auth.login,\n 'Login',\n () => loginTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.verify && experimentalTools.auth?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.auth.verify,\n 'Verify',\n () => verifyTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.resetPassword && experimentalTools.auth?.enabled) {\n registerTool(\n mcpAccessSettings.auth.resetPassword,\n 'Reset Password',\n () => resetPasswordTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.forgotPassword && experimentalTools.auth?.enabled) {\n registerTool(\n mcpAccessSettings.auth.forgotPassword,\n 'Forgot Password',\n () => forgotPasswordTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.unlock && experimentalTools.auth?.enabled) {\n registerTool(\n mcpAccessSettings.auth.unlock,\n 'Unlock',\n () => unlockTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (useVerboseLogs) {\n payload.logger.info('[payload-mcp] 🚀 MCP Server Ready.')\n }\n },\n {\n serverInfo: serverOptions.serverInfo,\n },\n {\n basePath: MCPHandlerOptions.basePath || payload.config.routes?.api || '/api',\n disableSse: MCPHandlerOptions.disableSse ?? true,\n maxDuration: MCPHandlerOptions.maxDuration || 60,\n onEvent: MCPHandlerOptions.onEvent,\n redisUrl: MCPHandlerOptions.redisUrl,\n verboseLogs: useVerboseLogs,\n },\n )\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n}\n"],"names":["createMcpHandler","join","APIError","configToJSONSchema","toCamelCase","getEnabledSlugs","registerTool","findGlobalTool","updateGlobalTool","createResourceTool","deleteResourceTool","findResourceTool","updateResourceTool","authTool","forgotPasswordTool","loginTool","resetPasswordTool","unlockTool","verifyTool","createCollectionTool","deleteCollectionTool","findCollectionTool","updateCollectionTool","findConfigTool","updateConfigTool","createJobTool","runJobTool","updateJobTool","getMCPHandler","pluginOptions","mcpAccessSettings","req","payload","configSchema","config","db","defaultIDType","i18n","wrapHandler","handler","args","_extra","length","handlerArgs","slice","payloadToolHandler","payloadPromptHandler","payloadResourceHandler","user","MCPOptions","mcp","customMCPTools","tools","customMCPPrompts","prompts","customMCPResources","resources","MCPHandlerOptions","handlerOptions","serverOptions","useVerboseLogs","verboseLogs","isDevelopment","process","env","NODE_ENV","experimentalTools","experimental","collectionsPluginConfig","collections","globalsPluginConfig","globals","collectionsDirPath","cwd","configFilePath","jobsDirPath","jobs","server","enabledCollectionSlugs","forEach","enabledCollectionSlug","schema","definitions","toolCapabilities","allowCreate","create","allowUpdate","update","allowFind","find","allowDelete","delete","error","String","enabledGlobalSlugs","enabledGlobalSlug","tool","camelCasedToolName","name","isToolEnabled","description","inputSchema","parameters","prompt","camelCasedPromptName","isPromptEnabled","registerPrompt","argsSchema","title","logger","info","resource","camelCasedResourceName","isResourceEnabled","registerResource","uri","mimeType","enabled","run","auth","login","verify","resetPassword","forgotPassword","unlock","serverInfo","basePath","routes","api","disableSse","maxDuration","onEvent","redisUrl"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,cAAa;AAC9C,SAASC,IAAI,QAAQ,OAAM;AAC3B,SAASC,QAAQ,EAA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EAC7B,UACA,IAAMvG,WAAW2D,QAAQ9C,KAAK6B,iBAC9B5B,SACA4B;YAEJ;YAEA,IAAI9B,kBAAkByF,IAAI,EAAEG,iBAAiBxD,kBAAkBqD,IAAI,EAAEF,SAAS;gBAC5E/G,aACEwB,kBAAkByF,IAAI,CAACG,aAAa,EACpC,kBACA,IAAM1G,kBAAkB6D,QAAQ9C,KAAK6B,iBACrC5B,SACA4B;YAEJ;YAEA,IAAI9B,kBAAkByF,IAAI,EAAEI,kBAAkBzD,kBAAkBqD,IAAI,EAAEF,SAAS;gBAC7E/G,aACEwB,kBAAkByF,IAAI,CAACI,cAAc,EACrC,mBACA,IAAM7G,mBAAmB+D,QAAQ9C,KAAK6B,iBACtC5B,SACA4B;YAEJ;YAEA,IAAI9B,kBAAkByF,IAAI,EAAEK,UAAU1D,kBAAkBqD,IAAI,EAAEF,SAAS;gBACrE/G,aACEwB,kBAAkByF,IAAI,CAACK,MAAM,EAC7B,UACA,IAAM3G,WAAW4D,QAAQ9C,KAAK6B,iBAC9B5B,SACA4B;YAEJ;YAEA,IAAIA,gBAAgB;gBAClB5B,QAAQ6E,MAAM,CAACC,IAAI,CAAC;YACtB;QACF,GACA;YACEe,YAAYlE,cAAckE,UAAU;QACtC,GACA;YACEC,UAAUrE,kBAAkBqE,QAAQ,IAAI9F,QAAQE,MAAM,CAAC6F,MAAM,EAAEC,OAAO;YACtEC,YAAYxE,kBAAkBwE,UAAU,IAAI;YAC5CC,aAAazE,kBAAkByE,WAAW,IAAI;YAC9CC,SAAS1E,kBAAkB0E,OAAO;YAClCC,UAAU3E,kBAAkB2E,QAAQ;YACpCvE,aAAaD;QACf;IAEJ,EAAE,OAAOgC,OAAO;QACd,MAAM,IAAI1F,SAAS,CAAC,gCAAgC,EAAE2F,OAAOD,QAAQ,EAAE;IACzE;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/mcp/getMcpHandler.ts"],"sourcesContent":["import type { JSONSchema4 } from 'json-schema'\n\nimport { createMcpHandler } from 'mcp-handler'\nimport { join } from 'path'\nimport { APIError, configToJSONSchema, type PayloadRequest, type TypedUser } from 'payload'\n\nimport type { MCPAccessSettings, PluginMCPServerConfig } from '../types.js'\n\nimport { toCamelCase } from '../utils/camelCase.js'\nimport { getEnabledSlugs } from '../utils/getEnabledSlugs.js'\nimport {\n getCollectionVirtualFieldNames,\n getGlobalVirtualFieldNames,\n} from '../utils/getVirtualFieldNames.js'\nimport { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js'\nimport { registerTool } from './registerTool.js'\n\n// Tools\nimport { findGlobalTool } from './tools/global/find.js'\nimport { updateGlobalTool } from './tools/global/update.js'\nimport { createResourceTool } from './tools/resource/create.js'\nimport { deleteResourceTool } from './tools/resource/delete.js'\nimport { findResourceTool } from './tools/resource/find.js'\nimport { updateResourceTool } from './tools/resource/update.js'\n\n// Experimental Tools\n/**\n * @experimental This tools are experimental and may change or be removed in the future.\n */\nimport { authTool } from './tools/auth/auth.js'\nimport { forgotPasswordTool } from './tools/auth/forgotPassword.js'\nimport { loginTool } from './tools/auth/login.js'\nimport { resetPasswordTool } from './tools/auth/resetPassword.js'\nimport { unlockTool } from './tools/auth/unlock.js'\nimport { verifyTool } from './tools/auth/verify.js'\nimport { createCollectionTool } from './tools/collection/create.js'\nimport { deleteCollectionTool } from './tools/collection/delete.js'\nimport { findCollectionTool } from './tools/collection/find.js'\nimport { updateCollectionTool } from './tools/collection/update.js'\nimport { findConfigTool } from './tools/config/find.js'\nimport { updateConfigTool } from './tools/config/update.js'\nimport { createJobTool } from './tools/job/create.js'\nimport { runJobTool } from './tools/job/run.js'\nimport { updateJobTool } from './tools/job/update.js'\n\nexport const getMCPHandler = (\n pluginOptions: PluginMCPServerConfig,\n mcpAccessSettings: MCPAccessSettings,\n req: PayloadRequest,\n) => {\n const { payload } = req\n const configSchema = configToJSONSchema(payload.config, payload.db.defaultIDType, req.i18n)\n\n // Handler wrapper that injects req before the _extra argument\n const wrapHandler = (handler: (...args: any[]) => any) => {\n return async (...args: any[]) => {\n const _extra = args[args.length - 1]\n const handlerArgs = args.slice(0, -1)\n return await handler(...handlerArgs, req, _extra)\n }\n }\n\n const payloadToolHandler = (\n handler: NonNullable<NonNullable<PluginMCPServerConfig['mcp']>['tools']>[number]['handler'],\n ) => wrapHandler(handler)\n\n const payloadPromptHandler = (\n handler: NonNullable<NonNullable<PluginMCPServerConfig['mcp']>['prompts']>[number]['handler'],\n ) => wrapHandler(handler)\n\n const payloadResourceHandler = (\n handler: NonNullable<NonNullable<PluginMCPServerConfig['mcp']>['resources']>[number]['handler'],\n ) => wrapHandler(handler)\n\n // User\n const user = mcpAccessSettings.user\n\n // MCP Server and Handler Options\n const MCPOptions = pluginOptions.mcp || {}\n const customMCPTools = MCPOptions.tools || []\n const customMCPPrompts = MCPOptions.prompts || []\n const customMCPResources = MCPOptions.resources || []\n const MCPHandlerOptions = MCPOptions.handlerOptions || {}\n const serverOptions = MCPOptions.serverOptions || {}\n const useVerboseLogs = MCPHandlerOptions.verboseLogs ?? false\n\n // Experimental MCP Tool Requirements\n const isDevelopment = process.env.NODE_ENV === 'development'\n const experimentalTools: NonNullable<PluginMCPServerConfig['experimental']>['tools'] =\n pluginOptions?.experimental?.tools || {}\n const collectionsPluginConfig = pluginOptions.collections || {}\n const globalsPluginConfig = pluginOptions.globals || {}\n const collectionsDirPath =\n experimentalTools && experimentalTools.collections?.collectionsDirPath\n ? experimentalTools.collections.collectionsDirPath\n : join(process.cwd(), 'src/collections')\n const configFilePath =\n experimentalTools && experimentalTools.config?.configFilePath\n ? experimentalTools.config.configFilePath\n : join(process.cwd(), 'src/payload.config.ts')\n const jobsDirPath =\n experimentalTools && experimentalTools.jobs?.jobsDirPath\n ? experimentalTools.jobs.jobsDirPath\n : join(process.cwd(), 'src/jobs')\n\n try {\n return createMcpHandler(\n (server) => {\n // Get enabled collections\n const enabledCollectionSlugs = getEnabledSlugs(collectionsPluginConfig, 'collection')\n\n // Collection Operation Tools\n enabledCollectionSlugs.forEach((enabledCollectionSlug) => {\n try {\n const rawSchema = configSchema.definitions?.[enabledCollectionSlug] as JSONSchema4\n\n const virtualFieldNames = getCollectionVirtualFieldNames(\n payload.config,\n enabledCollectionSlug,\n )\n const schema = removeVirtualFieldsFromSchema(\n JSON.parse(JSON.stringify(rawSchema)) as JSONSchema4,\n virtualFieldNames,\n )\n\n const toolCapabilities = mcpAccessSettings?.[\n `${toCamelCase(enabledCollectionSlug)}`\n ] as Record<string, unknown>\n const allowCreate: boolean | undefined = toolCapabilities?.create as boolean\n const allowUpdate: boolean | undefined = toolCapabilities?.update as boolean\n const allowFind: boolean | undefined = toolCapabilities?.find as boolean\n const allowDelete: boolean | undefined = toolCapabilities?.delete as boolean\n\n if (allowCreate) {\n registerTool(\n allowCreate,\n `Create ${enabledCollectionSlug}`,\n () =>\n createResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n schema,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowUpdate) {\n registerTool(\n allowUpdate,\n `Update ${enabledCollectionSlug}`,\n () =>\n updateResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n schema,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowFind) {\n registerTool(\n allowFind,\n `Find ${enabledCollectionSlug}`,\n () =>\n findResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowDelete) {\n registerTool(\n allowDelete,\n `Delete ${enabledCollectionSlug}`,\n () =>\n deleteResourceTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledCollectionSlug,\n collectionsPluginConfig,\n ),\n payload,\n useVerboseLogs,\n )\n }\n } catch (error) {\n throw new APIError(\n `Error registering tools for collection ${enabledCollectionSlug}: ${String(error)}`,\n 500,\n )\n }\n })\n\n // Global Operation Tools\n const enabledGlobalSlugs = getEnabledSlugs(globalsPluginConfig, 'global')\n\n enabledGlobalSlugs.forEach((enabledGlobalSlug) => {\n try {\n const rawSchema = configSchema.definitions?.[enabledGlobalSlug] as JSONSchema4\n\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, enabledGlobalSlug)\n const schema = removeVirtualFieldsFromSchema(\n JSON.parse(JSON.stringify(rawSchema)) as JSONSchema4,\n virtualFieldNames,\n )\n\n const toolCapabilities = mcpAccessSettings?.[\n `${toCamelCase(enabledGlobalSlug)}`\n ] as Record<string, unknown>\n const allowFind: boolean | undefined = toolCapabilities?.['find'] as boolean\n const allowUpdate: boolean | undefined = toolCapabilities?.['update'] as boolean\n\n if (allowFind) {\n registerTool(\n allowFind,\n `Find ${enabledGlobalSlug}`,\n () =>\n findGlobalTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledGlobalSlug,\n globalsPluginConfig,\n ),\n payload,\n useVerboseLogs,\n )\n }\n if (allowUpdate) {\n registerTool(\n allowUpdate,\n `Update ${enabledGlobalSlug}`,\n () =>\n updateGlobalTool(\n server,\n req,\n user,\n useVerboseLogs,\n enabledGlobalSlug,\n globalsPluginConfig,\n schema,\n ),\n payload,\n useVerboseLogs,\n )\n }\n } catch (error) {\n throw new APIError(\n `Error registering tools for global ${enabledGlobalSlug}: ${String(error)}`,\n 500,\n )\n }\n })\n\n // Custom tools\n customMCPTools.forEach((tool) => {\n const camelCasedToolName = toCamelCase(tool.name)\n const isToolEnabled = mcpAccessSettings['payload-mcp-tool']?.[camelCasedToolName] ?? false\n\n registerTool(\n isToolEnabled,\n tool.name,\n () =>\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.parameters,\n },\n payloadToolHandler(tool.handler),\n ),\n payload,\n useVerboseLogs,\n )\n })\n\n // Custom prompts\n customMCPPrompts.forEach((prompt) => {\n const camelCasedPromptName = toCamelCase(prompt.name)\n const isPromptEnabled =\n mcpAccessSettings['payload-mcp-prompt']?.[camelCasedPromptName] ?? false\n\n if (isPromptEnabled) {\n server.registerPrompt(\n prompt.name,\n {\n argsSchema: prompt.argsSchema,\n description: prompt.description,\n title: prompt.title,\n },\n payloadPromptHandler(prompt.handler),\n )\n if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ✅ Prompt: ${prompt.title} Registered.`)\n }\n } else if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ⏭️ Prompt: ${prompt.title} Skipped.`)\n }\n })\n\n // Custom resources\n customMCPResources.forEach((resource) => {\n const camelCasedResourceName = toCamelCase(resource.name)\n const isResourceEnabled =\n mcpAccessSettings['payload-mcp-resource']?.[camelCasedResourceName] ?? false\n\n if (isResourceEnabled) {\n server.registerResource(\n resource.name,\n // @ts-expect-error - Overload type is not working however -- ResourceTemplate OR String is a valid type\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n payloadResourceHandler(resource.handler),\n )\n\n if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ✅ Resource: ${resource.title} Registered.`)\n }\n } else if (useVerboseLogs) {\n payload.logger.info(`[payload-mcp] ⏭️ Resource: ${resource.title} Skipped.`)\n }\n })\n\n // Experimental - Collection Schema Modfication Tools\n if (\n mcpAccessSettings.collections?.create &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.create,\n 'Create Collection',\n () =>\n createCollectionTool(server, req, useVerboseLogs, collectionsDirPath, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n if (\n mcpAccessSettings.collections?.delete &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.delete,\n 'Delete Collection',\n () =>\n deleteCollectionTool(server, req, useVerboseLogs, collectionsDirPath, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (\n mcpAccessSettings.collections?.find &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.find,\n 'Find Collection',\n () => findCollectionTool(server, req, useVerboseLogs, collectionsDirPath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (\n mcpAccessSettings.collections?.update &&\n experimentalTools.collections?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.collections.update,\n 'Update Collection',\n () =>\n updateCollectionTool(server, req, useVerboseLogs, collectionsDirPath, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n // Experimental - Payload Config Modification Tools\n if (mcpAccessSettings.config?.find && experimentalTools.config?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.config.find,\n 'Find Config',\n () => findConfigTool(server, req, useVerboseLogs, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (\n mcpAccessSettings.config?.update &&\n experimentalTools.config?.enabled &&\n isDevelopment\n ) {\n registerTool(\n mcpAccessSettings.config.update,\n 'Update Config',\n () => updateConfigTool(server, req, useVerboseLogs, configFilePath),\n payload,\n useVerboseLogs,\n )\n }\n\n // Experimental - Job Modification Tools\n if (mcpAccessSettings.jobs?.create && experimentalTools.jobs?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.jobs.create,\n 'Create Job',\n () => createJobTool(server, req, useVerboseLogs, jobsDirPath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.jobs?.update && experimentalTools.jobs?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.jobs.update,\n 'Update Job',\n () => updateJobTool(server, req, useVerboseLogs, jobsDirPath),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.jobs?.run && experimentalTools.jobs?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.jobs.run,\n 'Run Job',\n () => runJobTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n // Experimental - Auth Modification Tools\n if (mcpAccessSettings.auth?.auth && experimentalTools.auth?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.auth.auth,\n 'Auth',\n () => authTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.login && experimentalTools.auth?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.auth.login,\n 'Login',\n () => loginTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.verify && experimentalTools.auth?.enabled && isDevelopment) {\n registerTool(\n mcpAccessSettings.auth.verify,\n 'Verify',\n () => verifyTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.resetPassword && experimentalTools.auth?.enabled) {\n registerTool(\n mcpAccessSettings.auth.resetPassword,\n 'Reset Password',\n () => resetPasswordTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.forgotPassword && experimentalTools.auth?.enabled) {\n registerTool(\n mcpAccessSettings.auth.forgotPassword,\n 'Forgot Password',\n () => forgotPasswordTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (mcpAccessSettings.auth?.unlock && experimentalTools.auth?.enabled) {\n registerTool(\n mcpAccessSettings.auth.unlock,\n 'Unlock',\n () => unlockTool(server, req, useVerboseLogs),\n payload,\n useVerboseLogs,\n )\n }\n\n if (useVerboseLogs) {\n payload.logger.info('[payload-mcp] 🚀 MCP Server Ready.')\n }\n },\n {\n serverInfo: serverOptions.serverInfo,\n },\n {\n basePath: MCPHandlerOptions.basePath || payload.config.routes?.api || '/api',\n disableSse: MCPHandlerOptions.disableSse ?? true,\n maxDuration: MCPHandlerOptions.maxDuration || 60,\n onEvent: MCPHandlerOptions.onEvent,\n redisUrl: MCPHandlerOptions.redisUrl,\n verboseLogs: useVerboseLogs,\n },\n )\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n}\n"],"names":["createMcpHandler","join","APIError","configToJSONSchema","toCamelCase","getEnabledSlugs","getCollectionVirtualFieldNames","getGlobalVirtualFieldNames","removeVirtualFieldsFromSchema","registerTool","findGlobalTool","updateGlobalTool","createResourceTool","deleteResourceTool","findResourceTool","updateResourceTool","authTool","forgotPasswordTool","loginTool","resetPasswordTool","unlockTool","verifyTool","createCollectionTool","deleteCollectionTool","findCollectionTool","updateCollectionTool","findConfigTool","updateConfigTool","createJobTool","runJobTool","updateJobTool","getMCPHandler","pluginOptions","mcpAccessSettings","req","payload","configSchema","config","db","defaultIDType","i18n","wrapHandler","handler","args","_extra","length","handlerArgs","slice","payloadToolHandler","payloadPromptHandler","payloadResourceHandler","user","MCPOptions","mcp","customMCPTools","tools","customMCPPrompts","prompts","customMCPResources","resources","MCPHandlerOptions","handlerOptions","serverOptions","useVerboseLogs","verboseLogs","isDevelopment","process","env","NODE_ENV","experimentalTools","experimental","collectionsPluginConfig","collections","globalsPluginConfig","globals","collectionsDirPath","cwd","configFilePath","jobsDirPath","jobs","server","enabledCollectionSlugs","forEach","enabledCollectionSlug","rawSchema","definitions","virtualFieldNames","schema","JSON","parse","stringify","toolCapabilities","allowCreate","create","allowUpdate","update","allowFind","find","allowDelete","delete","error","String","enabledGlobalSlugs","enabledGlobalSlug","tool","camelCasedToolName","name","isToolEnabled","description","inputSchema","parameters","prompt","camelCasedPromptName","isPromptEnabled","registerPrompt","argsSchema","title","logger","info","resource","camelCasedResourceName","isResourceEnabled","registerResource","uri","mimeType","enabled","run","auth","login","verify","resetPassword","forgotPassword","unlock","serverInfo","basePath","routes","api","disableSse","maxDuration","onEvent","redisUrl"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,cAAa;AAC9C,SAASC,IAAI,QAAQ,OAAM;AAC3B,SAASC,QAAQ,EAAEC,kBAAkB,QAA6C,UAAS;AAI3F,SAASC,WAAW,QAAQ,wBAAuB;AACnD,SAASC,eAAe,QAAQ,8BAA6B;AAC7D,SACEC,8BAA8B,EAC9BC,0BAA0B,QACrB,mCAAkC;AACzC,SAASC,6BAA6B,QAAQ,6DAA4D;AAC1G,SAASC,YAAY,QAAQ,oBAAmB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,MAAM,IAAIlG,SAAS,CAAC,gCAAgC,EAAEmG,OAAOD,QAAQ,EAAE;IACzE;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/global/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,gBAAgB,WACnB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,cACR,MAAM,WACT,qBAAqB,CAAC,SAAS,CAAC,UACjC,WAAW,SAmLpB,CAAA"}
1
+ {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/global/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAU9D,eAAO,MAAM,gBAAgB,WACnB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,cACR,MAAM,WACT,qBAAqB,CAAC,SAAS,CAAC,UACjC,WAAW,SAuLpB,CAAA"}
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { toCamelCase } from '../../../utils/camelCase.js';
3
+ import { getGlobalVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
3
4
  import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
4
5
  import { toolSchemas } from '../schemas.js';
5
6
  export const updateGlobalTool = (server, req, user, verboseLogs, globalSlug, globals, schema)=>{
@@ -13,6 +14,8 @@ export const updateGlobalTool = (server, req, user, verboseLogs, globalSlug, glo
13
14
  let parsedData;
14
15
  try {
15
16
  parsedData = JSON.parse(data);
17
+ const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug);
18
+ parsedData = stripVirtualFields(parsedData, virtualFieldNames);
16
19
  if (verboseLogs) {
17
20
  payload.logger.info(`[payload-mcp] Parsed data for ${globalSlug}: ${JSON.stringify(parsedData)}`);
18
21
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/tools/global/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const updateGlobalTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n globalSlug: string,\n globals: PluginMCPServerConfig['globals'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n draft: boolean = false,\n depth: number = 0,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Updating global: ${globalSlug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${globalSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON for global: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n user,\n }\n\n // Add locale parameters if provided\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (selectClause) {\n updateOptions.select = selectClause\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated global: ${globalSlug}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Global \"${globalSlug}\" updated successfully!\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, result, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(`[payload-mcp] Error updating global ${globalSlug}: ${errorMessage}`)\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating global \"${globalSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (globals?.[globalSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Make all fields optional for partial updates (PATCH-style)\n const optionalFields = Object.fromEntries(\n Object.entries(convertedFields.shape).map(([key, value]) => [key, (value as any).optional()]),\n )\n\n const updateGlobalSchema = z.object({\n ...optionalFields,\n depth: z.number().optional().describe('Optional: Depth of relationships to populate'),\n draft: z.boolean().optional().describe('Optional: Whether to save as draft (default: false)'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to update data in (e.g., \"en\", \"es\"). Use \"all\" to update all locales for localized fields',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"siteName\": \"My Site\"}\\'',\n ),\n })\n\n server.registerTool(\n `update${globalSlug.charAt(0).toUpperCase() + toCamelCase(globalSlug).slice(1)}`,\n {\n description: `${toolSchemas.updateGlobal.description.trim()}\\n\\n${globals?.[globalSlug]?.description || ''}`,\n inputSchema: updateGlobalSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...rest } = params\n const data = JSON.stringify(rest)\n return await tool(\n data,\n draft as boolean,\n depth as number,\n locale as string,\n fallbackLocale as string,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","toolSchemas","updateGlobalTool","server","req","user","verboseLogs","globalSlug","globals","schema","tool","data","draft","depth","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","response","content","type","text","overrideResponse","selectClause","warn","updateOptions","slug","result","updateGlobal","errorMessage","Error","message","enabled","convertedFields","optionalFields","Object","fromEntries","entries","shape","map","key","value","optional","updateGlobalSchema","object","number","describe","boolean","string","registerTool","charAt","toUpperCase","slice","description","trim","inputSchema","params","rest"],"mappings":"AAIA,SAASA,CAAC,Q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S;QAErD,6DAA6D;QAC7D,MAAMiC,iBAAiBC,OAAOC,WAAW,CACvCD,OAAOE,OAAO,CAACJ,gBAAgBK,KAAK,EAAEC,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;gBAACD;gBAAMC,MAAcC,QAAQ;aAAG;QAG9F,MAAMC,qBAAqBrD,EAAEsD,MAAM,CAAC;YAClC,GAAGV,cAAc;YACjB7B,OAAOf,EAAEuD,MAAM,GAAGH,QAAQ,GAAGI,QAAQ,CAAC;YACtC1C,OAAOd,EAAEyD,OAAO,GAAGL,QAAQ,GAAGI,QAAQ,CAAC;YACvCvC,gBAAgBjB,EACb0D,MAAM,GACNN,QAAQ,GACRI,QAAQ,CAAC;YACZxC,QAAQhB,EACL0D,MAAM,GACNN,QAAQ,GACRI,QAAQ,CACP;YAEJtC,QAAQlB,EACL0D,MAAM,GACNN,QAAQ,GACRI,QAAQ,CACP;QAEN;QAEAnD,OAAOsD,YAAY,CACjB,CAAC,MAAM,EAAElD,WAAWmD,MAAM,CAAC,GAAGC,WAAW,KAAK5D,YAAYQ,YAAYqD,KAAK,CAAC,IAAI,EAChF;YACEC,aAAa,GAAG5D,YAAYmC,YAAY,CAACyB,WAAW,CAACC,IAAI,GAAG,IAAI,EAAEtD,SAAS,CAACD,WAAW,EAAEsD,eAAe,IAAI;YAC5GE,aAAaZ,mBAAmBL,KAAK;QACvC,GACA,OAAOkB;YACL,MAAM,EAAEnD,KAAK,EAAED,KAAK,EAAEG,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAGiD,MAAM,GAAGD;YAClE,MAAMrD,OAAOU,KAAKE,SAAS,CAAC0C;YAC5B,OAAO,MAAMvD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../src/mcp/tools/global/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { toolSchemas } from '../schemas.js'\n\nexport const updateGlobalTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n globalSlug: string,\n globals: PluginMCPServerConfig['globals'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n draft: boolean = false,\n depth: number = 0,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Updating global: ${globalSlug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${globalSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON for global: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n user,\n }\n\n // Add locale parameters if provided\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (selectClause) {\n updateOptions.select = selectClause\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated global: ${globalSlug}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Global \"${globalSlug}\" updated successfully!\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, result, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(`[payload-mcp] Error updating global ${globalSlug}: ${errorMessage}`)\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating global \"${globalSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (globals?.[globalSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (globals?.[globalSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Make all fields optional for partial updates (PATCH-style)\n const optionalFields = Object.fromEntries(\n Object.entries(convertedFields.shape).map(([key, value]) => [key, (value as any).optional()]),\n )\n\n const updateGlobalSchema = z.object({\n ...optionalFields,\n depth: z.number().optional().describe('Optional: Depth of relationships to populate'),\n draft: z.boolean().optional().describe('Optional: Whether to save as draft (default: false)'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to update data in (e.g., \"en\", \"es\"). Use \"all\" to update all locales for localized fields',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"siteName\": \"My Site\"}\\'',\n ),\n })\n\n server.registerTool(\n `update${globalSlug.charAt(0).toUpperCase() + toCamelCase(globalSlug).slice(1)}`,\n {\n description: `${toolSchemas.updateGlobal.description.trim()}\\n\\n${globals?.[globalSlug]?.description || ''}`,\n inputSchema: updateGlobalSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...rest } = params\n const data = JSON.stringify(rest)\n return await tool(\n data,\n draft as boolean,\n depth as number,\n locale as string,\n fallbackLocale as string,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","getGlobalVirtualFieldNames","stripVirtualFields","convertCollectionSchemaToZod","toolSchemas","updateGlobalTool","server","req","user","verboseLogs","globalSlug","globals","schema","tool","data","draft","depth","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","virtualFieldNames","config","stringify","_parseError","error","response","content","type","text","overrideResponse","selectClause","warn","updateOptions","slug","result","updateGlobal","errorMessage","Error","message","enabled","convertedFields","optionalFields","Object","fromEntries","entries","shape","map","key","value","optional","updateGlobalSchema","object","number","describe","boolean","string","registerTool","charAt","toUpperCase","slice","description","trim","inputSchema","params","rest"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,WAAW,QAAQ,gBAAe;AAE3C,OAAO,MAAMC,mBAAmB,CAC9BC,QACAC,KACAC,MACAC,aACAC,YACAC,SACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QAAiB,KAAK,EACtBC,QAAgB,CAAC,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AAO,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
+ {"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAU9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SA2LpB,CAAA"}
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { toCamelCase } from '../../../utils/camelCase.js';
3
+ import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
3
4
  import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
4
5
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
5
6
  import { toolSchemas } from '../schemas.js';
@@ -16,6 +17,8 @@ export const createResourceTool = (server, req, user, verboseLogs, collectionSlu
16
17
  parsedData = JSON.parse(data);
17
18
  // Transform point fields from object format to tuple array
18
19
  parsedData = transformPointDataToPayload(parsedData);
20
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
21
+ parsedData = stripVirtualFields(parsedData, virtualFieldNames);
19
22
  if (verboseLogs) {
20
23
  payload.logger.info(`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`);
21
24
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/tools/resource/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const createResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n depth: number = 0,\n draft: boolean,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Creating resource in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n return {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Create the resource\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n })\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully created resource in ${collectionSlug} with ID: ${result.id}`,\n )\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource created successfully in collection \"${collectionSlug}\"!\nCreated resource:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error creating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error creating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with create-specific parameters\n const createResourceSchema = z.object({\n ...convertedFields.shape,\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships in response'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to create the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n })\n\n server.registerTool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n inputSchema: createResourceSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...fieldData } = params\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n depth as number,\n draft as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","createResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","depth","draft","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","content","type","text","selectClause","warn","response","overrideResponse","result","create","collection","overrideAccess","id","errorMessage","Error","message","enabled","convertedFields","createResourceSchema","object","shape","number","int","min","max","optional","default","describe","boolean","string","registerTool","charAt","toUpperCase","slice","description","createResource","trim","inputSchema","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QAAgB,CAAC,EACjBC,OACAC,QACAC,gBACAC;QAOA,MAAMC,UAAUb,IAAIa,OAAO;QAE3B,IAAIX,aAAa;YACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,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EJpC,QAAQnB,EACLyD,MAAM,GACNJ,QAAQ,GACRE,QAAQ,CACP;QAEN;QAEAjD,OAAOoD,YAAY,CACjB,CAAC,MAAM,EAAEhD,eAAeiD,MAAM,CAAC,GAAGC,WAAW,KAAK3D,YAAYS,gBAAgBmD,KAAK,CAAC,IAAI,EACxF;YACEC,aAAa,GAAGnD,aAAa,CAACD,eAAe,EAAEoD,eAAe1D,YAAY2D,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI;YAC7GC,aAAanB,qBAAqBE,KAAK;QACzC,GACA,OAAOkB;YACL,MAAM,EAAEnD,KAAK,EAAEC,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAGgD,WAAW,GAAGD;YACvE,MAAMpD,OAAOU,KAAKE,SAAS,CAACyC;YAC5B,OAAO,MAAMtD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../src/mcp/tools/resource/create.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const createResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n depth: number = 0,\n draft: boolean,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Creating resource in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n return {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Create the resource\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n req,\n user,\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n })\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully created resource in ${collectionSlug} with ID: ${result.id}`,\n )\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Resource created successfully in collection \"${collectionSlug}\"!\nCreated resource:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error creating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error creating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with create-specific parameters\n const createResourceSchema = z.object({\n ...convertedFields.shape,\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships in response'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to create the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n })\n\n server.registerTool(\n `create${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.createResource.description.trim()}`,\n inputSchema: createResourceSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const { depth, draft, fallbackLocale, locale, select, ...fieldData } = params\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n depth as number,\n draft as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","getCollectionVirtualFieldNames","stripVirtualFields","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","createResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","depth","draft","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","virtualFieldNames","config","stringify","_parseError","error","content","type","text","selectClause","warn","response","overrideResponse","result","create","collection","overrideAccess","id","errorMessage","Error","message","enabled","convertedFields","createResourceSchema","object","shape","number","int","min","max","optional","default","describe","boolean","string","registerTool","charAt","toUpperCase","slice","description","createResource","trim","inputSchema","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,QAAgB,CAAC,EACjBC,OACAC,QACAC,gBACAC;QAOA,MAAMC,UAAUb,IAAIa,OAAO;QAE3B,IAAIX,aAAa;YACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,+CAA+C,EAAEZ,iBAAiBO,SAAS,CAAC,cAAc,EAAEA,QAAQ,GAAG,IAAI;QAEhH;QAEA,IAAI;YACF,sBAAsB;YACtB,IAAIM;YACJ,IAAI;gBACFA,aAAaC,KAAKC,KAAK,CAACX;gBAExB,2DAA2D;gBAC3DS,aAAapB,4BAA4BoB;gBAEzC,MAAMG,oBAAoB1B,+BAA+BoB,QAAQO,MAAM,EAAEjB;gBACzEa,aAAatB,mBAAmBsB,YAAYG;gBAE5C,IAAIjB,aAAa;oBACfW,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEZ,eAAe,EAAE,EAAEc,KAAKI,SAAS,CAACL,aAAa;gBAEpF;YACF,E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AOkB;YACL,MAAM,EAAErD,KAAK,EAAEC,KAAK,EAAEE,cAAc,EAAED,MAAM,EAAEE,MAAM,EAAE,GAAGkD,WAAW,GAAGD;YACvE,MAAMtD,OAAOU,KAAKI,SAAS,CAACyC;YAC5B,OAAO,MAAMxD,KACXC,MACAC,OACAC,OACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAM9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAoWpB,CAAA"}
1
+ {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/mcp/tools/resource/update.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAc,SAAS,EAAE,MAAM,SAAS,CAAA;AAIpE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAU9D,eAAO,MAAM,kBAAkB,WACrB,SAAS,OACZ,cAAc,QACb,SAAS,eACF,OAAO,kBACJ,MAAM,eACT,qBAAqB,CAAC,aAAa,CAAC,UACzC,WAAW,SAuWpB,CAAA"}
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { toCamelCase } from '../../../utils/camelCase.js';
3
+ import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
3
4
  import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js';
4
5
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
5
6
  import { toolSchemas } from '../schemas.js';
@@ -16,6 +17,8 @@ export const updateResourceTool = (server, req, user, verboseLogs, collectionSlu
16
17
  parsedData = JSON.parse(data);
17
18
  // Transform point fields from object format to tuple array
18
19
  parsedData = transformPointDataToPayload(parsedData);
20
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug);
21
+ parsedData = stripVirtualFields(parsedData, virtualFieldNames);
19
22
  if (verboseLogs) {
20
23
  payload.logger.info(`[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`);
21
24
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/tools/resource/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const updateResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n id?: number | string,\n where?: string,\n draft: boolean = false,\n depth: number = 0,\n overrideLock: boolean = true,\n filePath?: string,\n overwriteExistingFiles: boolean = false,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Updating resource in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Validate that either id or where is provided\n if (!id && !where) {\n payload.logger.error('[payload-mcp] Either id or where clause must be provided')\n const response = {\n content: [\n { type: 'text' as const, text: 'Error: Either id or where clause must be provided' },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Update by ID or where clause\n if (id) {\n // Single document update\n const updateOptions = {\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating single document with ID: ${id}`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Document updated successfully in collection \"${collectionSlug}\"!\nUpdated document:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } else {\n // Multiple documents update\n const updateOptions = {\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n where: whereClause,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating multiple documents with where clause`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully updated ${docs.length} documents, ${errors.length} errors`,\n )\n }\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\nUpdated: ${docs.length} documents\nErrors: ${errors.length}\n---`\n\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\n\\`\\`\\`json\n${JSON.stringify(docs, null, 2)}\n\\`\\`\\``\n }\n\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\n\\`\\`\\`json\n${JSON.stringify(errors, null, 2)}\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(\n response,\n { docs, errors },\n req,\n ) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error updating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with update-specific parameters\n // Use .partial() to make all fields optional for partial updates\n const updateResourceSchema = z.object({\n ...convertedFields.partial().shape,\n id: z.union([z.string(), z.number()]).optional().describe('The ID of the document to update'),\n depth: z\n .number()\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to update the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n filePath: z.string().optional().describe('File path for file uploads'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n overrideLock: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether to override document locks'),\n overwriteExistingFiles: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to overwrite existing files'),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n where: z\n .string()\n .optional()\n .describe('JSON string for where clause to update multiple documents'),\n })\n\n server.registerTool(\n `update${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.updateResource.description.trim()}`,\n inputSchema: updateResourceSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n filePath,\n locale,\n overrideLock,\n overwriteExistingFiles,\n select,\n where,\n ...fieldData\n } = params\n // Convert field data back to JSON string format expected by the tool\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n id as number | string | undefined,\n where as string | undefined,\n draft as boolean,\n depth as number,\n overrideLock as boolean,\n filePath as string | undefined,\n overwriteExistingFiles as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","updateResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","id","where","draft","depth","overrideLock","filePath","overwriteExistingFiles","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","stringify","_parseError","error","response","content","type","text","overrideResponse","whereClause","selectClause","warn","updateOptions","collection","overrideAccess","result","update","bulkResult","docs","errors","length","responseText","errorMessage","Error","message","enabled","convertedFields","updateResourceSchema","object","partial","shape","union","string","number","optional","describe","default","boolean","registerTool","charAt","toUpperCase","slice","description","updateResource","trim","inputSchema","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,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,CAAC,IAAI,EACxF;YACEC,aAAa,GAAG7D,aAAa,CAACD,eAAe,EAAE8D,eAAepE,YAAYqE,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI;YAC7GC,aAAalB,qBAAqBG,KAAK;QACzC,GACA,OAAOgB;YACL,MAAM,EACJ7D,EAAE,EACFG,KAAK,EACLD,KAAK,EACLM,cAAc,EACdH,QAAQ,EACRE,MAAM,EACNH,YAAY,EACZE,sBAAsB,EACtBG,MAAM,EACNR,KAAK,EACL,GAAG6D,WACJ,GAAGD;YACJ,qEAAqE;YACrE,MAAM9D,OAAOe,KAAKE,SAAS,CAAC8C;YAC5B,OAAO,MAAMhE,KACXC,MACAC,IACAC,OACAC,OACAC,OACAC,cACAC,UACAC,wBACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../src/mcp/tools/resource/update.ts"],"sourcesContent":["import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { JSONSchema4 } from 'json-schema'\nimport type { PayloadRequest, SelectType, TypedUser } from 'payload'\n\nimport { z } from 'zod'\n\nimport type { PluginMCPServerConfig } from '../../../types.js'\n\nimport { toCamelCase } from '../../../utils/camelCase.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { toolSchemas } from '../schemas.js'\nexport const updateResourceTool = (\n server: McpServer,\n req: PayloadRequest,\n user: TypedUser,\n verboseLogs: boolean,\n collectionSlug: string,\n collections: PluginMCPServerConfig['collections'],\n schema: JSONSchema4,\n) => {\n const tool = async (\n data: string,\n id?: number | string,\n where?: string,\n draft: boolean = false,\n depth: number = 0,\n overrideLock: boolean = true,\n filePath?: string,\n overwriteExistingFiles: boolean = false,\n locale?: string,\n fallbackLocale?: string,\n select?: string,\n ): Promise<{\n content: Array<{\n text: string\n type: 'text'\n }>\n }> => {\n const payload = req.payload\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Updating resource in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n }\n\n try {\n // Parse the data JSON\n let parsedData: Record<string, unknown>\n try {\n parsedData = JSON.parse(data)\n\n // Transform point fields from object format to tuple array\n parsedData = transformPointDataToPayload(parsedData)\n\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,\n )\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid JSON data provided: ${data}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON data provided' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Validate that either id or where is provided\n if (!id && !where) {\n payload.logger.error('[payload-mcp] Either id or where clause must be provided')\n const response = {\n content: [\n { type: 'text' as const, text: 'Error: Either id or where clause must be provided' },\n ],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n\n // Parse where clause if provided\n let whereClause = {}\n if (where) {\n try {\n whereClause = JSON.parse(where)\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Using where clause: ${where}`)\n }\n } catch (_parseError) {\n payload.logger.error(`[payload-mcp] Invalid where clause JSON: ${where}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in where clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch (_parseError) {\n payload.logger.warn(`[payload-mcp] Invalid select clause JSON: ${select}`)\n const response = {\n content: [{ type: 'text' as const, text: 'Error: Invalid JSON in select clause' }],\n }\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n // Update by ID or where clause\n if (id) {\n // Single document update\n const updateOptions = {\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating single document with ID: ${id}`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Successfully updated document with ID: ${id}`)\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Document updated successfully in collection \"${collectionSlug}\"!\nUpdated document:\n\\`\\`\\`json\n${JSON.stringify(result, null, 2)}\n\\`\\`\\``,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, result, req) ||\n response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n } else {\n // Multiple documents update\n const updateOptions = {\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: false,\n overrideLock,\n req,\n user,\n where: whereClause,\n ...(filePath && { filePath }),\n ...(overwriteExistingFiles && { overwriteExistingFiles }),\n ...(locale && { locale }),\n ...(fallbackLocale && { fallbackLocale }),\n ...(selectClause && { select: selectClause }),\n }\n\n if (verboseLogs) {\n payload.logger.info(`[payload-mcp] Updating multiple documents with where clause`)\n }\n const result = await payload.update({\n ...updateOptions,\n data: parsedData,\n } as any)\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n if (verboseLogs) {\n payload.logger.info(\n `[payload-mcp] Successfully updated ${docs.length} documents, ${errors.length} errors`,\n )\n }\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\nUpdated: ${docs.length} documents\nErrors: ${errors.length}\n---`\n\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\n\\`\\`\\`json\n${JSON.stringify(docs, null, 2)}\n\\`\\`\\``\n }\n\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\n\\`\\`\\`json\n${JSON.stringify(errors, null, 2)}\n\\`\\`\\``\n }\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: responseText,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(\n response,\n { docs, errors },\n req,\n ) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n payload.logger.error(\n `[payload-mcp] Error updating resource in ${collectionSlug}: ${errorMessage}`,\n )\n\n const response = {\n content: [\n {\n type: 'text' as const,\n text: `Error updating resource in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n\n return (collections?.[collectionSlug]?.overrideResponse?.(response, {}, req) || response) as {\n content: Array<{\n text: string\n type: 'text'\n }>\n }\n }\n }\n\n if (collections?.[collectionSlug]?.enabled) {\n const convertedFields = convertCollectionSchemaToZod(schema)\n\n // Create a new schema that combines the converted fields with update-specific parameters\n // Use .partial() to make all fields optional for partial updates\n const updateResourceSchema = z.object({\n ...convertedFields.partial().shape,\n id: z.union([z.string(), z.number()]).optional().describe('The ID of the document to update'),\n depth: z\n .number()\n .optional()\n .default(0)\n .describe('How many levels deep to populate relationships'),\n draft: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to update the document as a draft'),\n fallbackLocale: z\n .string()\n .optional()\n .describe('Optional: fallback locale code to use when requested locale is not available'),\n filePath: z.string().optional().describe('File path for file uploads'),\n locale: z\n .string()\n .optional()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n ),\n overrideLock: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether to override document locks'),\n overwriteExistingFiles: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to overwrite existing files'),\n select: z\n .string()\n .optional()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n ),\n where: z\n .string()\n .optional()\n .describe('JSON string for where clause to update multiple documents'),\n })\n\n server.registerTool(\n `update${collectionSlug.charAt(0).toUpperCase() + toCamelCase(collectionSlug).slice(1)}`,\n {\n description: `${collections?.[collectionSlug]?.description || toolSchemas.updateResource.description.trim()}`,\n inputSchema: updateResourceSchema.shape,\n },\n async (params: Record<string, unknown>) => {\n const {\n id,\n depth,\n draft,\n fallbackLocale,\n filePath,\n locale,\n overrideLock,\n overwriteExistingFiles,\n select,\n where,\n ...fieldData\n } = params\n // Convert field data back to JSON string format expected by the tool\n const data = JSON.stringify(fieldData)\n return await tool(\n data,\n id as number | string | undefined,\n where as string | undefined,\n draft as boolean,\n depth as number,\n overrideLock as boolean,\n filePath as string | undefined,\n overwriteExistingFiles as boolean,\n locale as string | undefined,\n fallbackLocale as string | undefined,\n select as string | undefined,\n )\n },\n )\n }\n}\n"],"names":["z","toCamelCase","getCollectionVirtualFieldNames","stripVirtualFields","convertCollectionSchemaToZod","transformPointDataToPayload","toolSchemas","updateResourceTool","server","req","user","verboseLogs","collectionSlug","collections","schema","tool","data","id","where","draft","depth","overrideLock","filePath","overwriteExistingFiles","locale","fallbackLocale","select","payload","logger","info","parsedData","JSON","parse","virtualFieldNames","config","stringify","_parseError","error","response","content","type","text","overrideResponse","whereClause","selectClause","warn","updateOptions","collection","overrideAccess","result","update","bulkResult","docs","errors","length","responseText","errorMessage","Error","message","enabled","convertedFields","updateResourceSchema","object","partial","shape","union","string","number","optional","describe","default","boolean","registerTool","charAt","toUpperCase","slice","description","updateResource","trim","inputSchema","params","fieldData"],"mappings":"AAIA,SAASA,CAAC,QAAQ,MAAK;AAIvB,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gBAAe;AAC3C,OAAO,MAAMC,qBAAqB,CAChCC,QACAC,KACAC,MACAC,aACAC,gBACAC,aACAC;IAEA,MAAMC,OAAO,OACXC,MACAC,IACAC,OACAC,QAAiB,KAAK,EACtBC,QAAgB,CAAC,EACjBC,eAAwB,IAAI,EAC5BC,UACAC,yBAAkC,KAAK,EACvCC,QACAC,gBACAC;QAOA,MAAMC,UAAUlB,IAAIkB,OAAO;QAE3B,IAAIhB,aAAa;YACfgB,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,+CAA+C,EAAEjB,iBAAiBK,KAAK,CAAC,UAAU,EAAEA,IAAI,GAAG,qBAAqB,SAAS,EAAEE,QAAQK,SAAS,CAAC,UAAU,EAAEA,QAAQ,GAAG,IAAI;QAE7K;QAEA,IAAI;YACF,sBAAsB;YACtB,IAAIM;YACJ,IAAI;gBACFA,aAAaC,KAAKC,KAAK,CAAChB;gBAExB,2DAA2D;gBAC3Dc,aAAazB,4BAA4ByB;gBAEzC,MAAMG,oBAAoB/B,+BAA+ByB,QAAQO,MAAM,EAAEtB;gBACzEkB,aAAa3B,mBAAmB2B,YAAYG;gBAE5C,IAAItB,aAAa;oBACfgB,QAAQC,MAAM,CAACC,IAAI,CACjB,CAAC,8BAA8B,EAAEjB,eAAe,EAAE,EAAEmB,KAAKI,SAAS,CAACL,aAAa;gBAEpF;YACF,EAAE,OAAOM,aAAa;gBACpBT,QAAQC,MAAM,CAACS,KAAK,CAAC,CAAC,0CAA0C,EAAEr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GACRE,OAAO,CAAC,OACRD,QAAQ,CAAC;YACZ3C,QAAQ1B,EACLkE,MAAM,GACNE,QAAQ,GACRC,QAAQ,CACP;YAEJnD,OAAOlB,EACJkE,MAAM,GACNE,QAAQ,GACRC,QAAQ,CAAC;QACd;QAEA7D,OAAOgE,YAAY,CACjB,CAAC,MAAM,EAAE5D,eAAe6D,MAAM,CAAC,GAAGC,WAAW,KAAKzE,YAAYW,gBAAgB+D,KAAK,CAAC,IAAI,EACxF;YACEC,aAAa,GAAG/D,aAAa,CAACD,eAAe,EAAEgE,eAAetE,YAAYuE,cAAc,CAACD,WAAW,CAACE,IAAI,IAAI;YAC7GC,aAAalB,qBAAqBG,KAAK;QACzC,GACA,OAAOgB;YACL,MAAM,EACJ/D,EAAE,EACFG,KAAK,EACLD,KAAK,EACLM,cAAc,EACdH,QAAQ,EACRE,MAAM,EACNH,YAAY,EACZE,sBAAsB,EACtBG,MAAM,EACNR,KAAK,EACL,GAAG+D,WACJ,GAAGD;YACJ,qEAAqE;YACrE,MAAMhE,OAAOe,KAAKI,SAAS,CAAC8C;YAC5B,OAAO,MAAMlE,KACXC,MACAC,IACAC,OACAC,OACAC,OACAC,cACAC,UACAC,wBACAC,QACAC,gBACAC;QAEJ;IAEJ;AACF,EAAC"}
@@ -34,8 +34,8 @@ export declare const toolSchemas: {
34
34
  where: z.ZodOptional<z.ZodString>;
35
35
  }, "strip", z.ZodTypeAny, {
36
36
  depth: number;
37
- limit: number;
38
37
  page: number;
38
+ limit: number;
39
39
  locale?: string | undefined;
40
40
  select?: string | undefined;
41
41
  sort?: string | undefined;
@@ -51,9 +51,9 @@ export declare const toolSchemas: {
51
51
  draft?: boolean | undefined;
52
52
  where?: string | undefined;
53
53
  id?: string | number | undefined;
54
+ page?: number | undefined;
54
55
  fallbackLocale?: string | undefined;
55
56
  limit?: number | undefined;
56
- page?: number | undefined;
57
57
  }>;
58
58
  };
59
59
  createResource: {
@@ -0,0 +1,14 @@
1
+ import type { SanitizedConfig } from 'payload';
2
+ /**
3
+ * Returns the names of all top-level virtual fields for a given collection slug.
4
+ */
5
+ export declare function getCollectionVirtualFieldNames(config: SanitizedConfig, slug: string): string[];
6
+ /**
7
+ * Returns the names of all top-level virtual fields for a given global slug.
8
+ */
9
+ export declare function getGlobalVirtualFieldNames(config: SanitizedConfig, slug: string): string[];
10
+ /**
11
+ * Strips virtual field values from a data object given a list of virtual field names.
12
+ */
13
+ export declare function stripVirtualFields(data: Record<string, unknown>, virtualFieldNames: string[]): Record<string, unknown>;
14
+ //# sourceMappingURL=getVirtualFieldNames.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getVirtualFieldNames.d.ts","sourceRoot":"","sources":["../../src/utils/getVirtualFieldNames.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAI9C;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAU9F;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAU1F;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,iBAAiB,EAAE,MAAM,EAAE,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB"}
@@ -0,0 +1,35 @@
1
+ import { fieldIsVirtual } from 'payload/shared';
2
+ /**
3
+ * Returns the names of all top-level virtual fields for a given collection slug.
4
+ */ export function getCollectionVirtualFieldNames(config, slug) {
5
+ const collection = config.collections.find((c)=>c.slug === slug);
6
+ if (!collection) {
7
+ return [];
8
+ }
9
+ return collection.flattenedFields.filter((field)=>'name' in field && fieldIsVirtual(field)).map((field)=>field.name);
10
+ }
11
+ /**
12
+ * Returns the names of all top-level virtual fields for a given global slug.
13
+ */ export function getGlobalVirtualFieldNames(config, slug) {
14
+ const global = config.globals.find((g)=>g.slug === slug);
15
+ if (!global) {
16
+ return [];
17
+ }
18
+ return global.flattenedFields.filter((field)=>'name' in field && fieldIsVirtual(field)).map((field)=>field.name);
19
+ }
20
+ /**
21
+ * Strips virtual field values from a data object given a list of virtual field names.
22
+ */ export function stripVirtualFields(data, virtualFieldNames) {
23
+ if (virtualFieldNames.length === 0) {
24
+ return data;
25
+ }
26
+ const stripped = {
27
+ ...data
28
+ };
29
+ for (const name of virtualFieldNames){
30
+ delete stripped[name];
31
+ }
32
+ return stripped;
33
+ }
34
+
35
+ //# sourceMappingURL=getVirtualFieldNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/getVirtualFieldNames.ts"],"sourcesContent":["import type { SanitizedConfig } from 'payload'\n\nimport { fieldIsVirtual } from 'payload/shared'\n\n/**\n * Returns the names of all top-level virtual fields for a given collection slug.\n */\nexport function getCollectionVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {\n const collection = config.collections.find((c) => c.slug === slug)\n\n if (!collection) {\n return []\n }\n\n return collection.flattenedFields\n .filter((field) => 'name' in field && fieldIsVirtual(field))\n .map((field) => (field as { name: string }).name)\n}\n\n/**\n * Returns the names of all top-level virtual fields for a given global slug.\n */\nexport function getGlobalVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {\n const global = config.globals.find((g) => g.slug === slug)\n\n if (!global) {\n return []\n }\n\n return global.flattenedFields\n .filter((field) => 'name' in field && fieldIsVirtual(field))\n .map((field) => (field as { name: string }).name)\n}\n\n/**\n * Strips virtual field values from a data object given a list of virtual field names.\n */\nexport function stripVirtualFields(\n data: Record<string, unknown>,\n virtualFieldNames: string[],\n): Record<string, unknown> {\n if (virtualFieldNames.length === 0) {\n return data\n }\n\n const stripped = { ...data }\n\n for (const name of virtualFieldNames) {\n delete stripped[name]\n }\n\n return stripped\n}\n"],"names":["fieldIsVirtual","getCollectionVirtualFieldNames","config","slug","collection","collections","find","c","flattenedFields","filter","field","map","name","getGlobalVirtualFieldNames","global","globals","g","stripVirtualFields","data","virtualFieldNames","length","stripped"],"mappings":"AAEA,SAASA,cAAc,QAAQ,iBAAgB;AAE/C;;CAEC,GACD,OAAO,SAASC,+BAA+BC,MAAuB,EAAEC,IAAY;IAClF,MAAMC,aAAaF,OAAOG,WAAW,CAACC,IAAI,CAAC,CAACC,IAAMA,EAAEJ,IAAI,KAAKA;IAE7D,IAAI,CAACC,YAAY;QACf,OAAO,EAAE;IACX;IAEA,OAAOA,WAAWI,eAAe,CAC9BC,MAAM,CAAC,CAACC,QAAU,UAAUA,SAASV,eAAeU,QACpDC,GAAG,CAAC,CAACD,QAAU,AAACA,MAA2BE,IAAI;AACpD;AAEA;;CAEC,GACD,OAAO,SAASC,2BAA2BX,MAAuB,EAAEC,IAAY;IAC9E,MAAMW,SAASZ,OAAOa,OAAO,CAACT,IAAI,CAAC,CAACU,IAAMA,EAAEb,IAAI,KAAKA;IAErD,IAAI,CAACW,QAAQ;QACX,OAAO,EAAE;IACX;IAEA,OAAOA,OAAON,eAAe,CAC1BC,MAAM,CAAC,CAACC,QAAU,UAAUA,SAASV,eAAeU,QACpDC,GAAG,CAAC,CAACD,QAAU,AAACA,MAA2BE,IAAI;AACpD;AAEA;;CAEC,GACD,OAAO,SAASK,mBACdC,IAA6B,EAC7BC,iBAA2B;IAE3B,IAAIA,kBAAkBC,MAAM,KAAK,GAAG;QAClC,OAAOF;IACT;IAEA,MAAMG,WAAW;QAAE,GAAGH,IAAI;IAAC;IAE3B,KAAK,MAAMN,QAAQO,kBAAmB;QACpC,OAAOE,QAAQ,CAACT,KAAK;IACvB;IAEA,OAAOS;AACT"}
@@ -0,0 +1,7 @@
1
+ import type { JSONSchema4 } from 'json-schema';
2
+ /**
3
+ * Removes virtual fields from a JSON Schema by name so they don't appear
4
+ * in the generated MCP tool input schema.
5
+ */
6
+ export declare function removeVirtualFieldsFromSchema(schema: JSONSchema4, virtualFieldNames: string[]): JSONSchema4;
7
+ //# sourceMappingURL=removeVirtualFieldsFromSchema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"removeVirtualFieldsFromSchema.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAE9C;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,MAAM,EAAE,WAAW,EACnB,iBAAiB,EAAE,MAAM,EAAE,GAC1B,WAAW,CAiBb"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Removes virtual fields from a JSON Schema by name so they don't appear
3
+ * in the generated MCP tool input schema.
4
+ */ export function removeVirtualFieldsFromSchema(schema, virtualFieldNames) {
5
+ if (virtualFieldNames.length === 0) {
6
+ return schema;
7
+ }
8
+ for (const name of virtualFieldNames){
9
+ delete schema?.properties?.[name];
10
+ }
11
+ if (Array.isArray(schema.required)) {
12
+ schema.required = schema.required.filter((field)=>!virtualFieldNames.includes(field));
13
+ if (schema.required.length === 0) {
14
+ delete schema.required;
15
+ }
16
+ }
17
+ return schema;
18
+ }
19
+
20
+ //# sourceMappingURL=removeVirtualFieldsFromSchema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts"],"sourcesContent":["import type { JSONSchema4 } from 'json-schema'\n\n/**\n * Removes virtual fields from a JSON Schema by name so they don't appear\n * in the generated MCP tool input schema.\n */\nexport function removeVirtualFieldsFromSchema(\n schema: JSONSchema4,\n virtualFieldNames: string[],\n): JSONSchema4 {\n if (virtualFieldNames.length === 0) {\n return schema\n }\n\n for (const name of virtualFieldNames) {\n delete schema?.properties?.[name]\n }\n\n if (Array.isArray(schema.required)) {\n schema.required = schema.required.filter((field) => !virtualFieldNames.includes(field))\n if (schema.required.length === 0) {\n delete schema.required\n }\n }\n\n return schema\n}\n"],"names":["removeVirtualFieldsFromSchema","schema","virtualFieldNames","length","name","properties","Array","isArray","required","filter","field","includes"],"mappings":"AAEA;;;CAGC,GACD,OAAO,SAASA,8BACdC,MAAmB,EACnBC,iBAA2B;IAE3B,IAAIA,kBAAkBC,MAAM,KAAK,GAAG;QAClC,OAAOF;IACT;IAEA,KAAK,MAAMG,QAAQF,kBAAmB;QACpC,OAAOD,QAAQI,YAAY,CAACD,KAAK;IACnC;IAEA,IAAIE,MAAMC,OAAO,CAACN,OAAOO,QAAQ,GAAG;QAClCP,OAAOO,QAAQ,GAAGP,OAAOO,QAAQ,CAACC,MAAM,CAAC,CAACC,QAAU,CAACR,kBAAkBS,QAAQ,CAACD;QAChF,IAAIT,OAAOO,QAAQ,CAACL,MAAM,KAAK,GAAG;YAChC,OAAOF,OAAOO,QAAQ;QACxB;IACF;IAEA,OAAOP;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "3.78.0-canary.0",
3
+ "version": "3.78.0-canary.1",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "plugin",
@@ -45,10 +45,10 @@
45
45
  },
46
46
  "devDependencies": {
47
47
  "@payloadcms/eslint-config": "3.28.0",
48
- "payload": "3.78.0-canary.0"
48
+ "payload": "3.78.0-canary.1"
49
49
  },
50
50
  "peerDependencies": {
51
- "payload": "3.78.0-canary.0"
51
+ "payload": "3.78.0-canary.1"
52
52
  },
53
53
  "homepage:": "https://payloadcms.com",
54
54
  "scripts": {
@@ -8,6 +8,11 @@ import type { MCPAccessSettings, PluginMCPServerConfig } from '../types.js'
8
8
 
9
9
  import { toCamelCase } from '../utils/camelCase.js'
10
10
  import { getEnabledSlugs } from '../utils/getEnabledSlugs.js'
11
+ import {
12
+ getCollectionVirtualFieldNames,
13
+ getGlobalVirtualFieldNames,
14
+ } from '../utils/getVirtualFieldNames.js'
15
+ import { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js'
11
16
  import { registerTool } from './registerTool.js'
12
17
 
13
18
  // Tools
@@ -107,7 +112,16 @@ export const getMCPHandler = (
107
112
  // Collection Operation Tools
108
113
  enabledCollectionSlugs.forEach((enabledCollectionSlug) => {
109
114
  try {
110
- const schema = configSchema.definitions?.[enabledCollectionSlug] as JSONSchema4
115
+ const rawSchema = configSchema.definitions?.[enabledCollectionSlug] as JSONSchema4
116
+
117
+ const virtualFieldNames = getCollectionVirtualFieldNames(
118
+ payload.config,
119
+ enabledCollectionSlug,
120
+ )
121
+ const schema = removeVirtualFieldsFromSchema(
122
+ JSON.parse(JSON.stringify(rawSchema)) as JSONSchema4,
123
+ virtualFieldNames,
124
+ )
111
125
 
112
126
  const toolCapabilities = mcpAccessSettings?.[
113
127
  `${toCamelCase(enabledCollectionSlug)}`
@@ -200,7 +214,13 @@ export const getMCPHandler = (
200
214
 
201
215
  enabledGlobalSlugs.forEach((enabledGlobalSlug) => {
202
216
  try {
203
- const schema = configSchema.definitions?.[enabledGlobalSlug] as JSONSchema4
217
+ const rawSchema = configSchema.definitions?.[enabledGlobalSlug] as JSONSchema4
218
+
219
+ const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, enabledGlobalSlug)
220
+ const schema = removeVirtualFieldsFromSchema(
221
+ JSON.parse(JSON.stringify(rawSchema)) as JSONSchema4,
222
+ virtualFieldNames,
223
+ )
204
224
 
205
225
  const toolCapabilities = mcpAccessSettings?.[
206
226
  `${toCamelCase(enabledGlobalSlug)}`
@@ -7,6 +7,10 @@ import { z } from 'zod'
7
7
  import type { PluginMCPServerConfig } from '../../../types.js'
8
8
 
9
9
  import { toCamelCase } from '../../../utils/camelCase.js'
10
+ import {
11
+ getGlobalVirtualFieldNames,
12
+ stripVirtualFields,
13
+ } from '../../../utils/getVirtualFieldNames.js'
10
14
  import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'
11
15
  import { toolSchemas } from '../schemas.js'
12
16
 
@@ -45,6 +49,10 @@ export const updateGlobalTool = (
45
49
  let parsedData: Record<string, unknown>
46
50
  try {
47
51
  parsedData = JSON.parse(data)
52
+
53
+ const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)
54
+ parsedData = stripVirtualFields(parsedData, virtualFieldNames)
55
+
48
56
  if (verboseLogs) {
49
57
  payload.logger.info(
50
58
  `[payload-mcp] Parsed data for ${globalSlug}: ${JSON.stringify(parsedData)}`,
@@ -7,6 +7,10 @@ import { z } from 'zod'
7
7
  import type { PluginMCPServerConfig } from '../../../types.js'
8
8
 
9
9
  import { toCamelCase } from '../../../utils/camelCase.js'
10
+ import {
11
+ getCollectionVirtualFieldNames,
12
+ stripVirtualFields,
13
+ } from '../../../utils/getVirtualFieldNames.js'
10
14
  import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'
11
15
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
12
16
  import { toolSchemas } from '../schemas.js'
@@ -49,6 +53,9 @@ export const createResourceTool = (
49
53
  // Transform point fields from object format to tuple array
50
54
  parsedData = transformPointDataToPayload(parsedData)
51
55
 
56
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)
57
+ parsedData = stripVirtualFields(parsedData, virtualFieldNames)
58
+
52
59
  if (verboseLogs) {
53
60
  payload.logger.info(
54
61
  `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,
@@ -7,6 +7,10 @@ import { z } from 'zod'
7
7
  import type { PluginMCPServerConfig } from '../../../types.js'
8
8
 
9
9
  import { toCamelCase } from '../../../utils/camelCase.js'
10
+ import {
11
+ getCollectionVirtualFieldNames,
12
+ stripVirtualFields,
13
+ } from '../../../utils/getVirtualFieldNames.js'
10
14
  import { convertCollectionSchemaToZod } from '../../../utils/schemaConversion/convertCollectionSchemaToZod.js'
11
15
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'
12
16
  import { toolSchemas } from '../schemas.js'
@@ -54,6 +58,9 @@ export const updateResourceTool = (
54
58
  // Transform point fields from object format to tuple array
55
59
  parsedData = transformPointDataToPayload(parsedData)
56
60
 
61
+ const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)
62
+ parsedData = stripVirtualFields(parsedData, virtualFieldNames)
63
+
57
64
  if (verboseLogs) {
58
65
  payload.logger.info(
59
66
  `[payload-mcp] Parsed data for ${collectionSlug}: ${JSON.stringify(parsedData)}`,
@@ -0,0 +1,53 @@
1
+ import type { SanitizedConfig } from 'payload'
2
+
3
+ import { fieldIsVirtual } from 'payload/shared'
4
+
5
+ /**
6
+ * Returns the names of all top-level virtual fields for a given collection slug.
7
+ */
8
+ export function getCollectionVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {
9
+ const collection = config.collections.find((c) => c.slug === slug)
10
+
11
+ if (!collection) {
12
+ return []
13
+ }
14
+
15
+ return collection.flattenedFields
16
+ .filter((field) => 'name' in field && fieldIsVirtual(field))
17
+ .map((field) => (field as { name: string }).name)
18
+ }
19
+
20
+ /**
21
+ * Returns the names of all top-level virtual fields for a given global slug.
22
+ */
23
+ export function getGlobalVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {
24
+ const global = config.globals.find((g) => g.slug === slug)
25
+
26
+ if (!global) {
27
+ return []
28
+ }
29
+
30
+ return global.flattenedFields
31
+ .filter((field) => 'name' in field && fieldIsVirtual(field))
32
+ .map((field) => (field as { name: string }).name)
33
+ }
34
+
35
+ /**
36
+ * Strips virtual field values from a data object given a list of virtual field names.
37
+ */
38
+ export function stripVirtualFields(
39
+ data: Record<string, unknown>,
40
+ virtualFieldNames: string[],
41
+ ): Record<string, unknown> {
42
+ if (virtualFieldNames.length === 0) {
43
+ return data
44
+ }
45
+
46
+ const stripped = { ...data }
47
+
48
+ for (const name of virtualFieldNames) {
49
+ delete stripped[name]
50
+ }
51
+
52
+ return stripped
53
+ }
@@ -0,0 +1,27 @@
1
+ import type { JSONSchema4 } from 'json-schema'
2
+
3
+ /**
4
+ * Removes virtual fields from a JSON Schema by name so they don't appear
5
+ * in the generated MCP tool input schema.
6
+ */
7
+ export function removeVirtualFieldsFromSchema(
8
+ schema: JSONSchema4,
9
+ virtualFieldNames: string[],
10
+ ): JSONSchema4 {
11
+ if (virtualFieldNames.length === 0) {
12
+ return schema
13
+ }
14
+
15
+ for (const name of virtualFieldNames) {
16
+ delete schema?.properties?.[name]
17
+ }
18
+
19
+ if (Array.isArray(schema.required)) {
20
+ schema.required = schema.required.filter((field) => !virtualFieldNames.includes(field))
21
+ if (schema.required.length === 0) {
22
+ delete schema.required
23
+ }
24
+ }
25
+
26
+ return schema
27
+ }