@payloadcms/plugin-mcp 4.0.0-internal.5f0cd13 → 4.0.0-internal.a0ef1b8

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 (57) hide show
  1. package/dist/@types/assets.d.js +2 -0
  2. package/dist/@types/assets.d.js.map +1 -0
  3. package/dist/collection/index.d.ts.map +1 -1
  4. package/dist/collection/index.js +2 -1
  5. package/dist/collection/index.js.map +1 -1
  6. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  7. package/dist/mcp/buildMcpServer.js +17 -10
  8. package/dist/mcp/buildMcpServer.js.map +1 -1
  9. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  10. package/dist/mcp/builtin/collections/createTool.js +12 -8
  11. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  12. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  13. package/dist/mcp/builtin/collections/updateTool.js +21 -17
  14. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  15. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  16. package/dist/mcp/builtin/globals/updateTool.js +13 -9
  17. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  18. package/dist/utils/schemaConversion/buildToolInput.d.ts +29 -0
  19. package/dist/utils/schemaConversion/buildToolInput.d.ts.map +1 -0
  20. package/dist/utils/schemaConversion/buildToolInput.js +51 -0
  21. package/dist/utils/schemaConversion/buildToolInput.js.map +1 -0
  22. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +15 -0
  23. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -0
  24. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +464 -0
  25. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -0
  26. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +158 -0
  27. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -0
  28. package/package.json +6 -6
  29. package/src/@types/assets.d.ts +3 -0
  30. package/src/collection/index.ts +1 -0
  31. package/src/mcp/buildMcpServer.ts +19 -14
  32. package/src/mcp/builtin/collections/createTool.ts +37 -37
  33. package/src/mcp/builtin/collections/updateTool.ts +54 -49
  34. package/src/mcp/builtin/globals/updateTool.ts +35 -33
  35. package/src/utils/schemaConversion/buildToolInput.ts +68 -0
  36. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +103 -0
  37. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +529 -0
  38. package/dist/utils/schemaConversion/prepareCollectionSchema.d.ts +0 -7
  39. package/dist/utils/schemaConversion/prepareCollectionSchema.d.ts.map +0 -1
  40. package/dist/utils/schemaConversion/prepareCollectionSchema.js +0 -37
  41. package/dist/utils/schemaConversion/prepareCollectionSchema.js.map +0 -1
  42. package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts +0 -13
  43. package/dist/utils/schemaConversion/sanitizeJsonSchema.d.ts.map +0 -1
  44. package/dist/utils/schemaConversion/sanitizeJsonSchema.js +0 -56
  45. package/dist/utils/schemaConversion/sanitizeJsonSchema.js.map +0 -1
  46. package/dist/utils/schemaConversion/simplifyRelationshipFields.d.ts +0 -20
  47. package/dist/utils/schemaConversion/simplifyRelationshipFields.d.ts.map +0 -1
  48. package/dist/utils/schemaConversion/simplifyRelationshipFields.js +0 -56
  49. package/dist/utils/schemaConversion/simplifyRelationshipFields.js.map +0 -1
  50. package/dist/utils/schemaConversion/transformPointFields.d.ts +0 -3
  51. package/dist/utils/schemaConversion/transformPointFields.d.ts.map +0 -1
  52. package/dist/utils/schemaConversion/transformPointFields.js +0 -57
  53. package/dist/utils/schemaConversion/transformPointFields.js.map +0 -1
  54. package/src/utils/schemaConversion/prepareCollectionSchema.ts +0 -39
  55. package/src/utils/schemaConversion/sanitizeJsonSchema.ts +0 -62
  56. package/src/utils/schemaConversion/simplifyRelationshipFields.ts +0 -70
  57. package/src/utils/schemaConversion/transformPointFields.ts +0 -56
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=assets.d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/@types/assets.d.ts"],"names":[],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/collection/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA;AAI3D,eAAO,MAAM,oBAAoB,GAAI,mBAElC;IACD,YAAY,EAAE,wBAAwB,CAAA;CACvC,KAAG,gBAoDH,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/collection/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAA;AAI3D,eAAO,MAAM,oBAAoB,GAAI,mBAElC;IACD,YAAY,EAAE,wBAAwB,CAAA;CACvC,KAAG,gBAqDH,CAAA"}
@@ -51,7 +51,8 @@ export const getAPIKeysCollection = ({ pluginConfig })=>{
51
51
  labels: {
52
52
  plural: 'API Keys',
53
53
  singular: 'API Key'
54
- }
54
+ },
55
+ versions: false
55
56
  };
56
57
  return pluginConfig.overrideApiKeyCollection ? pluginConfig.overrideApiKeyCollection(collection) : collection;
57
58
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/collection/index.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { SanitizedMCPPluginConfig } from '../types.js'\n\nimport { getAccessField } from './getAccessField.js'\n\nexport const getAPIKeysCollection = ({\n pluginConfig,\n}: {\n pluginConfig: SanitizedMCPPluginConfig\n}): CollectionConfig => {\n const collection: CollectionConfig = {\n slug: 'payload-mcp-api-keys',\n admin: {\n description:\n 'API keys control which collections, resources, tools, and prompts MCP clients can access',\n group: 'MCP',\n useAsTitle: 'label',\n },\n auth: {\n disableLocalStrategy: true,\n useAPIKey: true,\n },\n fields: [\n {\n name: 'user',\n type: 'relationship',\n admin: { description: 'The user that the API key is associated with.' },\n relationTo: pluginConfig.userCollection,\n required: true,\n },\n {\n name: 'label',\n type: 'text',\n admin: { description: 'A useful label for the API key.' },\n },\n {\n name: 'description',\n type: 'text',\n admin: { description: 'The purpose of the API key.' },\n },\n {\n name: 'overrideAccess',\n type: 'checkbox',\n admin: {\n description:\n 'When checked, this key bypasses Payload access control on every operation it performs. Leave unchecked unless you have a specific reason.',\n },\n defaultValue: false,\n label: 'Override access control',\n },\n getAccessField({ pluginConfig }),\n ],\n labels: {\n plural: 'API Keys',\n singular: 'API Key',\n },\n }\n\n return pluginConfig.overrideApiKeyCollection\n ? pluginConfig.overrideApiKeyCollection(collection)\n : collection\n}\n"],"names":["getAccessField","getAPIKeysCollection","pluginConfig","collection","slug","admin","description","group","useAsTitle","auth","disableLocalStrategy","useAPIKey","fields","name","type","relationTo","userCollection","required","defaultValue","label","labels","plural","singular","overrideApiKeyCollection"],"mappings":"AAIA,SAASA,cAAc,QAAQ,sBAAqB;AAEpD,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,YAAY,EAGb;IACC,MAAMC,aAA+B;QACnCC,MAAM;QACNC,OAAO;YACLC,aACE;YACFC,OAAO;YACPC,YAAY;QACd;QACAC,MAAM;YACJC,sBAAsB;YACtBC,WAAW;QACb;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBAAEC,aAAa;gBAAgD;gBACtES,YAAYb,aAAac,cAAc;gBACvCC,UAAU;YACZ;YACA;gBACEJ,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBAAEC,aAAa;gBAAkC;YAC1D;YACA;gBACEO,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBAAEC,aAAa;gBAA8B;YACtD;YACA;gBACEO,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBACLC,aACE;gBACJ;gBACAY,cAAc;gBACdC,OAAO;YACT;YACAnB,eAAe;gBAAEE;YAAa;SAC/B;QACDkB,QAAQ;YACNC,QAAQ;YACRC,UAAU;QACZ;IACF;IAEA,OAAOpB,aAAaqB,wBAAwB,GACxCrB,aAAaqB,wBAAwB,CAACpB,cACtCA;AACN,EAAC"}
1
+ {"version":3,"sources":["../../src/collection/index.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { SanitizedMCPPluginConfig } from '../types.js'\n\nimport { getAccessField } from './getAccessField.js'\n\nexport const getAPIKeysCollection = ({\n pluginConfig,\n}: {\n pluginConfig: SanitizedMCPPluginConfig\n}): CollectionConfig => {\n const collection: CollectionConfig = {\n slug: 'payload-mcp-api-keys',\n admin: {\n description:\n 'API keys control which collections, resources, tools, and prompts MCP clients can access',\n group: 'MCP',\n useAsTitle: 'label',\n },\n auth: {\n disableLocalStrategy: true,\n useAPIKey: true,\n },\n fields: [\n {\n name: 'user',\n type: 'relationship',\n admin: { description: 'The user that the API key is associated with.' },\n relationTo: pluginConfig.userCollection,\n required: true,\n },\n {\n name: 'label',\n type: 'text',\n admin: { description: 'A useful label for the API key.' },\n },\n {\n name: 'description',\n type: 'text',\n admin: { description: 'The purpose of the API key.' },\n },\n {\n name: 'overrideAccess',\n type: 'checkbox',\n admin: {\n description:\n 'When checked, this key bypasses Payload access control on every operation it performs. Leave unchecked unless you have a specific reason.',\n },\n defaultValue: false,\n label: 'Override access control',\n },\n getAccessField({ pluginConfig }),\n ],\n labels: {\n plural: 'API Keys',\n singular: 'API Key',\n },\n versions: false,\n }\n\n return pluginConfig.overrideApiKeyCollection\n ? pluginConfig.overrideApiKeyCollection(collection)\n : collection\n}\n"],"names":["getAccessField","getAPIKeysCollection","pluginConfig","collection","slug","admin","description","group","useAsTitle","auth","disableLocalStrategy","useAPIKey","fields","name","type","relationTo","userCollection","required","defaultValue","label","labels","plural","singular","versions","overrideApiKeyCollection"],"mappings":"AAIA,SAASA,cAAc,QAAQ,sBAAqB;AAEpD,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,YAAY,EAGb;IACC,MAAMC,aAA+B;QACnCC,MAAM;QACNC,OAAO;YACLC,aACE;YACFC,OAAO;YACPC,YAAY;QACd;QACAC,MAAM;YACJC,sBAAsB;YACtBC,WAAW;QACb;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBAAEC,aAAa;gBAAgD;gBACtES,YAAYb,aAAac,cAAc;gBACvCC,UAAU;YACZ;YACA;gBACEJ,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBAAEC,aAAa;gBAAkC;YAC1D;YACA;gBACEO,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBAAEC,aAAa;gBAA8B;YACtD;YACA;gBACEO,MAAM;gBACNC,MAAM;gBACNT,OAAO;oBACLC,aACE;gBACJ;gBACAY,cAAc;gBACdC,OAAO;YACT;YACAnB,eAAe;gBAAEE;YAAa;SAC/B;QACDkB,QAAQ;YACNC,QAAQ;YACRC,UAAU;QACZ;QACAC,UAAU;IACZ;IAEA,OAAOrB,aAAasB,wBAAwB,GACxCtB,aAAasB,wBAAwB,CAACrB,cACtCA;AACN,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAAgC,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AAE3E,OAAO,KAAK,EACV,aAAa,EAIb,wBAAwB,EACzB,MAAM,aAAa,CAAA;AAiBpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,uCAI5B;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SAmLH,CAAA"}
1
+ {"version":3,"file":"buildMcpServer.d.ts","sourceRoot":"","sources":["../../src/mcp/buildMcpServer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAsB,MAAM,8BAA8B,CAAA;AAC5E,OAAO,EAA0C,KAAK,cAAc,EAAE,MAAM,SAAS,CAAA;AAErF,OAAO,KAAK,EACV,aAAa,EAIb,wBAAwB,EACzB,MAAM,aAAa,CAAA;AAiBpB;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,uCAI5B;IACD,aAAa,EAAE,aAAa,CAAA;IAC5B,YAAY,EAAE,wBAAwB,CAAA;IACtC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,SAwLH,CAAA"}
@@ -1,5 +1,5 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
- import { APIError, configToJSONSchema } from 'payload';
2
+ import { APIError, entityToStandaloneJSONSchema } from 'payload';
3
3
  import { toCamelCase } from '../utils/camelCase.js';
4
4
  import { getLogger } from '../utils/getLogger.js';
5
5
  import { getCollectionVirtualFieldNames, getGlobalVirtualFieldNames } from '../utils/getVirtualFieldNames.js';
@@ -36,9 +36,6 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
36
36
  const { doc: _doc, ...rest } = overridden;
37
37
  return rest;
38
38
  };
