@payloadcms/plugin-mcp 4.0.0-internal.4cbdd50 → 4.0.0-internal.543da65

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 (150) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/endpoint/access.d.ts +2 -7
  3. package/dist/endpoint/access.d.ts.map +1 -1
  4. package/dist/endpoint/access.js +4 -11
  5. package/dist/endpoint/access.js.map +1 -1
  6. package/dist/endpoint/index.d.ts +1 -1
  7. package/dist/endpoint/index.d.ts.map +1 -1
  8. package/dist/endpoint/index.js +57 -17
  9. package/dist/endpoint/index.js.map +1 -1
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/mcp/buildMcpServer.d.ts +4 -4
  15. package/dist/mcp/buildMcpServer.d.ts.map +1 -1
  16. package/dist/mcp/buildMcpServer.js +32 -10
  17. package/dist/mcp/buildMcpServer.js.map +1 -1
  18. package/dist/mcp/builtin/collections/countTool.d.ts.map +1 -1
  19. package/dist/mcp/builtin/collections/countTool.js +1 -2
  20. package/dist/mcp/builtin/collections/countTool.js.map +1 -1
  21. package/dist/mcp/builtin/collections/countVersionsTool.d.ts.map +1 -1
  22. package/dist/mcp/builtin/collections/countVersionsTool.js +1 -2
  23. package/dist/mcp/builtin/collections/countVersionsTool.js.map +1 -1
  24. package/dist/mcp/builtin/collections/createTool.d.ts.map +1 -1
  25. package/dist/mcp/builtin/collections/createTool.js +1 -2
  26. package/dist/mcp/builtin/collections/createTool.js.map +1 -1
  27. package/dist/mcp/builtin/collections/deleteTool.d.ts.map +1 -1
  28. package/dist/mcp/builtin/collections/deleteTool.js +1 -2
  29. package/dist/mcp/builtin/collections/deleteTool.js.map +1 -1
  30. package/dist/mcp/builtin/collections/duplicateTool.d.ts.map +1 -1
  31. package/dist/mcp/builtin/collections/duplicateTool.js +1 -2
  32. package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
  33. package/dist/mcp/builtin/collections/findDistinctTool.d.ts.map +1 -1
  34. package/dist/mcp/builtin/collections/findDistinctTool.js +1 -2
  35. package/dist/mcp/builtin/collections/findDistinctTool.js.map +1 -1
  36. package/dist/mcp/builtin/collections/findTool.d.ts.map +1 -1
  37. package/dist/mcp/builtin/collections/findTool.js +2 -3
  38. package/dist/mcp/builtin/collections/findTool.js.map +1 -1
  39. package/dist/mcp/builtin/collections/findVersionByIDTool.d.ts.map +1 -1
  40. package/dist/mcp/builtin/collections/findVersionByIDTool.js +1 -2
  41. package/dist/mcp/builtin/collections/findVersionByIDTool.js.map +1 -1
  42. package/dist/mcp/builtin/collections/findVersionsTool.d.ts.map +1 -1
  43. package/dist/mcp/builtin/collections/findVersionsTool.js +1 -2
  44. package/dist/mcp/builtin/collections/findVersionsTool.js.map +1 -1
  45. package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
  46. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +21 -3
  47. package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
  48. package/dist/mcp/builtin/collections/restoreVersionTool.d.ts.map +1 -1
  49. package/dist/mcp/builtin/collections/restoreVersionTool.js +1 -2
  50. package/dist/mcp/builtin/collections/restoreVersionTool.js.map +1 -1
  51. package/dist/mcp/builtin/collections/updateTool.d.ts.map +1 -1
  52. package/dist/mcp/builtin/collections/updateTool.js +2 -3
  53. package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
  54. package/dist/mcp/builtin/getConfigInfoTool.d.ts.map +1 -1
  55. package/dist/mcp/builtin/getConfigInfoTool.js +2 -5
  56. package/dist/mcp/builtin/getConfigInfoTool.js.map +1 -1
  57. package/dist/mcp/builtin/globals/countVersionsTool.d.ts.map +1 -1
  58. package/dist/mcp/builtin/globals/countVersionsTool.js +1 -2
  59. package/dist/mcp/builtin/globals/countVersionsTool.js.map +1 -1
  60. package/dist/mcp/builtin/globals/findTool.d.ts.map +1 -1
  61. package/dist/mcp/builtin/globals/findTool.js +2 -2
  62. package/dist/mcp/builtin/globals/findTool.js.map +1 -1
  63. package/dist/mcp/builtin/globals/findVersionByIDTool.d.ts.map +1 -1
  64. package/dist/mcp/builtin/globals/findVersionByIDTool.js +1 -2
  65. package/dist/mcp/builtin/globals/findVersionByIDTool.js.map +1 -1
  66. package/dist/mcp/builtin/globals/findVersionsTool.d.ts.map +1 -1
  67. package/dist/mcp/builtin/globals/findVersionsTool.js +1 -2
  68. package/dist/mcp/builtin/globals/findVersionsTool.js.map +1 -1
  69. package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
  70. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +21 -3
  71. package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
  72. package/dist/mcp/builtin/globals/restoreVersionTool.d.ts.map +1 -1
  73. package/dist/mcp/builtin/globals/restoreVersionTool.js +1 -2
  74. package/dist/mcp/builtin/globals/restoreVersionTool.js.map +1 -1
  75. package/dist/mcp/builtin/globals/updateTool.d.ts.map +1 -1
  76. package/dist/mcp/builtin/globals/updateTool.js +2 -2
  77. package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
  78. package/dist/mcp/builtin/validateEntityData.js +1 -1
  79. package/dist/mcp/builtin/validateEntityData.js.map +1 -1
  80. package/dist/mcp/sanitizeMCPConfig.d.ts.map +1 -1
  81. package/dist/mcp/sanitizeMCPConfig.js +1 -0
  82. package/dist/mcp/sanitizeMCPConfig.js.map +1 -1
  83. package/dist/stdio.d.ts +3 -4
  84. package/dist/stdio.d.ts.map +1 -1
  85. package/dist/stdio.js +59 -41
  86. package/dist/stdio.js.map +1 -1
  87. package/dist/types.d.ts +57 -9
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/types.js +2 -4
  90. package/dist/types.js.map +1 -1
  91. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
  92. package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
  93. package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
  94. package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
  95. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +5 -3
  96. package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -1
  97. package/dist/utils/schemaConversion/getEntityInputSchema.js +44 -12
  98. package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -1
  99. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +5 -10
  100. package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -1
  101. package/dist/utils/schemaConversion/sanitizeEntitySchema.js +15 -95
  102. package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -1
  103. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +15 -40
  104. package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -1
  105. package/package.json +8 -10
  106. package/src/endpoint/access.ts +3 -10
  107. package/src/endpoint/index.ts +45 -16
  108. package/src/index.ts +4 -4
  109. package/src/mcp/buildMcpServer.ts +40 -20
  110. package/src/mcp/builtin/collections/countTool.ts +1 -2
  111. package/src/mcp/builtin/collections/countVersionsTool.ts +1 -2
  112. package/src/mcp/builtin/collections/createTool.ts +1 -2
  113. package/src/mcp/builtin/collections/deleteTool.ts +1 -2
  114. package/src/mcp/builtin/collections/duplicateTool.ts +1 -2
  115. package/src/mcp/builtin/collections/findDistinctTool.ts +1 -2
  116. package/src/mcp/builtin/collections/findTool.ts +2 -3
  117. package/src/mcp/builtin/collections/findVersionByIDTool.ts +1 -2
  118. package/src/mcp/builtin/collections/findVersionsTool.ts +1 -2
  119. package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +25 -8
  120. package/src/mcp/builtin/collections/restoreVersionTool.ts +1 -2
  121. package/src/mcp/builtin/collections/updateTool.ts +2 -3
  122. package/src/mcp/builtin/getConfigInfoTool.ts +2 -4
  123. package/src/mcp/builtin/globals/countVersionsTool.ts +1 -2
  124. package/src/mcp/builtin/globals/findTool.ts +2 -2
  125. package/src/mcp/builtin/globals/findVersionByIDTool.ts +1 -2
  126. package/src/mcp/builtin/globals/findVersionsTool.ts +1 -2
  127. package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +25 -3
  128. package/src/mcp/builtin/globals/restoreVersionTool.ts +1 -2
  129. package/src/mcp/builtin/globals/updateTool.ts +2 -2
  130. package/src/mcp/builtin/validateEntityData.ts +1 -1
  131. package/src/mcp/sanitizeMCPConfig.ts +1 -0
  132. package/src/stdio.ts +59 -42
  133. package/src/types.ts +57 -9
  134. package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
  135. package/src/utils/schemaConversion/getEntityInputSchema.ts +45 -27
  136. package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +12 -19
  137. package/src/utils/schemaConversion/sanitizeEntitySchema.ts +17 -114
  138. package/dist/@types/assets.d.js +0 -2
  139. package/dist/@types/assets.d.js.map +0 -1
  140. package/dist/utils/localAPIDefaults.d.ts +0 -20
  141. package/dist/utils/localAPIDefaults.d.ts.map +0 -1
  142. package/dist/utils/localAPIDefaults.js +0 -19
  143. package/dist/utils/localAPIDefaults.js.map +0 -1
  144. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts +0 -7
  145. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.d.ts.map +0 -1
  146. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js +0 -20
  147. package/dist/utils/schemaConversion/removeVirtualFieldsFromSchema.js.map +0 -1
  148. package/src/@types/assets.d.ts +0 -3
  149. package/src/utils/localAPIDefaults.ts +0 -22
  150. package/src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts +0 -27
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n JsonSchemaType,\n McpServer,\n ResourceTemplate,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server'\nimport type {\n AuthCollectionSlug,\n CollectionSlug,\n GlobalSlug,\n MaybePromise,\n PayloadRequest,\n SanitizedPermissions,\n TypedUser,\n} from 'payload'\n\nimport type { GetAuthorizedMCPArgs } from './endpoint/access.js'\nimport type {\n MCPCollectionAuthToolName,\n MCPCollectionBuiltinName,\n MCPGlobalBuiltinName,\n} from './mcp/builtinTools.js'\n\nexport type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }\n\n/** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */\nexport type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }\n\n/**\n * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw\n * JSON Schema literal, or a Standard Schema instance (Zod, Valibot, …).\n */\nexport type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON\n\nexport type MCPToolResponse = {\n content: ContentBlock[]\n /**\n * If available, return the document fetched within the\n * mcp tool. This is threaded as an additional argument to\n * overrideResponse functions and stripped before going on the wire.\n */\n doc?: Record<string, unknown>\n} & Pick<CallToolResult, '_meta' | 'isError' | 'structuredContent'>\n\nexport type MCPResponseOverride = (\n response: MCPToolResponse,\n doc: Record<string, unknown>,\n req: PayloadRequest,\n) => MCPToolResponse\n\n/**\n * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets\n * its inferred output; anything else falls back to `Record<string, unknown>`.\n */\nexport type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON extends TSchema\n ? Record<string, unknown>\n : StandardSchemaWithJSON.InferOutput<TSchema>\n : Record<string, unknown>\n\nexport type MCPAccessArgs = {\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}\n\nexport type CollectionMCPAccessArgs = {\n collectionSlug: CollectionSlug\n} & MCPAccessArgs\n\nexport type GlobalMCPAccessArgs = {\n globalSlug: GlobalSlug\n} & MCPAccessArgs\n\nexport type ToolHandlerArgs<TSchema = undefined> = {\n authorizedMCP: AuthorizedMCP\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type CollectionToolHandlerArgs<TSchema = undefined> = {\n collectionSlug: CollectionSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type GlobalToolHandlerArgs<TSchema = undefined> = {\n globalSlug: GlobalSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description: string\n handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n /**\n * Override the return value of the tool handler\n */\n overrideResponse?: MCPResponseOverride\n}\n\nexport type CollectionTool<\n TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,\n> = {\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n} & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\nexport type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =\n {\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\n/**\n * Configures (or disables) a built-in tool without replacing it.\n * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a\n * required handler) from being silently accepted at a built-in key slot.\n */\nexport type MCPBuiltInCollectionToolOverride = {\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\n/**\n * Value at a custom (non-built-in) tool key. Either the tool itself, or `false`\n * to disable it (useful when one plugin defines a custom tool and another\n * wants to opt out per-collection).\n */\nexport type MCPTopLevelToolEntry = Tool\n\nexport type MCPCollectionToolsMap = {\n [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined\n} & {\n [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride\n}\n\nexport type MCPAuthCollectionToolsMap = {\n [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true\n} & MCPCollectionToolsMap\n\n/** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */\nexport type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends AuthCollectionSlug\n ? MCPAuthCollectionToolsMap\n : MCPCollectionToolsMap\n\nexport type MCPGlobalToolsMap = {\n [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined\n} & {\n [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride\n}\n\nexport type MCPTopLevelToolsMap = Record<string, Tool>\n\nexport type PromptHandlerArgs<TSchema = undefined> = {\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n argsSchema: TSchema\n description: string\n handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{\n messages: Array<{ content: { text: string; type: 'text' }; role: 'assistant' | 'user' }>\n }>\n title: string\n}\n\nexport type ResourceHandlerArgs = {\n /** Variables extracted from a `ResourceTemplate` URI. Empty for static-URI resources. */\n params: Record<string, string>\n req: PayloadRequest\n serverContext: ServerContext\n uri: URL\n}\n\nexport type Resource = {\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n description: string\n handler: (args: ResourceHandlerArgs) => MaybePromise<{\n contents: Array<{ text: string; uri: string }>\n }>\n mimeType: string\n title: string\n uri: ResourceTemplate | string\n}\n\nexport type MCPPluginCollectionConfig<TSlug extends CollectionSlug> = {\n description?: string\n /** Fallback for built-in tools that don't set their own `overrideResponse`. */\n overrideResponse?: MCPResponseOverride\n tools?: MCPToolsMapForCollection<TSlug>\n}\n\nexport type MCPPluginGlobalConfig = {\n description?: string\n overrideResponse?: MCPResponseOverride\n tools?: MCPGlobalToolsMap\n}\n\n/**\n * The user-facing config shape passed to `mcpPlugin({ ... })`. Tools, prompts,\n * resources, and per-collection/global tool maps live in their own nested\n * fields. `sanitizeMCPConfig` flattens those into `items` and applies defaults\n * to produce a `SanitizedMCPPluginConfig` — the form every internal consumer\n * actually works with.\n */\nexport type MCPPluginConfig = {\n collections?: {\n [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>\n }\n /** Skip MCP endpoint registration. */\n disabled?: boolean\n globals?: {\n [Slug in GlobalSlug]?: MCPPluginGlobalConfig\n }\n mcp?: {\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /** Replace the default MCP authorization resolver. */\n overrideGetAuthorizedMCP?: (\n args: {\n pluginConfig: SanitizedMCPPluginConfig\n } & GetAuthorizedMCPArgs,\n ) => MaybePromise<AuthorizedMCP>\n prompts?: Record<string, Prompt>\n resources?: Record<string, Resource>\n /** Cross-cutting tools (not scoped to any collection or global). */\n tools?: MCPTopLevelToolsMap\n}\n\nexport type SanitizedMCPPluginConfig = {\n items: MCPItem[]\n} & Pick<MCPPluginConfig, 'disabled' | 'mcp' | 'overrideGetAuthorizedMCP'>\n\nexport type MCPServerOptions = {\n options?: ConstructorParameters<typeof McpServer>[1]\n serverInfo?: Partial<ConstructorParameters<typeof McpServer>[0]>\n}\n\n/**\n * One MCP primitive plus the metadata needed for config-driven filtering and\n * registration.\n *\n * - `configKey`: the config identifier, e.g. `find` or `echo`.\n * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.\n * - `label`: human-readable display text.\n */\nexport type MCPItemBase = {\n configKey: string\n label: string\n mcpName: string\n}\n\nexport type CollectionMCPItem = {\n collectionSlug: CollectionSlug\n tool: CollectionTool\n type: 'collectionTool'\n} & MCPItemBase\n\nexport type GlobalMCPItem = {\n globalSlug: GlobalSlug\n tool: GlobalTool\n type: 'globalTool'\n} & MCPItemBase\n\nexport type MCPItem =\n | ({\n prompt: Prompt\n type: 'prompt'\n } & MCPItemBase)\n | ({\n resource: Resource\n type: 'resource'\n } & MCPItemBase)\n | ({\n tool: Tool\n type: 'tool'\n } & MCPItemBase)\n | CollectionMCPItem\n | GlobalMCPItem\n\n/**\n * The caller's identity + the MCP items authorized for this request. Disabled\n * items and items blocked by access callbacks or Payload operation access are\n * absent from `items`. Tool handlers receive this via `args.authorizedMCP` so\n * they can spread `localAPIDefaults(authorizedMCP)` into every local API call.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n user: null | TypedUser\n}\n"],"names":[],"mappings":"AA6SA;;;;;CAKC,GACD,WAIC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type {\n CallToolResult,\n ContentBlock,\n JsonSchemaType,\n McpServer,\n ResourceTemplate,\n ServerContext,\n StandardSchemaWithJSON,\n ToolAnnotations,\n} from '@modelcontextprotocol/server'\nimport type {\n AuthCollectionSlug,\n CollectionSlug,\n GlobalSlug,\n MaybePromise,\n PayloadRequest,\n SanitizedPermissions,\n} from 'payload'\n\nimport type { GetAuthorizedMCPArgs } from './endpoint/access.js'\nimport type {\n MCPCollectionAuthToolName,\n MCPCollectionBuiltinName,\n MCPGlobalBuiltinName,\n} from './mcp/builtinTools.js'\n\nexport type { MCPCollectionAuthToolName, MCPCollectionBuiltinName, MCPGlobalBuiltinName }\n\n/** Re-exported from `@modelcontextprotocol/server` — common MCP types used in plugin config. */\nexport type { JsonSchemaType, StandardSchemaWithJSON, ToolAnnotations }\n\n/**\n * What a tool's `input` (or a prompt's `argsSchema`) can be — either a raw\n * JSON Schema 2020-12 literal, or a Standard Schema instance (Zod, Valibot, …).\n * Raw schemas may omit `$schema`; when present it must declare the 2020-12 dialect.\n */\nexport type ToolInputSchema = JsonSchemaType | StandardSchemaWithJSON\n\nexport type MCPToolResponse = {\n content: ContentBlock[]\n /**\n * If available, return the document fetched within the\n * mcp tool. This is threaded as an additional argument to\n * overrideResponse functions and stripped before going on the wire.\n */\n doc?: Record<string, unknown>\n} & Pick<CallToolResult, '_meta' | 'isError' | 'structuredContent'>\n\nexport type MCPResponseOverride = (\n response: MCPToolResponse,\n doc: Record<string, unknown>,\n req: PayloadRequest,\n) => MCPToolResponse\n\nexport type MCPAfterToolCallHook = (args: {\n input: unknown\n req: PayloadRequest\n response: MCPToolResponse\n toolName: string\n}) => MaybePromise<MCPToolResponse>\n\n/**\n * The handler's `input` type. A specific Standard Schema (Zod, Valibot, …) gets\n * its inferred output; anything else falls back to `Record<string, unknown>`.\n */\nexport type TypedInput<TSchema> = TSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON extends TSchema\n ? Record<string, unknown>\n : StandardSchemaWithJSON.InferOutput<TSchema>\n : Record<string, unknown>\n\nexport type MCPAccessArgs = {\n permissions?: SanitizedPermissions\n req: PayloadRequest\n}\n\nexport type CollectionMCPAccessArgs = {\n collectionSlug: CollectionSlug\n} & MCPAccessArgs\n\nexport type GlobalMCPAccessArgs = {\n globalSlug: GlobalSlug\n} & MCPAccessArgs\n\nexport type ToolHandlerArgs<TSchema = undefined> = {\n authorizedMCP: AuthorizedMCP\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type CollectionToolHandlerArgs<TSchema = undefined> = {\n collectionSlug: CollectionSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type GlobalToolHandlerArgs<TSchema = undefined> = {\n globalSlug: GlobalSlug\n} & ToolHandlerArgs<TSchema>\n\nexport type Tool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> = {\n /**\n * Runs while authorizing each MCP request, before the tool is advertised or called. Return\n * `false` to make the tool unavailable for that request. This is skipped when `overrideAccess`\n * is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description: string\n handler: (args: ToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n /**\n * Override the return value of the tool handler\n */\n overrideResponse?: MCPResponseOverride\n}\n\nexport type CollectionTool<\n TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined,\n> = {\n /**\n * Runs while authorizing each MCP request for this collection. Return `false` to reject calls\n * to this tool for the collection. The shared tool is not advertised when no collections allow\n * it, but can remain advertised when it is available for another collection. This is skipped\n * when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: CollectionToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n} & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\nexport type GlobalTool<TSchema extends ToolInputSchema | undefined = ToolInputSchema | undefined> =\n {\n /**\n * Runs while authorizing each MCP request for this global. Return `false` to reject calls to\n * this tool for the global. The shared tool is not advertised when no globals allow it, but\n * can remain advertised when it is available for another global. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n handler: (args: GlobalToolHandlerArgs<TSchema>) => MaybePromise<MCPToolResponse>\n input?: TSchema\n } & Pick<Tool, 'annotations' | 'description' | 'overrideResponse'>\n\n/**\n * Configures (or disables) a built-in tool without replacing it.\n * `handler?: never` prevents a full `CollectionTool`/`GlobalTool` (which has a\n * required handler) from being silently accepted at a built-in key slot.\n */\nexport type MCPBuiltInCollectionToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this collection. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: CollectionMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\nexport type MCPBuiltInGlobalToolOverride = {\n /**\n * Replaces the built-in tool's access check. Return `false` to make the tool unavailable for\n * this global. This is skipped when `overrideAccess` is enabled.\n */\n access?: (args: GlobalMCPAccessArgs) => MaybePromise<boolean>\n annotations?: ToolAnnotations\n description?: string\n handler?: never\n overrideResponse?: MCPResponseOverride\n}\n\n/**\n * Value at a custom (non-built-in) tool key. Either the tool itself, or `false`\n * to disable it (useful when one plugin defines a custom tool and another\n * wants to opt out per-collection).\n */\nexport type MCPTopLevelToolEntry = Tool\n\nexport type MCPCollectionToolsMap = {\n [customToolName: string]: boolean | CollectionTool | MCPBuiltInCollectionToolOverride | undefined\n} & {\n [K in MCPCollectionBuiltinName]?: false | MCPBuiltInCollectionToolOverride\n}\n\nexport type MCPAuthCollectionToolsMap = {\n [K in MCPCollectionAuthToolName]?: MCPBuiltInCollectionToolOverride | true\n} & MCPCollectionToolsMap\n\n/** Auth-enabled collections get auth-tool name autocomplete; others get CRUD-only. */\nexport type MCPToolsMapForCollection<Slug extends CollectionSlug> = Slug extends AuthCollectionSlug\n ? MCPAuthCollectionToolsMap\n : MCPCollectionToolsMap\n\nexport type MCPGlobalToolsMap = {\n [customToolName: string]: boolean | GlobalTool | MCPBuiltInGlobalToolOverride | undefined\n} & {\n [K in MCPGlobalBuiltinName]?: false | MCPBuiltInGlobalToolOverride\n}\n\nexport type MCPTopLevelToolsMap = Record<string, Tool>\n\nexport type PromptHandlerArgs<TSchema = undefined> = {\n input: TypedInput<TSchema>\n req: PayloadRequest\n serverContext: ServerContext\n}\n\nexport type Prompt<TSchema extends ToolInputSchema = ToolInputSchema> = {\n /**\n * Runs while authorizing each MCP request, before the prompt is advertised or used. Return\n * `false` to make the prompt unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n argsSchema: TSchema\n description: string\n handler: (args: PromptHandlerArgs<TSchema>) => MaybePromise<{\n messages: Array<{ content: { text: string; type: 'text' }; role: 'assistant' | 'user' }>\n }>\n title: string\n}\n\nexport type ResourceHandlerArgs = {\n /** Variables extracted from a `ResourceTemplate` URI. Empty for static-URI resources. */\n params: Record<string, string>\n req: PayloadRequest\n serverContext: ServerContext\n uri: URL\n}\n\nexport type Resource = {\n /**\n * Runs while authorizing each MCP request, before the resource is advertised or read. Return\n * `false` to make the resource unavailable for that request. This is skipped when\n * `overrideAccess` is enabled.\n */\n access?: (args: MCPAccessArgs) => MaybePromise<boolean>\n description: string\n handler: (args: ResourceHandlerArgs) => MaybePromise<{\n contents: Array<{ text: string; uri: string }>\n }>\n mimeType: string\n title: string\n uri: ResourceTemplate | string\n}\n\nexport type MCPPluginCollectionConfig<TSlug extends CollectionSlug> = {\n description?: string\n /** Fallback for built-in tools that don't set their own `overrideResponse`. */\n overrideResponse?: MCPResponseOverride\n tools?: MCPToolsMapForCollection<TSlug>\n}\n\nexport type MCPPluginGlobalConfig = {\n description?: string\n overrideResponse?: MCPResponseOverride\n tools?: MCPGlobalToolsMap\n}\n\n/**\n * The user-facing config shape passed to `mcpPlugin({ ... })`. Tools, prompts,\n * resources, and per-collection/global tool maps live in their own nested\n * fields. `sanitizeMCPConfig` flattens those into `items` and applies defaults\n * to produce a `SanitizedMCPPluginConfig` — the form every internal consumer\n * actually works with.\n */\nexport type MCPPluginConfig = {\n collections?: {\n [Slug in CollectionSlug]?: MCPPluginCollectionConfig<Slug>\n }\n /** Skip MCP endpoint registration. */\n disabled?: boolean\n globals?: {\n [Slug in GlobalSlug]?: MCPPluginGlobalConfig\n }\n hooks?: {\n /** Transform a tool response after its handler returns */\n afterToolCall?: MCPAfterToolCallHook[]\n }\n mcp?: {\n serverOptions?: MCPServerOptions\n verboseLogs?: boolean\n }\n /**\n * Replace the default MCP authorization resolver.\n *\n * This hook replaces the default authentication flow. It must set `req.user` to the\n * authenticated Payload user, or to `null` for an anonymous caller, before returning.\n */\n overrideGetAuthorizedMCP?: (\n args: {\n pluginConfig: SanitizedMCPPluginConfig\n } & GetAuthorizedMCPArgs,\n ) => MaybePromise<AuthorizedMCP>\n prompts?: Record<string, Prompt>\n resources?: Record<string, Resource>\n /** Cross-cutting tools (not scoped to any collection or global). */\n tools?: MCPTopLevelToolsMap\n}\n\nexport type SanitizedMCPPluginConfig = {\n items: MCPItem[]\n} & Pick<MCPPluginConfig, 'disabled' | 'hooks' | 'mcp' | 'overrideGetAuthorizedMCP'>\n\nexport type MCPServerOptions = {\n options?: ConstructorParameters<typeof McpServer>[1]\n serverInfo?: Partial<ConstructorParameters<typeof McpServer>[0]>\n}\n\n/**\n * One MCP primitive plus the metadata needed for config-driven filtering and\n * registration.\n *\n * - `configKey`: the config identifier, e.g. `find` or `echo`.\n * - `mcpName`: the MCP wire name, e.g. `findDocuments` or `echo`.\n * - `label`: human-readable display text.\n */\nexport type MCPItemBase = {\n configKey: string\n label: string\n mcpName: string\n}\n\nexport type CollectionMCPItem = {\n collectionSlug: CollectionSlug\n tool: CollectionTool\n type: 'collectionTool'\n} & MCPItemBase\n\nexport type GlobalMCPItem = {\n globalSlug: GlobalSlug\n tool: GlobalTool\n type: 'globalTool'\n} & MCPItemBase\n\nexport type MCPItem =\n | ({\n prompt: Prompt\n type: 'prompt'\n } & MCPItemBase)\n | ({\n resource: Resource\n type: 'resource'\n } & MCPItemBase)\n | ({\n tool: Tool\n type: 'tool'\n } & MCPItemBase)\n | CollectionMCPItem\n | GlobalMCPItem\n\n/**\n * The MCP items and access mode authorized for this request. The authenticated user is available\n * as `req.user`.\n */\nexport type AuthorizedMCP = {\n items: MCPItem[]\n overrideAccess: boolean\n}\n"],"names":[],"mappings":"AAgWA;;;CAGC,GACD,WAGC"}
@@ -0,0 +1,28 @@
1
+ import type { FlattenedBlock, FlattenedField, Operation, SanitizedDocumentPermissions } from 'payload';
2
+ type FieldOperation = Exclude<Operation, 'delete'>;
3
+ type AllowedFieldOperations = Record<FieldOperation, boolean>;
4
+ /**
5
+ * Filters fields using the access results in `permissions`. `shouldExcludeField` receives the
6
+ * operations allowed by the entity, field, and its parents and decides whether to remove the
7
+ * field.
8
+ *
9
+ * Arrays, groups, named tabs, and blocks are filtered recursively. Rows and unnamed tabs are
10
+ * flattened by Payload, so their children are filtered at the containing level.
11
+ *
12
+ * @example Include fields writable through any collection operation the user can perform.
13
+ * ```ts
14
+ * filterFieldsByAccess({
15
+ * fields,
16
+ * permissions: collectionPermissions,
17
+ * shouldExcludeField: ({ create, update }) => !create && !update,
18
+ * })
19
+ * ```
20
+ */
21
+ export declare const filterFieldsByAccess: ({ blocks, fields, permissions, shouldExcludeField, }: {
22
+ blocks?: FlattenedBlock[];
23
+ fields: FlattenedField[];
24
+ permissions: SanitizedDocumentPermissions;
25
+ shouldExcludeField: (allowedOperations: AllowedFieldOperations) => boolean;
26
+ }) => FlattenedField[];
27
+ export {};
28
+ //# sourceMappingURL=filterFieldsByAccess.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filterFieldsByAccess.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/filterFieldsByAccess.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACd,SAAS,EACT,4BAA4B,EAE7B,MAAM,SAAS,CAAA;AAEhB,KAAK,cAAc,GAAG,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAA;AAClD,KAAK,sBAAsB,GAAG,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAA;AAE7D;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,oBAAoB,GAAI,sDAKlC;IACD,MAAM,CAAC,EAAE,cAAc,EAAE,CAAA;IACzB,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,WAAW,EAAE,4BAA4B,CAAA;IACzC,kBAAkB,EAAE,CAAC,iBAAiB,EAAE,sBAAsB,KAAK,OAAO,CAAA;CAC3E,KAAG,cAAc,EAoFjB,CAAA"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Filters fields using the access results in `permissions`. `shouldExcludeField` receives the
3
+ * operations allowed by the entity, field, and its parents and decides whether to remove the
4
+ * field.
5
+ *
6
+ * Arrays, groups, named tabs, and blocks are filtered recursively. Rows and unnamed tabs are
7
+ * flattened by Payload, so their children are filtered at the containing level.
8
+ *
9
+ * @example Include fields writable through any collection operation the user can perform.
10
+ * ```ts
11
+ * filterFieldsByAccess({
12
+ * fields,
13
+ * permissions: collectionPermissions,
14
+ * shouldExcludeField: ({ create, update }) => !create && !update,
15
+ * })
16
+ * ```
17
+ */ export const filterFieldsByAccess = ({ blocks, fields, permissions, shouldExcludeField })=>{
18
+ const filterFields = (nestedFields, nestedPermissions, parentAllowedOperations)=>{
19
+ const accessibleFields = [];
20
+ for (const field of nestedFields){
21
+ const fieldPermissions = nestedPermissions === true ? true : nestedPermissions?.[field.name];
22
+ const isOperationAllowed = (operation)=>parentAllowedOperations[operation] && (fieldPermissions === true || fieldPermissions?.[operation] === true);
23
+ const allowedOperations = {
24
+ create: isOperationAllowed('create'),
25
+ read: isOperationAllowed('read'),
26
+ update: isOperationAllowed('update')
27
+ };
28
+ if (shouldExcludeField(allowedOperations)) {
29
+ continue;
30
+ }
31
+ if (field.type === 'blocks') {
32
+ const accessibleBlocks = [];
33
+ for (const blockOrReference of field.blocks){
34
+ const block = typeof blockOrReference === 'string' ? blocks?.find(({ slug })=>slug === blockOrReference) : blockOrReference;
35
+ if (!block) {
36
+ continue;
37
+ }
38
+ const blockPermissions = fieldPermissions === true ? true : fieldPermissions?.blocks === true ? true : fieldPermissions?.blocks?.[block.slug];
39
+ accessibleBlocks.push({
40
+ ...block,
41
+ flattenedFields: filterFields(block.flattenedFields, blockPermissions === true ? true : blockPermissions?.fields, allowedOperations)
42
+ });
43
+ }
44
+ if (accessibleBlocks.length === 0) {
45
+ continue;
46
+ }
47
+ accessibleFields.push({
48
+ ...field,
49
+ blocks: accessibleBlocks
50
+ });
51
+ continue;
52
+ }
53
+ if (field.type === 'array' || field.type === 'group' || field.type === 'tab') {
54
+ accessibleFields.push({
55
+ ...field,
56
+ flattenedFields: filterFields(field.flattenedFields, fieldPermissions === true ? true : fieldPermissions?.fields, allowedOperations)
57
+ });
58
+ continue;
59
+ }
60
+ accessibleFields.push(field);
61
+ }
62
+ return accessibleFields;
63
+ };
64
+ return filterFields(fields, permissions.fields, {
65
+ create: 'create' in permissions && permissions.create === true,
66
+ read: permissions.read === true,
67
+ update: permissions.update === true
68
+ });
69
+ };
70
+
71
+ //# sourceMappingURL=filterFieldsByAccess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/utils/schemaConversion/filterFieldsByAccess.ts"],"sourcesContent":["import type {\n FlattenedBlock,\n FlattenedField,\n Operation,\n SanitizedDocumentPermissions,\n SanitizedFieldsPermissions,\n} from 'payload'\n\ntype FieldOperation = Exclude<Operation, 'delete'>\ntype AllowedFieldOperations = Record<FieldOperation, boolean>\n\n/**\n * Filters fields using the access results in `permissions`. `shouldExcludeField` receives the\n * operations allowed by the entity, field, and its parents and decides whether to remove the\n * field.\n *\n * Arrays, groups, named tabs, and blocks are filtered recursively. Rows and unnamed tabs are\n * flattened by Payload, so their children are filtered at the containing level.\n *\n * @example Include fields writable through any collection operation the user can perform.\n * ```ts\n * filterFieldsByAccess({\n * fields,\n * permissions: collectionPermissions,\n * shouldExcludeField: ({ create, update }) => !create && !update,\n * })\n * ```\n */\nexport const filterFieldsByAccess = ({\n blocks,\n fields,\n permissions,\n shouldExcludeField,\n}: {\n blocks?: FlattenedBlock[]\n fields: FlattenedField[]\n permissions: SanitizedDocumentPermissions\n shouldExcludeField: (allowedOperations: AllowedFieldOperations) => boolean\n}): FlattenedField[] => {\n const filterFields = (\n nestedFields: FlattenedField[],\n nestedPermissions: SanitizedFieldsPermissions | undefined,\n parentAllowedOperations: AllowedFieldOperations,\n ): FlattenedField[] => {\n const accessibleFields: FlattenedField[] = []\n\n for (const field of nestedFields) {\n const fieldPermissions = nestedPermissions === true ? true : nestedPermissions?.[field.name]\n const isOperationAllowed = (operation: FieldOperation): boolean =>\n parentAllowedOperations[operation] &&\n (fieldPermissions === true || fieldPermissions?.[operation] === true)\n const allowedOperations: AllowedFieldOperations = {\n create: isOperationAllowed('create'),\n read: isOperationAllowed('read'),\n update: isOperationAllowed('update'),\n }\n\n if (shouldExcludeField(allowedOperations)) {\n continue\n }\n\n if (field.type === 'blocks') {\n const accessibleBlocks: (FlattenedBlock | string)[] = []\n\n for (const blockOrReference of field.blocks) {\n const block =\n typeof blockOrReference === 'string'\n ? blocks?.find(({ slug }) => slug === blockOrReference)\n : blockOrReference\n\n if (!block) {\n continue\n }\n\n const blockPermissions =\n fieldPermissions === true\n ? true\n : fieldPermissions?.blocks === true\n ? true\n : fieldPermissions?.blocks?.[block.slug]\n\n accessibleBlocks.push({\n ...block,\n flattenedFields: filterFields(\n block.flattenedFields,\n blockPermissions === true ? true : blockPermissions?.fields,\n allowedOperations,\n ),\n })\n }\n\n if (accessibleBlocks.length === 0) {\n continue\n }\n\n accessibleFields.push({ ...field, blocks: accessibleBlocks })\n continue\n }\n\n if (field.type === 'array' || field.type === 'group' || field.type === 'tab') {\n accessibleFields.push({\n ...field,\n flattenedFields: filterFields(\n field.flattenedFields,\n fieldPermissions === true ? true : fieldPermissions?.fields,\n allowedOperations,\n ),\n })\n continue\n }\n\n accessibleFields.push(field)\n }\n\n return accessibleFields\n }\n\n return filterFields(fields, permissions.fields, {\n create: 'create' in permissions && permissions.create === true,\n read: permissions.read === true,\n update: permissions.update === true,\n })\n}\n"],"names":["filterFieldsByAccess","blocks","fields","permissions","shouldExcludeField","filterFields","nestedFields","nestedPermissions","parentAllowedOperations","accessibleFields","field","fieldPermissions","name","isOperationAllowed","operation","allowedOperations","create","read","update","type","accessibleBlocks","blockOrReference","block","find","slug","blockPermissions","push","flattenedFields","length"],"mappings":"AAWA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,MAAMA,uBAAuB,CAAC,EACnCC,MAAM,EACNC,MAAM,EACNC,WAAW,EACXC,kBAAkB,EAMnB;IACC,MAAMC,eAAe,CACnBC,cACAC,mBACAC;QAEA,MAAMC,mBAAqC,EAAE;QAE7C,KAAK,MAAMC,SAASJ,aAAc;YAChC,MAAMK,mBAAmBJ,sBAAsB,OAAO,OAAOA,mBAAmB,CAACG,MAAME,IAAI,CAAC;YAC5F,MAAMC,qBAAqB,CAACC,YAC1BN,uBAAuB,CAACM,UAAU,IACjCH,CAAAA,qBAAqB,QAAQA,kBAAkB,CAACG,UAAU,KAAK,IAAG;YACrE,MAAMC,oBAA4C;gBAChDC,QAAQH,mBAAmB;gBAC3BI,MAAMJ,mBAAmB;gBACzBK,QAAQL,mBAAmB;YAC7B;YAEA,IAAIT,mBAAmBW,oBAAoB;gBACzC;YACF;YAEA,IAAIL,MAAMS,IAAI,KAAK,UAAU;gBAC3B,MAAMC,mBAAgD,EAAE;gBAExD,KAAK,MAAMC,oBAAoBX,MAAMT,MAAM,CAAE;oBAC3C,MAAMqB,QACJ,OAAOD,qBAAqB,WACxBpB,QAAQsB,KAAK,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASH,oBACpCA;oBAEN,IAAI,CAACC,OAAO;wBACV;oBACF;oBAEA,MAAMG,mBACJd,qBAAqB,OACjB,OACAA,kBAAkBV,WAAW,OAC3B,OACAU,kBAAkBV,QAAQ,CAACqB,MAAME,IAAI,CAAC;oBAE9CJ,iBAAiBM,IAAI,CAAC;wBACpB,GAAGJ,KAAK;wBACRK,iBAAiBtB,aACfiB,MAAMK,eAAe,EACrBF,qBAAqB,OAAO,OAAOA,kBAAkBvB,QACrDa;oBAEJ;gBACF;gBAEA,IAAIK,iBAAiBQ,MAAM,KAAK,GAAG;oBACjC;gBACF;gBAEAnB,iBAAiBiB,IAAI,CAAC;oBAAE,GAAGhB,KAAK;oBAAET,QAAQmB;gBAAiB;gBAC3D;YACF;YAEA,IAAIV,MAAMS,IAAI,KAAK,WAAWT,MAAMS,IAAI,KAAK,WAAWT,MAAMS,IAAI,KAAK,OAAO;gBAC5EV,iBAAiBiB,IAAI,CAAC;oBACpB,GAAGhB,KAAK;oBACRiB,iBAAiBtB,aACfK,MAAMiB,eAAe,EACrBhB,qBAAqB,OAAO,OAAOA,kBAAkBT,QACrDa;gBAEJ;gBACA;YACF;YAEAN,iBAAiBiB,IAAI,CAAChB;QACxB;QAEA,OAAOD;IACT;IAEA,OAAOJ,aAAaH,QAAQC,YAAYD,MAAM,EAAE;QAC9Cc,QAAQ,YAAYb,eAAeA,YAAYa,MAAM,KAAK;QAC1DC,MAAMd,YAAYc,IAAI,KAAK;QAC3BC,QAAQf,YAAYe,MAAM,KAAK;IACjC;AACF,EAAC"}
@@ -1,11 +1,13 @@
1
- import { type CollectionSlug, type GlobalSlug, type PayloadRequest } from 'payload';
1
+ import { type CollectionSlug, type GlobalSlug, type PayloadRequest, type SanitizedCollectionPermission, type SanitizedGlobalPermission } from 'payload';
2
2
  import type { JsonSchemaType } from '../../types.js';
3
- export declare const getCollectionInputSchema: ({ collectionSlug, req, }: {
3
+ export declare const getCollectionInputSchema: ({ collectionSlug, permissions, req, }: {
4
4
  collectionSlug: CollectionSlug;
5
+ permissions?: SanitizedCollectionPermission;
5
6
  req: PayloadRequest;
6
7
  }) => JsonSchemaType | null;
7
- export declare const getGlobalInputSchema: ({ globalSlug, req, }: {
8
+ export declare const getGlobalInputSchema: ({ globalSlug, permissions, req, }: {
8
9
  globalSlug: GlobalSlug;
10
+ permissions?: SanitizedGlobalPermission;
9
11
  req: PayloadRequest;
10
12
  }) => JsonSchemaType | null;
11
13
  //# sourceMappingURL=getEntityInputSchema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"getEntityInputSchema.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/getEntityInputSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,cAAc,EAEnB,KAAK,UAAU,EACf,KAAK,cAAc,EAGpB,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AASpD,eAAO,MAAM,wBAAwB,GAAI,0BAGtC;IACD,cAAc,EAAE,cAAc,CAAA;IAC9B,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,cAAc,GAAG,IAYpB,CAAA;AAED,eAAO,MAAM,oBAAoB,GAAI,sBAGlC;IACD,UAAU,EAAE,UAAU,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,cAAc,GAAG,IAYpB,CAAA"}
1
+ {"version":3,"file":"getEntityInputSchema.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/getEntityInputSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,cAAc,EAGnB,KAAK,UAAU,EACf,KAAK,cAAc,EAEnB,KAAK,6BAA6B,EAElC,KAAK,yBAAyB,EAC/B,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAKpD,eAAO,MAAM,wBAAwB,GAAI,uCAItC;IACD,cAAc,EAAE,cAAc,CAAA;IAC9B,WAAW,CAAC,EAAE,6BAA6B,CAAA;IAC3C,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,cAAc,GAAG,IAmBpB,CAAA;AAED,eAAO,MAAM,oBAAoB,GAAI,mCAIlC;IACD,UAAU,EAAE,UAAU,CAAA;IACtB,WAAW,CAAC,EAAE,yBAAyB,CAAA;IACvC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,cAAc,GAAG,IAmBpB,CAAA"}
@@ -1,34 +1,66 @@
1
1
  import { entityToStandaloneJSONSchema } from 'payload';
2
- import { getCollectionVirtualFieldNames, getGlobalVirtualFieldNames } from '../getVirtualFieldNames.js';
3
- import { removeVirtualFieldsFromSchema } from './removeVirtualFieldsFromSchema.js';
2
+ import { filterFieldsByAccess } from './filterFieldsByAccess.js';
4
3
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js';
5
- export const getCollectionInputSchema = ({ collectionSlug, req })=>{
4
+ export const getCollectionInputSchema = ({ collectionSlug, permissions, req })=>{
6
5
  const collection = req.payload.collections[collectionSlug]?.config;
7
6
  if (!collection) {
8
7
  return null;
9
8
  }
9
+ if (!permissions) {
10
+ return buildEntityInputSchema({
11
+ entity: collection,
12
+ req
13
+ });
14
+ }
15
+ const fieldsAllowedByAccess = filterFieldsByAccess({
16
+ blocks: req.payload.config.blocks,
17
+ fields: collection.flattenedFields,
18
+ permissions,
19
+ shouldExcludeField: ({ create, update })=>!create && !update
20
+ });
10
21
  return buildEntityInputSchema({
11
22
  entity: collection,
12
- req,
13
- virtualFieldNames: getCollectionVirtualFieldNames(req.payload.config, collectionSlug)
23
+ fields: fieldsAllowedByAccess,
24
+ req
14
25
  });
15
26
  };
16
- export const getGlobalInputSchema = ({ globalSlug, req })=>{
27
+ export const getGlobalInputSchema = ({ globalSlug, permissions, req })=>{
17
28
  const global = req.payload.config.globals.find((globalConfig)=>globalConfig.slug === globalSlug);
18
29
  if (!global) {
19
30
  return null;
20
31
  }
32
+ if (!permissions) {
33
+ return buildEntityInputSchema({
34
+ entity: global,
35
+ req
36
+ });
37
+ }
38
+ const fieldsAllowedByAccess = filterFieldsByAccess({
39
+ blocks: req.payload.config.blocks,
40
+ fields: global.flattenedFields,
41
+ permissions,
42
+ shouldExcludeField: ({ create, update })=>!create && !update
43
+ });
21
44
  return buildEntityInputSchema({
22
45
  entity: global,
23
- req,
24
- virtualFieldNames: getGlobalVirtualFieldNames(req.payload.config, globalSlug)
46
+ fields: fieldsAllowedByAccess,
47
+ req
25
48
  });
26
49
  };
27
- const buildEntityInputSchema = ({ entity, req, virtualFieldNames })=>sanitizeEntitySchema(removeVirtualFieldsFromSchema(entityToStandaloneJSONSchema({
50
+ const buildEntityInputSchema = ({ entity, fields = entity.flattenedFields, req })=>{
51
+ // The core schema generator reads flattenedFields from the entity and has no fields argument.
52
+ const entityForSchema = {
53
+ ...entity,
54
+ flattenedFields: fields
55
+ };
56
+ const schema = entityToStandaloneJSONSchema({
28
57
  config: req.payload.config,
29
58
  defaultIDType: req.payload.db.defaultIDType,
30
- entity,
31
- i18n: req.i18n
32
- }), virtualFieldNames));
59
+ entity: entityForSchema,
60
+ i18n: req.i18n,
61
+ variant: 'input'
62
+ });
63
+ return sanitizeEntitySchema(schema);
64
+ };
33
65
 
34
66
  //# sourceMappingURL=getEntityInputSchema.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/getEntityInputSchema.ts"],"sourcesContent":["import {\n type CollectionSlug,\n entityToStandaloneJSONSchema,\n type GlobalSlug,\n type PayloadRequest,\n type SanitizedCollectionConfig,\n type SanitizedGlobalConfig,\n} from 'payload'\n\nimport type { JsonSchemaType } from '../../types.js'\n\nimport {\n getCollectionVirtualFieldNames,\n getGlobalVirtualFieldNames,\n} from '../getVirtualFieldNames.js'\nimport { removeVirtualFieldsFromSchema } from './removeVirtualFieldsFromSchema.js'\nimport { sanitizeEntitySchema } from './sanitizeEntitySchema.js'\n\nexport const getCollectionInputSchema = ({\n collectionSlug,\n req,\n}: {\n collectionSlug: CollectionSlug\n req: PayloadRequest\n}): JsonSchemaType | null => {\n const collection = req.payload.collections[collectionSlug]?.config\n\n if (!collection) {\n return null\n }\n\n return buildEntityInputSchema({\n entity: collection,\n req,\n virtualFieldNames: getCollectionVirtualFieldNames(req.payload.config, collectionSlug),\n })\n}\n\nexport const getGlobalInputSchema = ({\n globalSlug,\n req,\n}: {\n globalSlug: GlobalSlug\n req: PayloadRequest\n}): JsonSchemaType | null => {\n const global = req.payload.config.globals.find((globalConfig) => globalConfig.slug === globalSlug)\n\n if (!global) {\n return null\n }\n\n return buildEntityInputSchema({\n entity: global,\n req,\n virtualFieldNames: getGlobalVirtualFieldNames(req.payload.config, globalSlug),\n })\n}\n\nconst buildEntityInputSchema = ({\n entity,\n req,\n virtualFieldNames,\n}: {\n entity: SanitizedCollectionConfig | SanitizedGlobalConfig\n req: PayloadRequest\n virtualFieldNames: string[]\n}): JsonSchemaType =>\n sanitizeEntitySchema(\n removeVirtualFieldsFromSchema(\n entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity,\n i18n: req.i18n,\n }) as unknown as JsonSchemaType,\n virtualFieldNames,\n ),\n )\n"],"names":["entityToStandaloneJSONSchema","getCollectionVirtualFieldNames","getGlobalVirtualFieldNames","removeVirtualFieldsFromSchema","sanitizeEntitySchema","getCollectionInputSchema","collectionSlug","req","collection","payload","collections","config","buildEntityInputSchema","entity","virtualFieldNames","getGlobalInputSchema","globalSlug","global","globals","find","globalConfig","slug","defaultIDType","db","i18n"],"mappings":"AAAA,SAEEA,4BAA4B,QAKvB,UAAS;AAIhB,SACEC,8BAA8B,EAC9BC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,6BAA6B,QAAQ,qCAAoC;AAClF,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,2BAA2B,CAAC,EACvCC,cAAc,EACdC,GAAG,EAIJ;IACC,MAAMC,aAAaD,IAAIE,OAAO,CAACC,WAAW,CAACJ,eAAe,EAAEK;IAE5D,IAAI,CAACH,YAAY;QACf,OAAO;IACT;IAEA,OAAOI,uBAAuB;QAC5BC,QAAQL;QACRD;QACAO,mBAAmBb,+BAA+BM,IAAIE,OAAO,CAACE,MAAM,EAAEL;IACxE;AACF,EAAC;AAED,OAAO,MAAMS,uBAAuB,CAAC,EACnCC,UAAU,EACVT,GAAG,EAIJ;IACC,MAAMU,SAASV,IAAIE,OAAO,CAACE,MAAM,CAACO,OAAO,CAACC,IAAI,CAAC,CAACC,eAAiBA,aAAaC,IAAI,KAAKL;IAEvF,IAAI,CAACC,QAAQ;QACX,OAAO;IACT;IAEA,OAAOL,uBAAuB;QAC5BC,QAAQI;QACRV;QACAO,mBAAmBZ,2BAA2BK,IAAIE,OAAO,CAACE,MAAM,EAAEK;IACpE;AACF,EAAC;AAED,MAAMJ,yBAAyB,CAAC,EAC9BC,MAAM,EACNN,GAAG,EACHO,iBAAiB,EAKlB,GACCV,qBACED,8BACEH,6BAA6B;QAC3BW,QAAQJ,IAAIE,OAAO,CAACE,MAAM;QAC1BW,eAAef,IAAIE,OAAO,CAACc,EAAE,CAACD,aAAa;QAC3CT;QACAW,MAAMjB,IAAIiB,IAAI;IAChB,IACAV"}
1
+ {"version":3,"sources":["../../../src/utils/schemaConversion/getEntityInputSchema.ts"],"sourcesContent":["import {\n type CollectionSlug,\n entityToStandaloneJSONSchema,\n type FlattenedField,\n type GlobalSlug,\n type PayloadRequest,\n type SanitizedCollectionConfig,\n type SanitizedCollectionPermission,\n type SanitizedGlobalConfig,\n type SanitizedGlobalPermission,\n} from 'payload'\n\nimport type { JsonSchemaType } from '../../types.js'\n\nimport { filterFieldsByAccess } from './filterFieldsByAccess.js'\nimport { sanitizeEntitySchema } from './sanitizeEntitySchema.js'\n\nexport const getCollectionInputSchema = ({\n collectionSlug,\n permissions,\n req,\n}: {\n collectionSlug: CollectionSlug\n permissions?: SanitizedCollectionPermission\n req: PayloadRequest\n}): JsonSchemaType | null => {\n const collection = req.payload.collections[collectionSlug]?.config\n\n if (!collection) {\n return null\n }\n\n if (!permissions) {\n return buildEntityInputSchema({ entity: collection, req })\n }\n\n const fieldsAllowedByAccess = filterFieldsByAccess({\n blocks: req.payload.config.blocks,\n fields: collection.flattenedFields,\n permissions,\n shouldExcludeField: ({ create, update }) => !create && !update,\n })\n\n return buildEntityInputSchema({ entity: collection, fields: fieldsAllowedByAccess, req })\n}\n\nexport const getGlobalInputSchema = ({\n globalSlug,\n permissions,\n req,\n}: {\n globalSlug: GlobalSlug\n permissions?: SanitizedGlobalPermission\n req: PayloadRequest\n}): JsonSchemaType | null => {\n const global = req.payload.config.globals.find((globalConfig) => globalConfig.slug === globalSlug)\n\n if (!global) {\n return null\n }\n\n if (!permissions) {\n return buildEntityInputSchema({ entity: global, req })\n }\n\n const fieldsAllowedByAccess = filterFieldsByAccess({\n blocks: req.payload.config.blocks,\n fields: global.flattenedFields,\n permissions,\n shouldExcludeField: ({ create, update }) => !create && !update,\n })\n\n return buildEntityInputSchema({ entity: global, fields: fieldsAllowedByAccess, req })\n}\n\nconst buildEntityInputSchema = ({\n entity,\n fields = entity.flattenedFields,\n req,\n}: {\n entity: SanitizedCollectionConfig | SanitizedGlobalConfig\n fields?: FlattenedField[]\n req: PayloadRequest\n}): JsonSchemaType => {\n // The core schema generator reads flattenedFields from the entity and has no fields argument.\n const entityForSchema = { ...entity, flattenedFields: fields }\n const schema = entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity: entityForSchema,\n i18n: req.i18n,\n variant: 'input',\n }) as unknown as JsonSchemaType\n\n return sanitizeEntitySchema(schema)\n}\n"],"names":["entityToStandaloneJSONSchema","filterFieldsByAccess","sanitizeEntitySchema","getCollectionInputSchema","collectionSlug","permissions","req","collection","payload","collections","config","buildEntityInputSchema","entity","fieldsAllowedByAccess","blocks","fields","flattenedFields","shouldExcludeField","create","update","getGlobalInputSchema","globalSlug","global","globals","find","globalConfig","slug","entityForSchema","schema","defaultIDType","db","i18n","variant"],"mappings":"AAAA,SAEEA,4BAA4B,QAQvB,UAAS;AAIhB,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhE,OAAO,MAAMC,2BAA2B,CAAC,EACvCC,cAAc,EACdC,WAAW,EACXC,GAAG,EAKJ;IACC,MAAMC,aAAaD,IAAIE,OAAO,CAACC,WAAW,CAACL,eAAe,EAAEM;IAE5D,IAAI,CAACH,YAAY;QACf,OAAO;IACT;IAEA,IAAI,CAACF,aAAa;QAChB,OAAOM,uBAAuB;YAAEC,QAAQL;YAAYD;QAAI;IAC1D;IAEA,MAAMO,wBAAwBZ,qBAAqB;QACjDa,QAAQR,IAAIE,OAAO,CAACE,MAAM,CAACI,MAAM;QACjCC,QAAQR,WAAWS,eAAe;QAClCX;QACAY,oBAAoB,CAAC,EAAEC,MAAM,EAAEC,MAAM,EAAE,GAAK,CAACD,UAAU,CAACC;IAC1D;IAEA,OAAOR,uBAAuB;QAAEC,QAAQL;QAAYQ,QAAQF;QAAuBP;IAAI;AACzF,EAAC;AAED,OAAO,MAAMc,uBAAuB,CAAC,EACnCC,UAAU,EACVhB,WAAW,EACXC,GAAG,EAKJ;IACC,MAAMgB,SAAShB,IAAIE,OAAO,CAACE,MAAM,CAACa,OAAO,CAACC,IAAI,CAAC,CAACC,eAAiBA,aAAaC,IAAI,KAAKL;IAEvF,IAAI,CAACC,QAAQ;QACX,OAAO;IACT;IAEA,IAAI,CAACjB,aAAa;QAChB,OAAOM,uBAAuB;YAAEC,QAAQU;YAAQhB;QAAI;IACtD;IAEA,MAAMO,wBAAwBZ,qBAAqB;QACjDa,QAAQR,IAAIE,OAAO,CAACE,MAAM,CAACI,MAAM;QACjCC,QAAQO,OAAON,eAAe;QAC9BX;QACAY,oBAAoB,CAAC,EAAEC,MAAM,EAAEC,MAAM,EAAE,GAAK,CAACD,UAAU,CAACC;IAC1D;IAEA,OAAOR,uBAAuB;QAAEC,QAAQU;QAAQP,QAAQF;QAAuBP;IAAI;AACrF,EAAC;AAED,MAAMK,yBAAyB,CAAC,EAC9BC,MAAM,EACNG,SAASH,OAAOI,eAAe,EAC/BV,GAAG,EAKJ;IACC,8FAA8F;IAC9F,MAAMqB,kBAAkB;QAAE,GAAGf,MAAM;QAAEI,iBAAiBD;IAAO;IAC7D,MAAMa,SAAS5B,6BAA6B;QAC1CU,QAAQJ,IAAIE,OAAO,CAACE,MAAM;QAC1BmB,eAAevB,IAAIE,OAAO,CAACsB,EAAE,CAACD,aAAa;QAC3CjB,QAAQe;QACRI,MAAMzB,IAAIyB,IAAI;QACdC,SAAS;IACX;IAEA,OAAO9B,qBAAqB0B;AAC9B"}
@@ -1,15 +1,10 @@
1
1
  import type { JsonSchemaType } from '../../types.js';
2
2
  /**
3
- * Turns the JSON Schema that Payload generates for a collection or global into the input schema for
4
- * an MCP create/update tool. In short, it:
5
- *
6
- * - drops fields a client can't set (`id`, `createdAt`, the draft `_status`, …),
7
- * - rewrites Payload-specific field shapes (points, relationships) into plain JSON the model can fill,
8
- * - and shrinks the result so it's cheaper for the model to read,
9
- *
10
- * while keeping every node valid JSON Schema draft 2020-12. Each step below is tagged with why it runs -
11
- * **Correctness** (valid input the API accepts), **Size** (equivalence-preserving shrink), or **LLM
12
- * ergonomics** (easier for the model to read/fill) - and carries a before/after example on its definition.
3
+ * Refines Payload's `input`-variant JSON Schema into an MCP create/update tool's input schema. The
4
+ * variant already covers correctness (ID-only relationships, no managed/virtual/join fields); the
5
+ * passes here are MCP-specific - reshaping fields for the model and shrinking the result - and keep
6
+ * every node valid JSON Schema draft 2020-12. Each is tagged **Correctness**, **Size**, or **LLM
7
+ * ergonomics**, with a before/after example on its definition.
13
8
  */
14
9
  export declare const sanitizeEntitySchema: (schema: JsonSchemaType) => JsonSchemaType;
15
10
  //# sourceMappingURL=sanitizeEntitySchema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sanitizeEntitySchema.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAEpD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,cAAc,KAAG,cA6B7D,CAAA"}
1
+ {"version":3,"file":"sanitizeEntitySchema.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAEpD;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,cAAc,KAAG,cA0B7D,CAAA"}
@@ -1,23 +1,16 @@
1
1
  /**
2
- * Turns the JSON Schema that Payload generates for a collection or global into the input schema for
3
- * an MCP create/update tool. In short, it:
4
- *
5
- * - drops fields a client can't set (`id`, `createdAt`, the draft `_status`, …),
6
- * - rewrites Payload-specific field shapes (points, relationships) into plain JSON the model can fill,
7
- * - and shrinks the result so it's cheaper for the model to read,
8
- *
9
- * while keeping every node valid JSON Schema draft 2020-12. Each step below is tagged with why it runs -
10
- * **Correctness** (valid input the API accepts), **Size** (equivalence-preserving shrink), or **LLM
11
- * ergonomics** (easier for the model to read/fill) - and carries a before/after example on its definition.
2
+ * Refines Payload's `input`-variant JSON Schema into an MCP create/update tool's input schema. The
3
+ * variant already covers correctness (ID-only relationships, no managed/virtual/join fields); the
4
+ * passes here are MCP-specific - reshaping fields for the model and shrinking the result - and keep
5
+ * every node valid JSON Schema draft 2020-12. Each is tagged **Correctness**, **Size**, or **LLM
6
+ * ergonomics**, with a before/after example on its definition.
12
7
  */ export const sanitizeEntitySchema = (schema)=>{
13
8
  // Work on a copy — the caller reuses the original schema elsewhere (e.g. when listing tools).
14
9
  let result = structuredClone(schema);
15
- // Correctness — drop the fields a client can't set (id, createdAt, updatedAt, draft _status) + collapse nullable types.
16
- result = removeManagedFields(result);
10
+ // LLM ergonomics — drop the redundant `'null'` from optional arrays/objects (`['array','null']` `'array'`).
11
+ result = collapseOptionalContainerTypes(result);
17
12
  // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.
18
13
  result = pointFieldsToObjects(result);
19
- // Correctness — a relationship value can be an ID or a populated doc; on input only the ID is valid, so keep that.
20
- result = relationshipsToIds(result);
21
14
  // Size — strip inert type-gen leftovers that only bloat the schema (`tsType`, block-collision notes).
22
15
  result = removeTypeGenArtifacts(result);
23
16
  // Size — where a `const` already pins a value, the sibling `type` is redundant; remove it.
@@ -46,26 +39,16 @@
46
39
  }
47
40
  return visit(out);
48
41
  };
49
- // Payload sets these on every document, so an MCP client never provides them when creating/updating.
50
- const PAYLOAD_MANAGED_FIELDS = new Set([
51
- '_status',
52
- 'createdAt',
53
- 'id',
54
- 'updatedAt'
55
- ]);
56
42
  /**
57
- * **Correctness.** Removes the fields a client can't set on create/update - `id`, `createdAt`, `updatedAt`, and the draft
58
- * `_status` - from every field object's `properties` and `required` (recursing into nested objects and
59
- * array items). Along the way it also collapses optional array/object types via {@link collapseNullableType}.
43
+ * **LLM ergonomics.** Collapses optional array/object types (`['array', 'null']` `'array'`) via
44
+ * {@link collapseNullableType}, recursing through `properties` and array items. The `required` list
45
+ * already conveys optionality, so the `'null'` is redundant noise for the model.
60
46
  *
61
47
  * @example
62
- * { properties: { id: { type: 'string' }, tags: { type: ['array', 'null'], items: {} } }, required: ['id', 'tags'] }
63
- * → { properties: { tags: { type: 'array', items: {} } }, required: ['tags'] }
64
- */ const removeManagedFields = (schema)=>{
48
+ * { properties: { tags: { type: ['array', 'null'], items: {} } }, required: [] }
49
+ * → { properties: { tags: { type: 'array', items: {} } }, required: [] }
50
+ */ const collapseOptionalContainerTypes = (schema)=>{
65
51
  if (schema.properties && typeof schema.properties === 'object') {
66
- for (const field of PAYLOAD_MANAGED_FIELDS){
67
- delete schema.properties[field];
68
- }
69
52
  for (const key of Object.keys(schema.properties)){
70
53
  const prop = schema.properties[key];
71
54
  if (!prop || typeof prop !== 'object') {
@@ -74,19 +57,13 @@ const PAYLOAD_MANAGED_FIELDS = new Set([
74
57
  const isRequired = Array.isArray(schema.required) && schema.required.includes(key);
75
58
  collapseNullableType(prop, isRequired);
76
59
  if (prop.properties) {
77
- removeManagedFields(prop);
60
+ collapseOptionalContainerTypes(prop);
78
61
  }
79
62
  if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {
80
- removeManagedFields(prop.items);
63
+ collapseOptionalContainerTypes(prop.items);
81
64
  }
82
65
  }
83
66
  }
84
- if (Array.isArray(schema.required)) {
85
- schema.required = schema.required.filter((name)=>!PAYLOAD_MANAGED_FIELDS.has(name));
86
- if (schema.required.length === 0) {
87
- delete schema.required;
88
- }
89
- }
90
67
  return schema;
91
68
  };
92
69
  /**
@@ -177,63 +154,6 @@ const PAYLOAD_MANAGED_FIELDS = new Set([
177
154
  }
178
155
  return transformed;
179
156
  };
180
- /**
181
- * **Correctness.** Reduces relationship/upload fields to the IDs a client actually sends. Payload types the value as
182
- * "an ID or the full related document" - but the populated-document form only appears in read responses;
183
- * on create/update you always reference a relationship by its ID. So we drop that `$ref` option, leaving
184
- * the bare ID. A single remaining target collapses inline (with a description naming the target
185
- * collection); several targets become an `anyOf` of IDs.
186
- *
187
- * @example
188
- * { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] }
189
- * → { type: 'string', description: 'The ID of the related "posts" document.' }
190
- */ const relationshipsToIds = (schema)=>{
191
- if (!schema || typeof schema !== 'object') {
192
- return schema;
193
- }
194
- const processed = {
195
- ...schema
196
- };
197
- if (Array.isArray(processed.oneOf)) {
198
- const isRelatedDocRef = (option)=>!!option && typeof option === 'object' && '$ref' in option;
199
- if (processed.oneOf.some(isRelatedDocRef)) {
200
- // A relationship value is "an ID, or the populated related document". Keep the ID option(s) and
201
- // drop the `$ref`s to the related collections, since a client only ever sends the ID.
202
- const idOptions = processed.oneOf.filter((option)=>!isRelatedDocRef(option)).map((option)=>typeof option === 'object' ? relationshipsToIds(option) : option);
203
- const targetCollections = processed.oneOf.filter(isRelatedDocRef).map((option)=>option.$ref.replace('#/$defs/', ''));
204
- if (idOptions.length === 1) {
205
- delete processed.oneOf;
206
- Object.assign(processed, idOptions[0]);
207
- if (targetCollections.length > 0 && !processed.description) {
208
- processed.description = `The ID of the related "${targetCollections.join('" or "')}" document.`;
209
- }
210
- } else if (idOptions.length > 1) {
211
- delete processed.oneOf;
212
- processed.anyOf = idOptions;
213
- }
214
- } else {
215
- processed.oneOf = processed.oneOf.map((option)=>typeof option === 'object' ? relationshipsToIds(option) : option);
216
- }
217
- }
218
- if (processed.properties && typeof processed.properties === 'object') {
219
- processed.properties = Object.fromEntries(Object.entries(processed.properties).map(([key, value])=>[
220
- key,
221
- typeof value === 'object' ? relationshipsToIds(value) : value
222
- ]));
223
- }
224
- if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {
225
- processed.items = relationshipsToIds(processed.items);
226
- }
227
- // Lexical node unions and blocks live under `$defs` and have their own relationship fields, so walk
228
- // those too — otherwise their `$ref`s would dangle once we don't bundle the related collections.
229
- if (processed.$defs && typeof processed.$defs === 'object') {
230
- processed.$defs = Object.fromEntries(Object.entries(processed.$defs).map(([key, value])=>[
231
- key,
232
- typeof value === 'object' ? relationshipsToIds(value) : value
233
- ]));
234
- }
235
- return processed;
236
- };
237
157
  /**
238
158
  * **Size.** Strips type-generation leftovers that bloat the schema without helping the model: the `tsType`
239
159
  * hint (a `json-schema-to-typescript` extension; JSON Schema validators just ignore it, they don't reject it)