39
- const { jsonSchema: configSchema } = configToJSONSchema(req.payload.config, req.payload.db.defaultIDType, req.i18n, {
40
- forceInlineBlocks: true
41
- });
42
39
  try {
43
40
  for (const item of authorizedMCP.items){
44
41
  switch(item.type){
@@ -48,11 +45,16 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
48
45
  const name = wireName(item.key, item.collectionSlug);
49
46
  let inputSchema = tool.input;
50
47
  if (typeof inputSchema === 'function') {
51
- const raw = configSchema.definitions?.[item.collectionSlug];
52
- if (!raw) {
48
+ const collection = req.payload.collections[item.collectionSlug]?.config;
49
+ if (!collection) {
53
50
  throw new APIError(`Collection schema not found for slug: ${item.collectionSlug}`, 500);
54
51
  }
55
- const collectionSchema = removeVirtualFieldsFromSchema(JSON.parse(JSON.stringify(raw)), getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug));
52
+ const collectionSchema = removeVirtualFieldsFromSchema(entityToStandaloneJSONSchema({
53
+ config: req.payload.config,
54
+ defaultIDType: req.payload.db.defaultIDType,
55
+ entity: collection,
56
+ i18n: req.i18n
57
+ }), getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug));
56
58
  inputSchema = inputSchema({
57
59
  collectionSchema
58
60
  });
@@ -76,11 +78,16 @@ import { toStandardSchema } from '../utils/toStandardSchema.js';
76
78
  const name = wireName(item.key, item.globalSlug);
77
79
  let inputSchema = tool.input;
78
80
  if (typeof inputSchema === 'function') {
79
- const raw = configSchema.definitions?.[item.globalSlug];
80
- if (!raw) {
81
+ const globalEntity = req.payload.config.globals.find((globalConfig)=>globalConfig.slug === item.globalSlug);
82
+ if (!globalEntity) {
81
83
  throw new APIError(`Global schema not found for slug: ${item.globalSlug}`, 500);
82
84
  }
83
- const globalSchema = removeVirtualFieldsFromSchema(JSON.parse(JSON.stringify(raw)), getGlobalVirtualFieldNames(req.payload.config, item.globalSlug));
85
+ const globalSchema = removeVirtualFieldsFromSchema(entityToStandaloneJSONSchema({
86
+ config: req.payload.config,
87
+ defaultIDType: req.payload.db.defaultIDType,
88
+ entity: globalEntity,
89
+ i18n: req.i18n
90
+ }), getGlobalVirtualFieldNames(req.payload.config, item.globalSlug));
84
91
  inputSchema = inputSchema({
85
92
  globalSchema
86
93
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, configToJSONSchema, type PayloadRequest } from 'payload'\n\nimport type {\n AuthorizedMCP,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { toCamelCase } from '../utils/camelCase.js'\nimport { getLogger } from '../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n getGlobalVirtualFieldNames,\n} from '../utils/getVirtualFieldNames.js'\nimport { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/** `findPosts`, `updateSiteSettings` — auto-prefixed wire name for collection/global tools. */\nconst wireName = (key: string, slug: string): string => {\n const camel = toCamelCase(slug)\n return `${key}${camel.charAt(0).toUpperCase()}${camel.slice(1)}`\n}\n\n/**\n * Transport-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The caller is responsible for picking a transport\n * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and\n * calling `server.connect(transport)`.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = (\n response: MCPToolResponse,\n overrideResponse?: MCPResponseOverride,\n ): MCPToolResponse => {\n const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n const { jsonSchema: configSchema } = configToJSONSchema(\n req.payload.config,\n req.payload.db.defaultIDType,\n req.i18n,\n { forceInlineBlocks: true },\n ) as { jsonSchema: JsonSchemaType; typeStringDefinitions: Set<string> }\n\n try {\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool': {\n const tool = item.tool\n const name = wireName(item.key, item.collectionSlug)\n let inputSchema = tool.input\n if (typeof inputSchema === 'function') {\n const raw = configSchema.definitions?.[item.collectionSlug]\n if (!raw) {\n throw new APIError(\n `Collection schema not found for slug: ${item.collectionSlug}`,\n 500,\n )\n }\n const collectionSchema = removeVirtualFieldsFromSchema(\n JSON.parse(JSON.stringify(raw)) as JsonSchemaType,\n getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug),\n )\n inputSchema = inputSchema({ collectionSchema })\n }\n server.registerTool(\n name,\n {\n description: tool.description,\n inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n collectionSlug: item.collectionSlug,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${name} Registered.`)\n break\n }\n case 'globalTool': {\n const tool = item.tool\n const name = wireName(item.key, item.globalSlug)\n let inputSchema = tool.input\n if (typeof inputSchema === 'function') {\n const raw = configSchema.definitions?.[item.globalSlug]\n if (!raw) {\n throw new APIError(`Global schema not found for slug: ${item.globalSlug}`, 500)\n }\n const globalSchema = removeVirtualFieldsFromSchema(\n JSON.parse(JSON.stringify(raw)) as JsonSchemaType,\n getGlobalVirtualFieldNames(req.payload.config, item.globalSlug),\n )\n\n inputSchema = inputSchema({ globalSchema })\n }\n server.registerTool(\n name,\n {\n description: tool.description,\n inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n globalSlug: item.globalSlug,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${name} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.key,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.key,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.key,\n {\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${item.key} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n"],"names":["McpServer","APIError","configToJSONSchema","toCamelCase","getLogger","getCollectionVirtualFieldNames","getGlobalVirtualFieldNames","removeVirtualFieldsFromSchema","toStandardSchema","wireName","key","slug","camel","charAt","toUpperCase","slice","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","response","overrideResponse","overridden","doc","_doc","rest","jsonSchema","configSchema","config","db","defaultIDType","i18n","forceInlineBlocks","item","items","type","tool","collectionSlug","inputSchema","input","raw","definitions","collectionSchema","JSON","parse","stringify","registerTool","description","undefined","ctx","handler","serverContext","info","globalSlug","globalSchema","prompt","registerPrompt","argsSchema","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String"],"mappings":"AAAA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,kBAAkB,QAA6B,UAAS;AAU3E,SAASC,WAAW,QAAQ,wBAAuB;AACnD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SACEC,8BAA8B,EAC9BC,0BAA0B,QACrB,mCAAkC;AACzC,SAASC,6BAA6B,QAAQ,6DAA4D;AAC1G,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D,6FAA6F,GAC7F,MAAMC,WAAW,CAACC,KAAaC;IAC7B,MAAMC,QAAQT,YAAYQ;IAC1B,OAAO,GAAGD,MAAME,MAAMC,MAAM,CAAC,GAAGC,WAAW,KAAKF,MAAMG,KAAK,CAAC,IAAI;AAClE;AAEA;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACC,MAAMC,gBAAgBF,aAAaG,GAAG,EAAED,iBAAiB,CAAC;IAC1D,MAAME,SAAS,IAAItB,UACjB;QAAEuB,MAAM;QAAsBC,SAAS;QAAS,GAAGJ,cAAcK,UAAU;IAAC,GAC5EL,cAAcM,OAAO;IAGvB,MAAMC,SAASvB,UAAU;QAAEwB,SAAST,IAAIS,OAAO;IAAC;IAEhD;;;GAGC,GACD,MAAMC,uBAAuB,CAC3BC,UACAC;QAEA,MAAMC,aAAaD,mBAAmBD,UAAUA,SAASG,GAAG,IAAI,CAAC,GAAGd,QAAQW;QAC5E,MAAM,EAAEG,KAAKC,IAAI,EAAE,GAAGC,MAAM,GAAGH;QAC/B,OAAOG;IACT;IAEA,MAAM,EAAEC,YAAYC,YAAY,EAAE,GAAGnC,mBACnCiB,IAAIS,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AAS,CAAC,gCAAgC,EAAE4E,OAAOD,QAAQ,EAAE;IACzE;IAEA,OAAOtD;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/mcp/buildMcpServer.ts"],"sourcesContent":["import { McpServer, type ServerContext } from '@modelcontextprotocol/server'\nimport { APIError, entityToStandaloneJSONSchema, type PayloadRequest } from 'payload'\n\nimport type {\n AuthorizedMCP,\n JsonSchemaType,\n MCPResponseOverride,\n MCPToolResponse,\n SanitizedMCPPluginConfig,\n} from '../types.js'\n\nimport { toCamelCase } from '../utils/camelCase.js'\nimport { getLogger } from '../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n getGlobalVirtualFieldNames,\n} from '../utils/getVirtualFieldNames.js'\nimport { removeVirtualFieldsFromSchema } from '../utils/schemaConversion/removeVirtualFieldsFromSchema.js'\nimport { toStandardSchema } from '../utils/toStandardSchema.js'\n\n/** `findPosts`, `updateSiteSettings` — auto-prefixed wire name for collection/global tools. */\nconst wireName = (key: string, slug: string): string => {\n const camel = toCamelCase(slug)\n return `${key}${camel.charAt(0).toUpperCase()}${camel.slice(1)}`\n}\n\n/**\n * Transport-agnostic core: registers every authorized MCP item onto a fresh\n * `McpServer` and returns it. The caller is responsible for picking a transport\n * (`WebStandardStreamableHTTPServerTransport`, `StdioServerTransport`, …) and\n * calling `server.connect(transport)`.\n *\n * `req` is the request context handlers see. For HTTP it's the live\n * `PayloadRequest` derived from the incoming HTTP request; for stdio it's a\n * synthesized one built via `createLocalReq`.\n */\nexport const buildMcpServer = ({\n authorizedMCP,\n pluginConfig,\n req,\n}: {\n authorizedMCP: AuthorizedMCP\n pluginConfig: SanitizedMCPPluginConfig\n req: PayloadRequest\n}): McpServer => {\n const serverOptions = pluginConfig.mcp?.serverOptions || {}\n const server = new McpServer(\n { name: 'Payload MCP Server', version: '1.0.0', ...serverOptions.serverInfo },\n serverOptions.options,\n )\n\n const logger = getLogger({ payload: req.payload })\n\n /**\n * Wrap a tool handler's response with the tool's `overrideResponse`, then\n * strip the internal `doc` field so it doesn't leak onto the wire.\n */\n const finalizeToolResponse = (\n response: MCPToolResponse,\n overrideResponse?: MCPResponseOverride,\n ): MCPToolResponse => {\n const overridden = overrideResponse?.(response, response.doc ?? {}, req) ?? response\n const { doc: _doc, ...rest } = overridden\n return rest\n }\n\n try {\n for (const item of authorizedMCP.items) {\n switch (item.type) {\n case 'collectionTool': {\n const tool = item.tool\n const name = wireName(item.key, item.collectionSlug)\n let inputSchema = tool.input\n if (typeof inputSchema === 'function') {\n const collection = req.payload.collections[item.collectionSlug]?.config\n if (!collection) {\n throw new APIError(\n `Collection schema not found for slug: ${item.collectionSlug}`,\n 500,\n )\n }\n const collectionSchema = removeVirtualFieldsFromSchema(\n entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity: collection,\n i18n: req.i18n,\n }) as unknown as JsonSchemaType,\n getCollectionVirtualFieldNames(req.payload.config, item.collectionSlug),\n )\n inputSchema = inputSchema({ collectionSchema })\n }\n server.registerTool(\n name,\n {\n description: tool.description,\n inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n collectionSlug: item.collectionSlug,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${name} Registered.`)\n break\n }\n case 'globalTool': {\n const tool = item.tool\n const name = wireName(item.key, item.globalSlug)\n let inputSchema = tool.input\n if (typeof inputSchema === 'function') {\n const globalEntity = req.payload.config.globals.find(\n (globalConfig) => globalConfig.slug === item.globalSlug,\n )\n if (!globalEntity) {\n throw new APIError(`Global schema not found for slug: ${item.globalSlug}`, 500)\n }\n const globalSchema = removeVirtualFieldsFromSchema(\n entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity: globalEntity,\n i18n: req.i18n,\n }) as unknown as JsonSchemaType,\n getGlobalVirtualFieldNames(req.payload.config, item.globalSlug),\n )\n\n inputSchema = inputSchema({ globalSchema })\n }\n server.registerTool(\n name,\n {\n description: tool.description,\n inputSchema: inputSchema ? toStandardSchema(inputSchema) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n globalSlug: item.globalSlug,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${name} Registered.`)\n break\n }\n case 'prompt': {\n const prompt = item.prompt\n server.registerPrompt(\n item.key,\n {\n argsSchema: prompt.argsSchema ? toStandardSchema(prompt.argsSchema) : undefined,\n description: prompt.description,\n title: prompt.title,\n },\n async (input: unknown, ctx: ServerContext) =>\n prompt.handler({\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n )\n logger.info(`✅ Prompt: ${prompt.title} Registered.`)\n break\n }\n case 'resource': {\n const resource = item.resource\n server.registerResource(\n item.key,\n // @ts-expect-error - Overload type ambiguity (string OR ResourceTemplate is valid)\n resource.uri,\n {\n description: resource.description,\n mimeType: resource.mimeType,\n title: resource.title,\n },\n // Static URIs call (uri, ctx); ResourceTemplates call (uri, params, ctx).\n // The rest-params shape lets us collect either signature uniformly.\n async (...sdkArgs: unknown[]) => {\n const ctx = sdkArgs[sdkArgs.length - 1] as ServerContext\n const uri = sdkArgs[0] as URL\n const params = (sdkArgs.length > 2 ? sdkArgs[1] : {}) as Record<string, string>\n return resource.handler({ params, req, serverContext: ctx, uri })\n },\n )\n logger.info(`✅ Resource: ${resource.title} Registered.`)\n break\n }\n case 'tool': {\n const tool = item.tool\n server.registerTool(\n item.key,\n {\n description: tool.description,\n inputSchema: tool.input ? toStandardSchema(tool.input) : undefined,\n },\n async (input: unknown, ctx: ServerContext) =>\n finalizeToolResponse(\n await tool.handler({\n authorizedMCP,\n input: (input ?? {}) as Record<string, unknown>,\n req,\n serverContext: ctx,\n }),\n tool.overrideResponse,\n ),\n )\n logger.info(`✅ Tool: ${item.key} Registered.`)\n break\n }\n }\n }\n } catch (error) {\n throw new APIError(`Error initializing MCP handler: ${String(error)}`, 500)\n }\n\n return server\n}\n"],"names":["McpServer","APIError","entityToStandaloneJSONSchema","toCamelCase","getLogger","getCollectionVirtualFieldNames","getGlobalVirtualFieldNames","removeVirtualFieldsFromSchema","toStandardSchema","wireName","key","slug","camel","charAt","toUpperCase","slice","buildMcpServer","authorizedMCP","pluginConfig","req","serverOptions","mcp","server","name","version","serverInfo","options","logger","payload","finalizeToolResponse","response","overrideResponse","overridden","doc","_doc","rest","item","items","type","tool","collectionSlug","inputSchema","input","collection","collections","config","collectionSchema","defaultIDType","db","entity","i18n","registerTool","description","undefined","ctx","handler","serverContext","info","globalSlug","globalEntity","globals","find","globalConfig","globalSchema","prompt","registerPrompt","argsSchema","title","resource","registerResource","uri","mimeType","sdkArgs","length","params","error","String"],"mappings":"AAAA,SAASA,SAAS,QAA4B,+BAA8B;AAC5E,SAASC,QAAQ,EAAEC,4BAA4B,QAA6B,UAAS;AAUrF,SAASC,WAAW,QAAQ,wBAAuB;AACnD,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SACEC,8BAA8B,EAC9BC,0BAA0B,QACrB,mCAAkC;AACzC,SAASC,6BAA6B,QAAQ,6DAA4D;AAC1G,SAASC,gBAAgB,QAAQ,+BAA8B;AAE/D,6FAA6F,GAC7F,MAAMC,WAAW,CAACC,KAAaC;IAC7B,MAAMC,QAAQT,YAAYQ;IAC1B,OAAO,GAAGD,MAAME,MAAMC,MAAM,CAAC,GAAGC,WAAW,KAAKF,MAAMG,KAAK,CAAC,IAAI;AAClE;AAEA;;;;;;;;;CASC,GACD,OAAO,MAAMC,iBAAiB,CAAC,EAC7BC,aAAa,EACbC,YAAY,EACZC,GAAG,EAKJ;IACC,MAAMC,gBAAgBF,aAAaG,GAAG,EAAED,iBAAiB,CAAC;IAC1D,M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B,IAAI,CAAC,CAAC,YAAY,EAAEW,SAASD,KAAK,CAAC,YAAY,CAAC;wBACvD;oBACF;gBACA,KAAK;oBAAQ;wBACX,MAAM5B,OAAOH,KAAKG,IAAI;wBACtBjB,OAAO6B,YAAY,CACjBf,KAAK1B,GAAG,EACR;4BACE0C,aAAab,KAAKa,WAAW;4BAC7BX,aAAaF,KAAKG,KAAK,GAAGlC,iBAAiB+B,KAAKG,KAAK,IAAIW;wBAC3D,GACA,OAAOX,OAAgBY,MACrBzB,qBACE,MAAMU,KAAKgB,OAAO,CAAC;gCACjBtC;gCACAyB,OAAQA,SAAS,CAAC;gCAClBvB;gCACAqC,eAAeF;4BACjB,IACAf,KAAKR,gBAAgB;wBAG3BJ,OAAO8B,IAAI,CAAC,CAAC,QAAQ,EAAErB,KAAK1B,GAAG,CAAC,YAAY,CAAC;wBAC7C;oBACF;YACF;QACF;IACF,EAAE,OAAOiE,OAAO;QACd,MAAM,IAAI1E,SAAS,CAAC,gCAAgC,EAAE2E,OAAOD,QAAQ,EAAE;IACzE;IAEA,OAAOrD;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,oBAAoB,4CAmG/B,CAAA"}
1
+ {"version":3,"file":"createTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,oBAAoB,4CAkG/B,CAAA"}
@@ -3,18 +3,22 @@ import { defineCollectionTool } from '../../../defineTool.js';
3
3
  import { getLogger } from '../../../utils/getLogger.js';
4
4
  import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
5
5
  import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { prepareCollectionSchema } from '../../../utils/schemaConversion/prepareCollectionSchema.js';
6
+ import { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js';
7
+ import { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js';
7
8
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
8
9
  const DEFAULT_DESCRIPTION = 'Create a document in a collection.';
9
10
  export const createCollectionTool = defineCollectionTool({
10
11
  description: DEFAULT_DESCRIPTION,
11
- input: ({ collectionSchema })=>z.object({
12
- data: z.fromJSONSchema(prepareCollectionSchema(collectionSchema)).describe('The document fields to create'),
13
- depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
14
- draft: z.boolean().describe('Whether to create the document as a draft').optional().default(false),
15
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
16
- locale: z.string().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
17
- select: z.string().describe('Optional: define exactly which fields you\'d like to create (JSON), e.g., \'{"title": "My Post"}\'').optional()
12
+ input: ({ collectionSchema })=>buildToolInput({
13
+ controls: {
14
+ depth: z.number().int().min(0).max(10).describe('How many levels deep to populate relationships in response').optional().default(0),
15
+ draft: z.boolean().describe('Whether to create the document as a draft').optional().default(false),
16
+ fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
17
+ locale: z.string().describe('Optional: locale code to create the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
18
+ select: z.string().describe('Optional: define exactly which fields you\'d like to create (JSON), e.g., \'{"title": "My Post"}\'').optional()
19
+ },
20
+ dataDescription: 'The document fields to create',
21
+ dataSchema: sanitizeEntitySchema(collectionSchema)
18
22
  })
19
23
  }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
20
24
  const payload = req.payload;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { prepareCollectionSchema } from '../../../utils/schemaConversion/prepareCollectionSchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\n\nconst DEFAULT_DESCRIPTION = 'Create a document in a collection.'\n\nexport const createCollectionTool = defineCollectionTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ collectionSchema }) =>\n z.object({\n data: z\n .fromJSONSchema(\n prepareCollectionSchema(collectionSchema) as unknown as z.core.JSONSchema.JSONSchema,\n )\n .describe('The document fields to create'),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to create the document as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n let parsedData = transformPointDataToPayload(data as Record<string, unknown>)\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error creating document in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","localAPIDefaults","prepareCollectionSchema","transformPointDataToPayload","DEFAULT_DESCRIPTION","createCollectionTool","description","input","collectionSchema","object","data","fromJSONSchema","describe","depth","number","int","min","max","optional","default","draft","boolean","fallbackLocale","string","locale","select","handler","authorizedMCP","collectionSlug","req","payload","logger","info","parsedData","virtualFieldNames","config","selectClause","JSON","parse","warn","content","type","text","result","create","collection","id","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,uBAAuB,QAAQ,6DAA4D;AACpG,SAASC,2BAA2B,QAAQ,gDAA+C;AAE3F,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,uBAAuBR,qBAAqB;IACvDS,aAAaF;IACbG,OAAO,CAAC,EAAEC,gBA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QC,MAAM;wBAAuC;qBAAE;gBAAC;YACrF;QACF;QAEA,MAAMC,SAAS,MAAMb,QAAQc,MAAM,CAAC;YAClCC,YAAYjB;YACZlB,MAAMuB;YACNpB;YACAO;YACAS;YACA,GAAG5B,iBAAiB0B,cAAc;YAClC,GAAIH,SAAS;gBAAEA;YAAO,IAAI,CAAC,CAAC;YAC5B,GAAIF,iBAAiB;gBAAEA;YAAe,IAAI,CAAC,CAAC;YAC5C,GAAIc,eAAe;gBAAEX,QAAQW;YAAa,IAAI,CAAC,CAAC;QAClD;QAEAL,OAAOC,IAAI,CAAC,CAAC,iCAAiC,EAAEJ,eAAe,UAAU,EAAEe,OAAOG,EAAE,EAAE;QAEtF,OAAO;YACLN,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEd,eAAe,mCAAmC,EAAES,KAAKU,SAAS,CAACJ,QAAQ,QAAQ,CAAC;gBAC5I;aACD;YACDK,KAAKL;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DrB,OAAOkB,KAAK,CAAC,CAAC,2BAA2B,EAAErB,eAAe,EAAE,EAAEsB,cAAc;QAC5E,OAAO;YACLV,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,uCAAuC,EAAEd,eAAe,GAAG,EAAEsB,cAAc;gBACpF;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js'\nimport { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\n\nconst DEFAULT_DESCRIPTION = 'Create a document in a collection.'\n\nexport const createCollectionTool = defineCollectionTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ collectionSchema }) =>\n buildToolInput({\n controls: {\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to create the document as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to create (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n )\n .optional(),\n },\n dataDescription: 'The document fields to create',\n dataSchema: sanitizeEntitySchema(collectionSchema),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Creating document in collection: ${collectionSlug}${locale ? ` with locale: ${locale}` : ''}`,\n )\n\n try {\n let parsedData = transformPointDataToPayload(data)\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n })\n\n logger.info(`Successfully created document in ${collectionSlug} with ID: ${result.id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document created successfully in collection \"${collectionSlug}\"!\\nCreated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error creating document in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error creating document in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","localAPIDefaults","buildToolInput","sanitizeEntitySchema","transformPointDataToPayload","DEFAULT_DESCRIPTION","createCollectionTool","description","input","collectionSchema","controls","depth","number","int","min","max","describe","optional","default","draft","boolean","fallbackLocale","string","locale","select","dataDescription","dataSchema","handler","authorizedMCP","collectionSlug","req","payload","logger","data","info","parsedData","virtualFieldNames","config","selectClause","JSON","parse","warn","content","type","text","result","create","collection","id","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAASC,oBAAoB,QAAQ,0DAAyD;AAC9F,SAASC,2BAA2B,QAAQ,gDAA+C;AAE3F,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,uBAAuBT,qBAAqB;IACvDU,aAAaF;IACbG,OAAO,CAAC,EAAEC,gBAAgB,EAAE,GAC1BP,eAAe;YACbQ,UAAU;gBACRC,OAAOf,EACJgB,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,C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B;YACAQ;YACAW;YACA,GAAG7B,iBAAiB2B,cAAc;YAClC,GAAIL,SAAS;gBAAEA;YAAO,IAAI,CAAC,CAAC;YAC5B,GAAIF,iBAAiB;gBAAEA;YAAe,IAAI,CAAC,CAAC;YAC5C,GAAIiB,eAAe;gBAAEd,QAAQc;YAAa,IAAI,CAAC,CAAC;QAClD;QAEAN,OAAOE,IAAI,CAAC,CAAC,iCAAiC,EAAEL,eAAe,UAAU,EAAEgB,OAAOG,EAAE,EAAE;QAEtF,OAAO;YACLN,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,6CAA6C,EAAEf,eAAe,mCAAmC,EAAEU,KAAKU,SAAS,CAACJ,QAAQ,QAAQ,CAAC;gBAC5I;aACD;YACDK,KAAKL;QACP;IACF,EAAE,OAAOM,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DtB,OAAOmB,KAAK,CAAC,CAAC,2BAA2B,EAAEtB,eAAe,EAAE,EAAEuB,cAAc;QAC5E,OAAO;YACLV,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,uCAAuC,EAAEf,eAAe,GAAG,EAAEuB,cAAc;gBACpF;aACD;QACH;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,oBAAoB,4CA4L/B,CAAA"}
1
+ {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,oBAAoB,4CAgM/B,CAAA"}
@@ -3,33 +3,37 @@ import { defineCollectionTool } from '../../../defineTool.js';
3
3
  import { getLogger } from '../../../utils/getLogger.js';
4
4
  import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
5
5
  import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { prepareCollectionSchema } from '../../../utils/schemaConversion/prepareCollectionSchema.js';
6
+ import { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js';
7
+ import { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js';
7
8
  import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
8
9
  const DEFAULT_DESCRIPTION = 'Update documents in a collection by ID or where clause.';
9
10
  export const updateCollectionTool = defineCollectionTool({
10
11
  description: DEFAULT_DESCRIPTION,
11
12
  input: ({ collectionSchema })=>{
12
- const partialSchema = prepareCollectionSchema(collectionSchema);
13
+ const partialSchema = sanitizeEntitySchema(collectionSchema);
13
14
  // Collection updates do not require all required fields to be passed => delete .required.
14
15
  //
15
16
  // Local API equivalent: packages/payload/src/collections/operations/local/update.ts#BaseOptions#data:
16
17
  // data: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>
17
18
  delete partialSchema.required;
18
- return z.object({
19
- id: z.union([
20
- z.string(),
21
- z.number()
22
- ]).describe('The ID of the document to update').optional(),
23
- data: z.fromJSONSchema(partialSchema).describe('The fields to update'),
24
- depth: z.number().describe('How many levels deep to populate relationships').optional().default(0),
25
- draft: z.boolean().describe('Whether to update the document as a draft').optional().default(false),
26
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
27
- filePath: z.string().describe('File path for file uploads').optional(),
28
- locale: z.string().describe('Optional: locale code to update the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
29
- overrideLock: z.boolean().describe('Whether to override document locks').optional().default(true),
30
- overwriteExistingFiles: z.boolean().describe('Whether to overwrite existing files').optional().default(false),
31
- select: z.string().describe('Optional: define exactly which fields you\'d like to return in the response (JSON), e.g., \'{"title": "My Post"}\'').optional(),
32
- where: z.string().describe('JSON string for where clause to update multiple documents').optional()
19
+ return buildToolInput({
20
+ controls: {
21
+ id: z.union([
22
+ z.string(),
23
+ z.number()
24
+ ]).describe('The ID of the document to update').optional(),
25
+ depth: z.number().describe('How many levels deep to populate relationships').optional().default(0),
26
+ draft: z.boolean().describe('Whether to update the document as a draft').optional().default(false),
27
+ fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
28
+ filePath: z.string().describe('File path for file uploads').optional(),
29
+ locale: z.string().describe('Optional: locale code to update the document in (e.g., "en", "es"). Defaults to the default locale').optional(),
30
+ overrideLock: z.boolean().describe('Whether to override document locks').optional().default(true),
31
+ overwriteExistingFiles: z.boolean().describe('Whether to overwrite existing files').optional().default(false),
32
+ select: z.string().describe('Optional: define exactly which fields you\'d like to return in the response (JSON), e.g., \'{"title": "My Post"}\'').optional(),
33
+ where: z.string().describe('JSON string for where clause to update multiple documents').optional()
34
+ },
35
+ dataDescription: 'The fields to update',
36
+ dataSchema: partialSchema
33
37
  });
34
38
  }
35
39
  }).handler(async ({ authorizedMCP, collectionSlug, input, req })=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { prepareCollectionSchema } from '../../../utils/schemaConversion/prepareCollectionSchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\n\nconst DEFAULT_DESCRIPTION = 'Update documents in a collection by ID or where clause.'\n\nexport const updateCollectionTool = defineCollectionTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ collectionSchema }) => {\n const partialSchema = prepareCollectionSchema(collectionSchema)\n\n // Collection updates do not require all required fields to be passed => delete .required.\n //\n // Local API equivalent: packages/payload/src/collections/operations/local/update.ts#BaseOptions#data:\n // data: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n delete partialSchema.required\n\n return z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),\n data: z\n .fromJSONSchema(partialSchema as unknown as z.core.JSONSchema.JSONSchema)\n .describe('The fields to update'),\n depth: z\n .number()\n .describe('How many levels deep to populate relationships')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to update the document as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n filePath: z.string().describe('File path for file uploads').optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n overrideLock: z\n .boolean()\n .describe('Whether to override document locks')\n .optional()\n .default(true),\n overwriteExistingFiles: z\n .boolean()\n .describe('Whether to overwrite existing files')\n .optional()\n .default(false),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n )\n .optional(),\n where: z\n .string()\n .describe('JSON string for where clause to update multiple documents')\n .optional(),\n })\n },\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n filePath,\n locale,\n overrideLock,\n overwriteExistingFiles,\n select,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n let parsedData = transformPointDataToPayload(data as Record<string, unknown>)\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n let whereClause: Record<string, unknown> = {}\n if (where) {\n try {\n whereClause = JSON.parse(where) as Record<string, unknown>\n } catch {\n logger.error(`Invalid where clause JSON: ${where}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in where clause' }] }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n if (id) {\n const updateOptions = {\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideLock,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(filePath ? { filePath } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n }\n\n const result = await payload.update(updateOptions as any)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${collectionSlug}\"!\\nUpdated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const updateOptions = {\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideLock,\n req,\n ...localAPIDefaults(authorizedMCP),\n where: whereClause,\n ...(filePath ? { filePath } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n }\n\n const result = await payload.update(updateOptions as any)\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\\nUpdated: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating document in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error updating document in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","localAPIDefaults","prepareCollectionSchema","transformPointDataToPayload","DEFAULT_DESCRIPTION","updateCollectionTool","description","input","collectionSchema","partialSchema","required","object","id","union","string","number","describe","optional","data","fromJSONSchema","depth","default","draft","boolean","fallbackLocale","filePath","locale","overrideLock","overwriteExistingFiles","select","where","handler","authorizedMCP","collectionSlug","req","payload","logger","info","content","type","text","parsedData","virtualFieldNames","config","whereClause","JSON","parse","error","selectClause","warn","updateOptions","collection","result","update","stringify","doc","bulkResult","docs","errors","responseText","length","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,uBAAuB,QAAQ,6DAA4D;AACpG,SAASC,2BAA2B,QAAQ,gDAA+C;AAE3F,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,uBAAuBR,qBAAqB;IACvDS,aAAaF;IACbG,OAAO,CAAC,EAAEC,gBAAgB,EAAE;QAC1B,MAAMC,gBAAgBP,wBAAwBM;QAE9C,0FAA0F;QAC1F,EAAE;QACF,sGAAsG;QACtG,2DAA2D;QAC3D,OAAOC,cAAcC,QAAQ;QAE7B,OAAOd,EAAEe,MAAM,CAAC;YACdC,IAAIhB,EAAEiB,KAAK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C9E;QAEA,OAAO;YACLpB,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMmB;gBAAa;aAAE;YAC/CJ,KAAK;gBAAEE;gBAAMC;YAAO;QACtB;IACF,EAAE,OAAOX,OAAO;QACd,MAAMc,eAAed,iBAAiBe,QAAQf,MAAMgB,OAAO,GAAG;QAC9D3B,OAAOW,KAAK,CAAC,CAAC,2BAA2B,EAAEd,eAAe,EAAE,EAAE4B,cAAc;QAC5E,OAAO;YACLvB,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,uCAAuC,EAAEP,eAAe,GAAG,EAAE4B,cAAc;gBACpF;aACD;QACH;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js'\nimport { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\n\nconst DEFAULT_DESCRIPTION = 'Update documents in a collection by ID or where clause.'\n\nexport const updateCollectionTool = defineCollectionTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ collectionSchema }) => {\n const partialSchema = sanitizeEntitySchema(collectionSchema)\n\n // Collection updates do not require all required fields to be passed => delete .required.\n //\n // Local API equivalent: packages/payload/src/collections/operations/local/update.ts#BaseOptions#data:\n // data: DeepPartial<RequiredDataFromCollectionSlug<TSlug>>\n delete partialSchema.required\n\n return buildToolInput({\n controls: {\n id: z\n .union([z.string(), z.number()])\n .describe('The ID of the document to update')\n .optional(),\n depth: z\n .number()\n .describe('How many levels deep to populate relationships')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to update the document as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n filePath: z.string().describe('File path for file uploads').optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n overrideLock: z\n .boolean()\n .describe('Whether to override document locks')\n .optional()\n .default(true),\n overwriteExistingFiles: z\n .boolean()\n .describe('Whether to overwrite existing files')\n .optional()\n .default(false),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"title\": \"My Post\"}\\'',\n )\n .optional(),\n where: z\n .string()\n .describe('JSON string for where clause to update multiple documents')\n .optional(),\n },\n dataDescription: 'The fields to update',\n dataSchema: partialSchema,\n })\n },\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n filePath,\n locale,\n overrideLock,\n overwriteExistingFiles,\n select,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n let parsedData = transformPointDataToPayload(data)\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n parsedData = stripVirtualFields(parsedData, virtualFieldNames)\n\n let whereClause: Record<string, unknown> = {}\n if (where) {\n try {\n whereClause = JSON.parse(where) as Record<string, unknown>\n } catch {\n logger.error(`Invalid where clause JSON: ${where}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in where clause' }] }\n }\n }\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n if (id) {\n const updateOptions = {\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideLock,\n req,\n ...localAPIDefaults(authorizedMCP),\n ...(filePath ? { filePath } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n }\n\n const result = await payload.update(updateOptions as any)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${collectionSlug}\"!\\nUpdated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const updateOptions = {\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideLock,\n req,\n ...localAPIDefaults(authorizedMCP),\n where: whereClause,\n ...(filePath ? { filePath } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(selectClause ? { select: selectClause } : {}),\n }\n\n const result = await payload.update(updateOptions as any)\n\n const bulkResult = result as { docs?: unknown[]; errors?: unknown[] }\n const docs = bulkResult.docs || []\n const errors = bulkResult.errors || []\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\\nUpdated: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating document in ${collectionSlug}: ${errorMessage}`)\n return {\n content: [\n {\n type: 'text',\n text: `Error updating document in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n }\n }\n})\n"],"names":["z","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","localAPIDefaults","buildToolInput","sanitizeEntitySchema","transformPointDataToPayload","DEFAULT_DESCRIPTION","updateCollectionTool","description","input","collectionSchema","partialSchema","required","controls","id","union","string","number","describe","optional","depth","default","draft","boolean","fallbackLocale","filePath","locale","overrideLock","overwriteExistingFiles","select","where","dataDescription","dataSchema","handler","authorizedMCP","collectionSlug","req","payload","logger","data","info","content","type","text","parsedData","virtualFieldNames","config","whereClause","JSON","parse","error","selectClause","warn","updateOptions","collection","result","update","stringify","doc","bulkResult","docs","errors","responseText","length","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAASC,oBAAoB,QAAQ,0DAAyD;AAC9F,SAASC,2BAA2B,QAAQ,gDAA+C;AAE3F,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,uBAAuBT,qBAAqB;IACvDU,aAAaF;IACbG,OAAO,CAAC,EAAEC,gBAAgB,EAAE;QAC1B,MAAMC,gBAAgBP,qBAAqBM;QAE3C,0FAA0F;QAC1F,EAAE;QACF,sGAAsG;QACtG,2DAA2D;QAC3D,OAAOC,cAAcC,QAAQ;QAE7B,OAAOT,eAAe;YACpBU,UAAU;gBACRC,IAAIjB,EACDkB,KAAK,CAAC;oBAAClB,EAAEmB,MAAM;oBAAInB,EAAEoB,MAAM;iBAAG,EAC9BC,QAAQ,CAA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AC/CJ,KAAK;gBAAEE;gBAAMC;YAAO;QACtB;IACF,EAAE,OAAOX,OAAO;QACd,MAAMc,eAAed,iBAAiBe,QAAQf,MAAMgB,OAAO,GAAG;QAC9D5B,OAAOY,KAAK,CAAC,CAAC,2BAA2B,EAAEf,eAAe,EAAE,EAAE6B,cAAc;QAC5E,OAAO;YACLvB,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,uCAAuC,EAAER,eAAe,GAAG,EAAE6B,cAAc;gBACpF;aACD;QACH;IACF;AACF,GAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,gBAAgB,wCAsG3B,CAAA"}
1
+ {"version":3,"file":"updateTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"names":[],"mappings":"AAgBA,eAAO,MAAM,gBAAgB,wCAuG3B,CAAA"}
@@ -3,24 +3,28 @@ import { defineGlobalTool } from '../../../defineTool.js';
3
3
  import { getLogger } from '../../../utils/getLogger.js';
4
4
  import { getGlobalVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
5
5
  import { localAPIDefaults } from '../../../utils/localAPIDefaults.js';
6
- import { prepareCollectionSchema } from '../../../utils/schemaConversion/prepareCollectionSchema.js';
6
+ import { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js';
7
+ import { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js';
7
8
  const DEFAULT_DESCRIPTION = 'Update a Payload global singleton configuration.';
8
9
  export const updateGlobalTool = defineGlobalTool({
9
10
  description: DEFAULT_DESCRIPTION,
10
11
  input: ({ globalSchema })=>{
11
- const partialSchema = prepareCollectionSchema(globalSchema);
12
+ const partialSchema = sanitizeEntitySchema(globalSchema);
12
13
  // Global updates do not require all required fields to be passed => delete .required.
13
14
  //
14
15
  // Local API equivalent: packages/payload/src/global/operations/local/update.ts#BaseOptions#data:
15
16
  // data: DeepPartial<Omit<DataFromGlobalSlug<TSlug>, 'id'>>
16
17
  delete partialSchema.required;
17
- return z.object({
18
- data: z.fromJSONSchema(partialSchema).describe('The fields to update'),
19
- depth: z.number().describe('Optional: Depth of relationships to populate').optional().default(0),
20
- draft: z.boolean().describe('Optional: Whether to save as draft (default: false)').optional().default(false),
21
- fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
22
- locale: z.string().describe('Optional: locale code to update data in (e.g., "en", "es"). Use "all" to update all locales for localized fields').optional(),
23
- select: z.string().describe('Optional: define exactly which fields you\'d like to return in the response (JSON), e.g., \'{"siteName": "My Site"}\'').optional()
18
+ return buildToolInput({
19
+ controls: {
20
+ depth: z.number().describe('Optional: Depth of relationships to populate').optional().default(0),
21
+ draft: z.boolean().describe('Optional: Whether to save as draft (default: false)').optional().default(false),
22
+ fallbackLocale: z.string().describe('Optional: fallback locale code to use when requested locale is not available').optional(),
23
+ locale: z.string().describe('Optional: locale code to update data in (e.g., "en", "es"). Use "all" to update all locales for localized fields').optional(),
24
+ select: z.string().describe('Optional: define exactly which fields you\'d like to return in the response (JSON), e.g., \'{"siteName": "My Site"}\'').optional()
25
+ },
26
+ dataDescription: 'The fields to update',
27
+ dataSchema: partialSchema
24
28
  });
25
29
  }
26
30
  }).handler(async ({ authorizedMCP, globalSlug, input, req })=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineGlobalTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { prepareCollectionSchema } from '../../../utils/schemaConversion/prepareCollectionSchema.js'\n\nconst DEFAULT_DESCRIPTION = 'Update a Payload global singleton configuration.'\n\nexport const updateGlobalTool = defineGlobalTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ globalSchema }) => {\n const partialSchema = prepareCollectionSchema(globalSchema)\n // Global updates do not require all required fields to be passed => delete .required.\n //\n // Local API equivalent: packages/payload/src/global/operations/local/update.ts#BaseOptions#data:\n // data: DeepPartial<Omit<DataFromGlobalSlug<TSlug>, 'id'>>\n delete partialSchema.required\n\n return z.object({\n data: z\n .fromJSONSchema(partialSchema as unknown as z.core.JSONSchema.JSONSchema)\n .describe('The fields to update'),\n depth: z\n .number()\n .describe('Optional: Depth of relationships to populate')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Optional: Whether to save as draft (default: false)')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\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 .optional(),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"siteName\": \"My Site\"}\\'',\n )\n .optional(),\n })\n },\n}).handler(async ({ authorizedMCP, globalSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Updating global: ${globalSlug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)\n const parsedData = stripVirtualFields(data as Record<string, unknown>, virtualFieldNames)\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON for global: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n ...localAPIDefaults(authorizedMCP),\n }\n\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 return {\n content: [\n {\n type: 'text',\n text: `Global \"${globalSlug}\" updated successfully!\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating global ${globalSlug}: ${errorMessage}`)\n return {\n content: [{ type: 'text', text: `Error updating global \"${globalSlug}\": ${errorMessage}` }],\n }\n }\n})\n"],"names":["z","defineGlobalTool","getLogger","getGlobalVirtualFieldNames","stripVirtualFields","localAPIDefaults","prepareCollectionSchema","DEFAULT_DESCRIPTION","updateGlobalTool","description","input","globalSchema","partialSchema","required","object","data","fromJSONSchema","describe","depth","number","optional","default","draft","boolean","fallbackLocale","string","locale","select","handler","authorizedMCP","globalSlug","req","payload","logger","info","virtualFieldNames","config","parsedData","selectClause","JSON","parse","warn","content","type","text","updateOptions","slug","result","updateGlobal","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,uBAAuB,QAAQ,6DAA4D;AAEpG,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,mBAAmBP,iBAAiB;IAC/CQ,aAAaF;IACbG,OAAO,CAAC,EAAEC,YAAY,EAAE;QACtB,MAAMC,gBAAgBN,wBAAwBK;QAC9C,sFAAsF;QACtF,EAAE;QACF,iGAAiG;QACjG,2DAA2D;QAC3D,OAAOC,cAAcC,Q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YAChEC,MAAMhB;YACNf,MAAMsB;YACNnB;YACAI;YACA,GAAGjB,iBAAiBwB,cAAc;QACpC;QAEA,IAAIH,QAAQ;YACVmB,cAAcnB,MAAM,GAAGA;QACzB;QACA,IAAIF,gBAAgB;YAClBqB,cAAcrB,cAAc,GAAGA;QACjC;QACA,IAAIc,cAAc;YAChBO,cAAclB,MAAM,GAAGW;QACzB;QAEA,MAAMS,SAAS,MAAMf,QAAQgB,YAAY,CAACH;QAE1C,OAAO;YACLH,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,QAAQ,EAAEd,WAAW,qCAAqC,EAAES,KAAKU,SAAS,CAACF,QAAQ,QAAQ,CAAC;gBACrG;aACD;YACDG,KAAKH;QACP;IACF,EAAE,OAAOI,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DrB,OAAOkB,KAAK,CAAC,CAAC,sBAAsB,EAAErB,WAAW,EAAE,EAAEsB,cAAc;QACnE,OAAO;YACLV,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAM,CAAC,uBAAuB,EAAEd,WAAW,GAAG,EAAEsB,cAAc;gBAAC;aAAE;QAC7F;IACF;AACF,GAAE"}
1
+ {"version":3,"sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defineGlobalTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { localAPIDefaults } from '../../../utils/localAPIDefaults.js'\nimport { buildToolInput } from '../../../utils/schemaConversion/buildToolInput.js'\nimport { sanitizeEntitySchema } from '../../../utils/schemaConversion/sanitizeEntitySchema.js'\n\nconst DEFAULT_DESCRIPTION = 'Update a Payload global singleton configuration.'\n\nexport const updateGlobalTool = defineGlobalTool({\n description: DEFAULT_DESCRIPTION,\n input: ({ globalSchema }) => {\n const partialSchema = sanitizeEntitySchema(globalSchema)\n // Global updates do not require all required fields to be passed => delete .required.\n //\n // Local API equivalent: packages/payload/src/global/operations/local/update.ts#BaseOptions#data:\n // data: DeepPartial<Omit<DataFromGlobalSlug<TSlug>, 'id'>>\n delete partialSchema.required\n\n return buildToolInput({\n controls: {\n depth: z\n .number()\n .describe('Optional: Depth of relationships to populate')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Optional: Whether to save as draft (default: false)')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\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 .optional(),\n select: z\n .string()\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response (JSON), e.g., \\'{\"siteName\": \"My Site\"}\\'',\n )\n .optional(),\n },\n dataDescription: 'The fields to update',\n dataSchema: partialSchema,\n })\n },\n}).handler(async ({ authorizedMCP, globalSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Updating global: ${globalSlug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)\n const parsedData = stripVirtualFields(data, virtualFieldNames)\n\n let selectClause: SelectType | undefined\n if (select) {\n try {\n selectClause = JSON.parse(select) as SelectType\n } catch {\n logger.warn(`Invalid select clause JSON for global: ${select}`)\n return { content: [{ type: 'text', text: 'Error: Invalid JSON in select clause' }] }\n }\n }\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n ...localAPIDefaults(authorizedMCP),\n }\n\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 return {\n content: [\n {\n type: 'text',\n text: `Global \"${globalSlug}\" updated successfully!\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating global ${globalSlug}: ${errorMessage}`)\n return {\n content: [{ type: 'text', text: `Error updating global \"${globalSlug}\": ${errorMessage}` }],\n }\n }\n})\n"],"names":["z","defineGlobalTool","getLogger","getGlobalVirtualFieldNames","stripVirtualFields","localAPIDefaults","buildToolInput","sanitizeEntitySchema","DEFAULT_DESCRIPTION","updateGlobalTool","description","input","globalSchema","partialSchema","required","controls","depth","number","describe","optional","default","draft","boolean","fallbackLocale","string","locale","select","dataDescription","dataSchema","handler","authorizedMCP","globalSlug","req","payload","logger","data","info","virtualFieldNames","config","parsedData","selectClause","JSON","parse","warn","content","type","text","updateOptions","slug","result","updateGlobal","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAASC,oBAAoB,QAAQ,0DAAyD;AAE9F,MAAMC,sBAAsB;AAE5B,OAAO,MAAMC,mBAAmBR,iBAAiB;IAC/CS,aAAaF;IACbG,OAAO,CAAC,EAAEC,YAAY,EAAE;QACtB,MAAMC,gBAAgBN,qBAAqBK;QAC3C,sFAAsF;QACtF,EAAE;QACF,iGAAiG;QACjG,2DAA2D;QAC3D,OAAOC,cAAcC,QAAQ;QAE7B,OAAOR,eAAe;YACpBS,UAAU;gBACRC,OAAOhB,EACJiB,MAA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EA,IAAIL,QAAQ;YACVsB,cAActB,MAAM,GAAGA;QACzB;QACA,IAAIF,gBAAgB;YAClBwB,cAAcxB,cAAc,GAAGA;QACjC;QACA,IAAIiB,cAAc;YAChBO,cAAcrB,MAAM,GAAGc;QACzB;QAEA,MAAMS,SAAS,MAAMhB,QAAQiB,YAAY,CAACH;QAE1C,OAAO;YACLH,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,QAAQ,EAAEf,WAAW,qCAAqC,EAAEU,KAAKU,SAAS,CAACF,QAAQ,QAAQ,CAAC;gBACrG;aACD;YACDG,KAAKH;QACP;IACF,EAAE,OAAOI,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9DtB,OAAOmB,KAAK,CAAC,CAAC,sBAAsB,EAAEtB,WAAW,EAAE,EAAEuB,cAAc;QACnE,OAAO;YACLV,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAM,CAAC,uBAAuB,EAAEf,WAAW,GAAG,EAAEuB,cAAc;gBAAC;aAAE;QAC7F;IACF;AACF,GAAE"}
@@ -0,0 +1,29 @@
1
+ import type { StandardSchemaWithJSON } from '@modelcontextprotocol/server';
2
+ import { z } from 'zod';
3
+ import type { JsonSchemaType } from '../../types.js';
4
+ /**
5
+ * Builds a create/update tool's `input`: a `data` field (the document's fields) plus controls like
6
+ * `depth` and `draft`. Using just `z.fromJSONSchema(ourJSONSchema)` has a few problems which are mitigated
7
+ * in this function. z.fromJSONSchema is both bigger and lossier (≈40% larger on the lexical schema).
8
+ * Each example below is `what we publish` => `what a plain zod round-trip would publish instead`.
9
+ *
10
+ * @example
11
+ * Bigger - zod inlines shared defs instead of keeping our `$ref`s (and adds junk integer bounds), so a
12
+ * reused def is duplicated at every use:
13
+ * `{ $ref: '#/$defs/author' }` => `{ type: 'object', properties: { id, name }, additionalProperties: false }`
14
+ *
15
+ * @example
16
+ * Lossier - zod drops the `description` on `enum`/`const` fields:
17
+ * `{ enum: ['draft', 'published'], description: 'Publish state' }` → `{ enum: ['draft', 'published'] }`
18
+ */
19
+ export declare const buildToolInput: <TControls extends z.ZodRawShape>({ controls, dataDescription, dataSchema, }: {
20
+ /** Tool options alongside `data` (depth, draft, where, …) as plain zod - inferred into `input`. */
21
+ controls: TControls;
22
+ dataDescription: string;
23
+ dataSchema: JsonSchemaType;
24
+ }) => StandardSchemaWithJSON<{
25
+ data: Record<string, unknown>;
26
+ } & Omit<z.output<z.ZodObject<{
27
+ data: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
28
+ } & TControls extends infer T ? { -readonly [P in keyof T]: T[P]; } : never, z.core.$strip>>, "data">>;
29
+ //# sourceMappingURL=buildToolInput.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildToolInput.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/buildToolInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAE1E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAEpD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,cAAc,GAAI,SAAS,SAAS,CAAC,CAAC,WAAW,EAAE,4CAI7D;IACD,mGAAmG;IACnG,QAAQ,EAAE,SAAS,CAAA;IACnB,eAAe,EAAE,MAAM,CAAA;IACvB,UAAU,EAAE,cAAc,CAAA;CAC3B,KAkCM,sBAAsB,CACzB;IAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM;;4FAAe,EAAE,MAAM,CAAC,CAE5E,CAAA"}
@@ -0,0 +1,51 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Builds a create/update tool's `input`: a `data` field (the document's fields) plus controls like
4
+ * `depth` and `draft`. Using just `z.fromJSONSchema(ourJSONSchema)` has a few problems which are mitigated
5
+ * in this function. z.fromJSONSchema is both bigger and lossier (≈40% larger on the lexical schema).
6
+ * Each example below is `what we publish` => `what a plain zod round-trip would publish instead`.
7
+ *
8
+ * @example
9
+ * Bigger - zod inlines shared defs instead of keeping our `$ref`s (and adds junk integer bounds), so a
10
+ * reused def is duplicated at every use:
11
+ * `{ $ref: '#/$defs/author' }` => `{ type: 'object', properties: { id, name }, additionalProperties: false }`
12
+ *
13
+ * @example
14
+ * Lossier - zod drops the `description` on `enum`/`const` fields:
15
+ * `{ enum: ['draft', 'published'], description: 'Publish state' }` → `{ enum: ['draft', 'published'] }`
16
+ */ export const buildToolInput = ({ controls, dataDescription, dataSchema })=>{
17
+ // `sanitizeEntitySchema` already emits draft 2020-12 with `$defs`, which is what zod's `fromJSONSchema`
18
+ // and MCP clients both expect. Drop only the root `$schema` keyword, redundant once it's a sub-schema.
19
+ const { $schema: _schema, ...entitySchema } = dataSchema;
20
+ const schema = z.object({
21
+ data: z.fromJSONSchema(entitySchema),
22
+ ...controls
23
+ });
24
+ const standard = schema['~standard'];
25
+ return {
26
+ '~standard': {
27
+ ...standard,
28
+ jsonSchema: {
29
+ ...standard.jsonSchema,
30
+ input: (options)=>{
31
+ // Start from zod's JSON Schema for the whole input, then replace its lossy `data` schema with
32
+ // the sanitized entity schema. The entity's `$defs` move to the root so the `$ref`s resolve.
33
+ const generated = standard.jsonSchema.input(options);
34
+ const { $defs, ...entityBody } = entitySchema;
35
+ generated.properties.data = {
36
+ ...entityBody,
37
+ description: dataDescription
38
+ };
39
+ if ($defs) {
40
+ generated.$defs = $defs;
41
+ } else {
42
+ delete generated.$defs;
43
+ }
44
+ return generated;
45
+ }
46
+ }
47
+ }
48
+ };
49
+ };
50
+
51
+ //# sourceMappingURL=buildToolInput.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/schemaConversion/buildToolInput.ts"],"sourcesContent":["import type { StandardSchemaWithJSON } from '@modelcontextprotocol/server'\n\nimport { z } from 'zod'\n\nimport type { JsonSchemaType } from '../../types.js'\n\n/**\n * Builds a create/update tool's `input`: a `data` field (the document's fields) plus controls like\n * `depth` and `draft`. Using just `z.fromJSONSchema(ourJSONSchema)` has a few problems which are mitigated\n * in this function. z.fromJSONSchema is both bigger and lossier (≈40% larger on the lexical schema).\n * Each example below is `what we publish` => `what a plain zod round-trip would publish instead`.\n *\n * @example\n * Bigger - zod inlines shared defs instead of keeping our `$ref`s (and adds junk integer bounds), so a\n * reused def is duplicated at every use:\n * `{ $ref: '#/$defs/author' }` => `{ type: 'object', properties: { id, name }, additionalProperties: false }`\n *\n * @example\n * Lossier - zod drops the `description` on `enum`/`const` fields:\n * `{ enum: ['draft', 'published'], description: 'Publish state' }` → `{ enum: ['draft', 'published'] }`\n */\nexport const buildToolInput = <TControls extends z.ZodRawShape>({\n controls,\n dataDescription,\n dataSchema,\n}: {\n /** Tool options alongside `data` (depth, draft, where, …) as plain zod - inferred into `input`. */\n controls: TControls\n dataDescription: string\n dataSchema: JsonSchemaType\n}) => {\n // `sanitizeEntitySchema` already emits draft 2020-12 with `$defs`, which is what zod's `fromJSONSchema`\n // and MCP clients both expect. Drop only the root `$schema` keyword, redundant once it's a sub-schema.\n const { $schema: _schema, ...entitySchema } = dataSchema as Record<string, unknown>\n\n const schema = z.object({\n data: z.fromJSONSchema(entitySchema as unknown as z.core.JSONSchema.JSONSchema),\n ...controls,\n })\n const standard = (schema as unknown as StandardSchemaWithJSON)['~standard']\n\n return {\n '~standard': {\n ...standard,\n jsonSchema: {\n ...standard.jsonSchema,\n input: (options) => {\n // Start from zod's JSON Schema for the whole input, then replace its lossy `data` schema with\n // the sanitized entity schema. The entity's `$defs` move to the root so the `$ref`s resolve.\n const generated = standard.jsonSchema.input(options)\n const { $defs, ...entityBody } = entitySchema\n ;(generated.properties as Record<string, unknown>).data = {\n ...entityBody,\n description: dataDescription,\n }\n if ($defs) {\n generated.$defs = $defs as object\n } else {\n delete generated.$defs\n }\n return generated\n },\n },\n },\n } as StandardSchemaWithJSON<\n { data: Record<string, unknown> } & Omit<z.output<typeof schema>, 'data'>\n >\n}\n"],"names":["z","buildToolInput","controls","dataDescription","dataSchema","$schema","_schema","entitySchema","schema","object","data","fromJSONSchema","standard","jsonSchema","input","options","generated","$defs","entityBody","properties","description"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAIvB;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMC,iBAAiB,CAAkC,EAC9DC,QAAQ,EACRC,eAAe,EACfC,UAAU,EAMX;IACC,wGAAwG;IACxG,uGAAuG;IACvG,MAAM,EAAEC,SAASC,OAAO,EAAE,GAAGC,cAAc,GAAGH;IAE9C,MAAMI,SAASR,EAAES,MAAM,CAAC;QACtBC,MAAMV,EAAEW,cAAc,CAACJ;QACvB,GAAGL,QAAQ;IACb;IACA,MAAMU,WAAW,AAACJ,MAA4C,CAAC,YAAY;IAE3E,OAAO;QACL,aAAa;YACX,GAAGI,QAAQ;YACXC,YAAY;gBACV,GAAGD,SAASC,UAAU;gBACtBC,OAAO,CAACC;oBACN,8FAA8F;oBAC9F,6FAA6F;oBAC7F,MAAMC,YAAYJ,SAASC,UAAU,CAACC,KAAK,CAACC;oBAC5C,MAAM,EAAEE,KAAK,EAAE,GAAGC,YAAY,GAAGX;oBAC/BS,UAAUG,UAAU,CAA6BT,IAAI,GAAG;wBACxD,GAAGQ,UAAU;wBACbE,aAAajB;oBACf;oBACA,IAAIc,OAAO;wBACTD,UAAUC,KAAK,GAAGA;oBACpB,OAAO;wBACL,OAAOD,UAAUC,KAAK;oBACxB;oBACA,OAAOD;gBACT;YACF;QACF;IACF;AAGF,EAAC"}