@payloadcms/plugin-mcp 4.0.0-canary.4 → 4.0.0-canary.6

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.
@@ -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,EAEnB,KAAK,UAAU,EACf,KAAK,cAAc,EAGpB,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAIpD,eAAO,MAAM,wBAAwB,GAAI,0BAGtC;IACD,cAAc,EAAE,cAAc,CAAA;IAC9B,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,cAAc,GAAG,IAQpB,CAAA;AAED,eAAO,MAAM,oBAAoB,GAAI,sBAGlC;IACD,UAAU,EAAE,UAAU,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,cAAc,GAAG,IAQpB,CAAA"}
@@ -1,6 +1,4 @@
1
1
  import { entityToStandaloneJSONSchema } from 'payload';
2
- import { getCollectionVirtualFieldNames, getGlobalVirtualFieldNames } from '../getVirtualFieldNames.js';
3
- import { removeVirtualFieldsFromSchema } from './removeVirtualFieldsFromSchema.js';
4
2
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js';
5
3
  export const getCollectionInputSchema = ({ collectionSlug, req })=>{
6
4
  const collection = req.payload.collections[collectionSlug]?.config;
@@ -9,8 +7,7 @@ export const getCollectionInputSchema = ({ collectionSlug, req })=>{
9
7
  }
10
8
  return buildEntityInputSchema({
11
9
  entity: collection,
12
- req,
13
- virtualFieldNames: getCollectionVirtualFieldNames(req.payload.config, collectionSlug)
10
+ req
14
11
  });
15
12
  };
16
13
  export const getGlobalInputSchema = ({ globalSlug, req })=>{
@@ -20,15 +17,16 @@ export const getGlobalInputSchema = ({ globalSlug, req })=>{
20
17
  }
21
18
  return buildEntityInputSchema({
22
19
  entity: global,
23
- req,
24
- virtualFieldNames: getGlobalVirtualFieldNames(req.payload.config, globalSlug)
20
+ req
25
21
  });
26
22
  };
27
- const buildEntityInputSchema = ({ entity, req, virtualFieldNames })=>sanitizeEntitySchema(removeVirtualFieldsFromSchema(entityToStandaloneJSONSchema({
23
+ const buildEntityInputSchema = ({ entity, req })=>// The `input` variant is already the write shape; sanitizeEntitySchema only adds MCP-specific passes.
24
+ sanitizeEntitySchema(entityToStandaloneJSONSchema({
28
25
  config: req.payload.config,
29
26
  defaultIDType: req.payload.db.defaultIDType,
30
27
  entity,
31
- i18n: req.i18n
32
- }), virtualFieldNames));
28
+ i18n: req.i18n,
29
+ variant: 'input'
30
+ }));
33
31
 
34
32
  //# 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 GlobalSlug,\n type PayloadRequest,\n type SanitizedCollectionConfig,\n type SanitizedGlobalConfig,\n} from 'payload'\n\nimport type { JsonSchemaType } from '../../types.js'\n\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({ entity: collection, req })\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({ entity: global, req })\n}\n\nconst buildEntityInputSchema = ({\n entity,\n req,\n}: {\n entity: SanitizedCollectionConfig | SanitizedGlobalConfig\n req: PayloadRequest\n}): JsonSchemaType =>\n // The `input` variant is already the write shape; sanitizeEntitySchema only adds MCP-specific passes.\n sanitizeEntitySchema(\n entityToStandaloneJSONSchema({\n config: req.payload.config,\n defaultIDType: req.payload.db.defaultIDType,\n entity,\n i18n: req.i18n,\n variant: 'input',\n }) as unknown as JsonSchemaType,\n )\n"],"names":["entityToStandaloneJSONSchema","sanitizeEntitySchema","getCollectionInputSchema","collectionSlug","req","collection","payload","collections","config","buildEntityInputSchema","entity","getGlobalInputSchema","globalSlug","global","globals","find","globalConfig","slug","defaultIDType","db","i18n","variant"],"mappings":"AAAA,SAEEA,4BAA4B,QAKvB,UAAS;AAIhB,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;QAAEC,QAAQL;QAAYD;IAAI;AAC1D,EAAC;AAED,OAAO,MAAMO,uBAAuB,CAAC,EACnCC,UAAU,EACVR,GAAG,EAIJ;IACC,MAAMS,SAAST,IAAIE,OAAO,CAACE,MAAM,CAACM,OAAO,CAACC,IAAI,CAAC,CAACC,eAAiBA,aAAaC,IAAI,KAAKL;IAEvF,IAAI,CAACC,QAAQ;QACX,OAAO;IACT;IAEA,OAAOJ,uBAAuB;QAAEC,QAAQG;QAAQT;IAAI;AACtD,EAAC;AAED,MAAMK,yBAAyB,CAAC,EAC9BC,MAAM,EACNN,GAAG,EAIJ,GACC,sGAAsG;IACtGH,qBACED,6BAA6B;QAC3BQ,QAAQJ,IAAIE,OAAO,CAACE,MAAM;QAC1BU,eAAed,IAAIE,OAAO,CAACa,EAAE,CAACD,aAAa;QAC3CR;QACAU,MAAMhB,IAAIgB,IAAI;QACdC,SAAS;IACX"}
@@ -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)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.ts"],"sourcesContent":["import type { JsonSchemaType } from '../../types.js'\n\n/**\n * Turns the JSON Schema that Payload generates for a collection or global into the input schema for\n * an MCP create/update tool. In short, it:\n *\n * - drops fields a client can't set (`id`, `createdAt`, the draft `_status`, …),\n * - rewrites Payload-specific field shapes (points, relationships) into plain JSON the model can fill,\n * - and shrinks the result so it's cheaper for the model to read,\n *\n * while keeping every node valid JSON Schema draft 2020-12. Each step below is tagged with why it runs -\n * **Correctness** (valid input the API accepts), **Size** (equivalence-preserving shrink), or **LLM\n * ergonomics** (easier for the model to read/fill) - and carries a before/after example on its definition.\n */\nexport const sanitizeEntitySchema = (schema: JsonSchemaType): JsonSchemaType => {\n // Work on a copy — the caller reuses the original schema elsewhere (e.g. when listing tools).\n let result = structuredClone(schema)\n\n // Correctness — drop the fields a client can't set (id, createdAt, updatedAt, draft _status) + collapse nullable types.\n result = removeManagedFields(result)\n\n // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.\n result = pointFieldsToObjects(result)\n\n // Correctness — a relationship value can be an ID or a populated doc; on input only the ID is valid, so keep that.\n result = relationshipsToIds(result)\n\n // Size — strip inert type-gen leftovers that only bloat the schema (`tsType`, block-collision notes).\n result = removeTypeGenArtifacts(result)\n\n // Size — where a `const` already pins a value, the sibling `type` is redundant; remove it.\n result = dropRedundantConstType(result)\n\n // Size — fold per-collection relationship/upload variants (identical but for `relationTo`) into one `enum`.\n result = mergeConstDiscriminatedUnions(result)\n\n // Size — pull any subschema that appears more than once into a single shared `$defs` entry.\n result = deduplicateIntoDefinitions(result)\n\n // LLM ergonomics — give `$defs` short, readable names (`Code`, `paragraph`, `node`) so the `$ref`s read nicely.\n result = shortenDefinitionNames(result)\n\n return result\n}\n\n/**\n * Rebuilds a schema bottom-up, calling `visit` on each node after its children. Shared by the\n * transforms that need to touch every node in the tree.\n */\nconst mapNodes = (node: unknown, visit: (node: JsonSchemaType) => JsonSchemaType): unknown => {\n if (Array.isArray(node)) {\n return node.map((child) => mapNodes(child, visit))\n }\n if (!node || typeof node !== 'object') {\n return node\n }\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(node)) {\n out[key] = mapNodes(value, visit)\n }\n return visit(out as JsonSchemaType)\n}\n\n// Payload sets these on every document, so an MCP client never provides them when creating/updating.\nconst PAYLOAD_MANAGED_FIELDS = new Set(['_status', 'createdAt', 'id', 'updatedAt'])\n\n/**\n * **Correctness.** Removes the fields a client can't set on create/update - `id`, `createdAt`, `updatedAt`, and the draft\n * `_status` - from every field object's `properties` and `required` (recursing into nested objects and\n * array items). Along the way it also collapses optional array/object types via {@link collapseNullableType}.\n *\n * @example\n * { properties: { id: { type: 'string' }, tags: { type: ['array', 'null'], items: {} } }, required: ['id', 'tags'] }\n * → { properties: { tags: { type: 'array', items: {} } }, required: ['tags'] }\n */\nconst removeManagedFields = (schema: JsonSchemaType): JsonSchemaType => {\n if (schema.properties && typeof schema.properties === 'object') {\n for (const field of PAYLOAD_MANAGED_FIELDS) {\n delete schema.properties[field]\n }\n for (const key of Object.keys(schema.properties)) {\n const prop = schema.properties[key] as JsonSchemaType\n if (!prop || typeof prop !== 'object') {\n continue\n }\n const isRequired = Array.isArray(schema.required) && schema.required.includes(key)\n collapseNullableType(prop, isRequired)\n if (prop.properties) {\n removeManagedFields(prop)\n }\n if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {\n removeManagedFields(prop.items)\n }\n }\n }\n\n if (Array.isArray(schema.required)) {\n schema.required = schema.required.filter((name) => !PAYLOAD_MANAGED_FIELDS.has(name))\n if (schema.required.length === 0) {\n delete schema.required\n }\n }\n\n return schema\n}\n\n/**\n * Drops the `'null'` from an optional array/object type (`['array', 'null']` → `'array'`, likewise\n * `'object'`). Payload marks a field optional by unioning its type with `'null'`, but a create/update\n * tool already conveys \"optional\" through the `required` list - the client just omits the field - so the\n * `'null'` is redundant here. Dropping it shows the model a plain `type: 'array'` instead of implying it\n * should send a literal `null`.\n *\n * We never touch the `required` list, so this can't change whether a field is required. And we skip fields\n * that ARE required (`isRequired`): there a `'null'` is a value the field genuinely accepts, not optionality\n * encoding. Nullable scalars (`['string', 'null']`) are also left alone - they read fine as `string | null`.\n *\n * @example\n * optional { type: ['array', 'null'] } → { type: 'array' } (still optional, just no longer null-valued)\n * required { type: ['array', 'null'] } → unchanged\n * { type: ['string', 'null'] } → unchanged\n */\nconst collapseNullableType = (schema: JsonSchemaType, isRequired: boolean): void => {\n if (isRequired || !Array.isArray(schema.type)) {\n return\n }\n const nonNullTypes = schema.type.filter((t) => t !== 'null')\n if (nonNullTypes.length === 1 && (nonNullTypes[0] === 'array' || nonNullTypes[0] === 'object')) {\n schema.type = nonNullTypes[0]\n }\n}\n\n/**\n * **LLM ergonomics.** Rewrites a point field (stored as a two-number tuple) into a `{ longitude, latitude }` object, which\n * is far easier for the model to fill in than a positional array. This is input-only and lossless: the\n * create/update handler converts the object back to the `[longitude, latitude]` tuple Payload stores,\n * via `transformPointDataToPayload`.\n *\n * @example\n * { type: 'array', items: [{ type: 'number' }, { type: 'number' }] }\n * → { type: 'object', properties: { longitude: { type: 'number' }, latitude: { type: 'number' } }, required: ['longitude', 'latitude'] }\n */\nconst pointFieldsToObjects = (schema: JsonSchemaType): JsonSchemaType => {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const transformed = { ...schema }\n\n if (transformed.properties && typeof transformed.properties === 'object') {\n transformed.properties = Object.fromEntries(\n Object.entries(transformed.properties).map(([key, value]) => {\n if (!value || typeof value !== 'object') {\n return [key, value]\n }\n const isArrayType =\n value.type === 'array' || (Array.isArray(value.type) && value.type.includes('array'))\n const isPointField =\n isArrayType &&\n Array.isArray(value.items) &&\n value.items.length === 2 &&\n value.items.every((item) => item && typeof item === 'object' && item.type === 'number')\n\n if (isPointField) {\n const isNullable = Array.isArray(value.type) && value.type.includes('null')\n return [\n key,\n {\n type: isNullable ? ['object', 'null'] : 'object',\n description: value.description || 'Geographic coordinates (longitude, latitude)',\n properties: {\n latitude: { type: 'number', description: 'Latitude coordinate' },\n longitude: { type: 'number', description: 'Longitude coordinate' },\n },\n required: ['longitude', 'latitude'],\n },\n ]\n }\n\n return [key, pointFieldsToObjects(value)]\n }),\n )\n }\n\n if (\n transformed.items &&\n typeof transformed.items === 'object' &&\n !Array.isArray(transformed.items)\n ) {\n transformed.items = pointFieldsToObjects(transformed.items)\n }\n\n return transformed\n}\n\n/**\n * **Correctness.** Reduces relationship/upload fields to the IDs a client actually sends. Payload types the value as\n * \"an ID or the full related document\" - but the populated-document form only appears in read responses;\n * on create/update you always reference a relationship by its ID. So we drop that `$ref` option, leaving\n * the bare ID. A single remaining target collapses inline (with a description naming the target\n * collection); several targets become an `anyOf` of IDs.\n *\n * @example\n * { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] }\n * → { type: 'string', description: 'The ID of the related \"posts\" document.' }\n */\nconst relationshipsToIds = (schema: JsonSchemaType): JsonSchemaType => {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const processed = { ...schema }\n\n if (Array.isArray(processed.oneOf)) {\n const isRelatedDocRef = (option: unknown): option is { $ref: string } =>\n !!option && typeof option === 'object' && '$ref' in option\n\n if (processed.oneOf.some(isRelatedDocRef)) {\n // A relationship value is \"an ID, or the populated related document\". Keep the ID option(s) and\n // drop the `$ref`s to the related collections, since a client only ever sends the ID.\n const idOptions = processed.oneOf\n .filter((option) => !isRelatedDocRef(option))\n .map((option) => (typeof option === 'object' ? relationshipsToIds(option) : option))\n const targetCollections = processed.oneOf\n .filter(isRelatedDocRef)\n .map((option) => option.$ref.replace('#/$defs/', ''))\n\n if (idOptions.length === 1) {\n delete processed.oneOf\n Object.assign(processed, idOptions[0])\n if (targetCollections.length > 0 && !processed.description) {\n processed.description = `The ID of the related \"${targetCollections.join('\" or \"')}\" document.`\n }\n } else if (idOptions.length > 1) {\n delete processed.oneOf\n processed.anyOf = idOptions\n }\n } else {\n processed.oneOf = processed.oneOf.map((option) =>\n typeof option === 'object' ? relationshipsToIds(option) : option,\n )\n }\n }\n\n if (processed.properties && typeof processed.properties === 'object') {\n processed.properties = Object.fromEntries(\n Object.entries(processed.properties).map(([key, value]) => [\n key,\n typeof value === 'object' ? relationshipsToIds(value) : value,\n ]),\n )\n }\n\n if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {\n processed.items = relationshipsToIds(processed.items)\n }\n\n // Lexical node unions and blocks live under `$defs` and have their own relationship fields, so walk\n // those too — otherwise their `$ref`s would dangle once we don't bundle the related collections.\n if (processed.$defs && typeof processed.$defs === 'object') {\n processed.$defs = Object.fromEntries(\n Object.entries(processed.$defs).map(([key, value]) => [\n key,\n typeof value === 'object' ? relationshipsToIds(value) : value,\n ]),\n )\n }\n\n return processed\n}\n\n/**\n * **Size.** Strips type-generation leftovers that bloat the schema without helping the model: the `tsType`\n * hint (a `json-schema-to-typescript` extension; JSON Schema validators just ignore it, they don't reject it)\n * and the block-interface-collision note Payload adds to some block descriptions (the\n * `block-interface-name-collisions` docs link set in `registerBlockInterface`, see configToJSONSchema.ts).\n * Both are inert here - removing them only shrinks the schema (and spares the model irrelevant noise).\n *\n * @example\n * { type: 'object', tsType: 'SerializedBlockNode', description: 'see …#block-interface-name-collisions' }\n * → { type: 'object' }\n */\nconst removeTypeGenArtifacts = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n delete (node as { tsType?: unknown }).tsType\n const { description } = node as { description?: string }\n if (\n typeof description === 'string' &&\n description.includes('block-interface-name-collisions')\n ) {\n delete (node as { description?: unknown }).description\n }\n return node\n }) as JsonSchemaType\n\n/**\n * **Size.** Removes `type` whenever a `const` sits next to it — the constant already fixes the value.\n *\n * @example\n * { type: 'string', const: 'paragraph' } → { const: 'paragraph' }\n */\nconst dropRedundantConstType = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n if ('const' in node && 'type' in node) {\n delete (node as { type?: unknown }).type\n }\n return node\n }) as JsonSchemaType\n\n/**\n * **Size.** Merges the members of a `oneOf`/`anyOf` that are identical except for one `const`-valued property\n * into a single member with that property as an `enum`. Since the members differ only by that one\n * constant, the `enum` form accepts exactly the same values - it's just smaller. This folds the\n * per-collection relationship and upload variants, which differ only in their `relationTo` constant.\n *\n * @example\n * { oneOf: [\n * { properties: { relationTo: { const: 'posts' }, value: { type: 'string' } } },\n * { properties: { relationTo: { const: 'pages' }, value: { type: 'string' } } },\n * ] }\n * → { properties: { relationTo: { enum: ['posts', 'pages'] }, value: { type: 'string' } } }\n */\nconst mergeConstDiscriminatedUnions = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n for (const keyword of ['oneOf', 'anyOf'] as const) {\n const members = node[keyword]\n if (Array.isArray(members) && members.length > 1) {\n const merged = mergeMembersByConst(members)\n if (merged) {\n delete node[keyword]\n Object.assign(node, merged)\n }\n }\n }\n return node\n }) as JsonSchemaType\n\n/** Returns the merged member for {@link mergeConstDiscriminatedUnions}, or `null` if they can't merge. */\nconst mergeMembersByConst = (members: Array<boolean | JsonSchemaType>): JsonSchemaType | null => {\n const objects = members.filter(\n (member): member is JsonSchemaType =>\n typeof member === 'object' && member !== null && typeof member.properties === 'object',\n )\n if (objects.length < 2 || objects.length !== members.length) {\n return null\n }\n\n for (const discriminator of Object.keys(objects[0]!.properties!)) {\n // Each member must pin this property to a `const`...\n const constValues: unknown[] = []\n const everyMemberPinsConst = objects.every((member) => {\n const prop = member.properties![discriminator]\n if (prop && typeof prop === 'object' && 'const' in prop) {\n constValues.push(prop.const)\n return true\n }\n return false\n })\n if (!everyMemberPinsConst) {\n continue\n }\n\n // ...and be otherwise identical (compare each member with the discriminator removed).\n const fingerprintWithoutDiscriminator = (member: JsonSchemaType): string => {\n const { [discriminator]: _discriminator, ...otherProperties } = member.properties!\n return JSON.stringify({ ...member, properties: otherProperties })\n }\n if (new Set(objects.map(fingerprintWithoutDiscriminator)).size !== 1) {\n continue\n }\n\n const uniqueConstValues = [...new Set(constValues)]\n if (uniqueConstValues.length < 2) {\n continue\n }\n\n // Replace the per-member `const` with a single `enum` of every value.\n const merged = structuredClone(objects[0]!)\n const discriminatorProp = merged.properties![discriminator]\n if (discriminatorProp && typeof discriminatorProp === 'object') {\n delete discriminatorProp.const\n discriminatorProp.enum = uniqueConstValues as NonNullable<typeof discriminatorProp.enum>\n }\n return merged\n }\n return null\n}\n\n// A `$ref` costs ~30 characters once names are shortened, so sharing a subschema only pays off when\n// it's larger than that and appears more than once.\nconst MIN_SHARED_SIZE = 64\n\n/** A subschema worth sharing: a standalone object/union/described schema, not a `$ref` or a primitive. */\nconst isShareable = (node: unknown): node is Record<string, unknown> => {\n if (!node || typeof node !== 'object' || Array.isArray(node) || '$ref' in node) {\n return false\n }\n const schema = node as JsonSchemaType\n return (\n Array.isArray(schema.oneOf) ||\n Array.isArray(schema.anyOf) ||\n Boolean(schema.properties) ||\n Boolean(schema.items) ||\n typeof schema.description === 'string'\n )\n}\n\n/**\n * **Size.** Replaces any subschema that appears more than once with a single shared `$defs` entry referenced by\n * `$ref`. Lossless — only the serialized size shrinks. A collection with several rich-text fields, for\n * example, inlines the same large lexical node schema once per field; this collapses them into one.\n *\n * @example\n * { properties: { billing: address, shipping: address } }\n * → { properties: { billing: { $ref: '#/$defs/shared_0' }, shipping: { $ref: '#/$defs/shared_0' } }, $defs: { shared_0: address } }\n */\nconst deduplicateIntoDefinitions = (schema: JsonSchemaType): JsonSchemaType => {\n // Count how often each shareable subschema appears, keyed by its serialized form.\n const counts = new Map<string, number>()\n const count = (node: unknown): void => {\n if (isShareable(node)) {\n const key = JSON.stringify(node)\n if (key.length >= MIN_SHARED_SIZE) {\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n }\n if (Array.isArray(node)) {\n node.forEach(count)\n } else if (node && typeof node === 'object') {\n Object.values(node).forEach(count)\n }\n }\n count(schema)\n\n if (![...counts.values()].some((n) => n >= 2)) {\n return schema\n }\n\n // Replace each subschema seen 2+ times with a `$ref`. The first time we meet one it becomes a shared\n // entry; we never descend into a stored entry, so shared entries never reference one another.\n const sharedEntries: Record<string, JsonSchemaType> = {}\n const nameByKey = new Map<string, string>()\n const share = (node: unknown): unknown => {\n if (isShareable(node)) {\n const key = JSON.stringify(node)\n if ((counts.get(key) ?? 0) >= 2) {\n let name = nameByKey.get(key)\n if (!name) {\n name = `shared_${nameByKey.size}`\n nameByKey.set(key, name)\n sharedEntries[name] = node as JsonSchemaType\n }\n return { $ref: `#/$defs/${name}` }\n }\n }\n if (Array.isArray(node)) {\n return node.map(share)\n }\n if (node && typeof node === 'object') {\n return Object.fromEntries(\n Object.entries(node).map(([childKey, value]) => [childKey, share(value)]),\n )\n }\n return node\n }\n\n const result = share(schema) as JsonSchemaType\n result.$defs = { ...result.$defs, ...sharedEntries }\n return result\n}\n\n/**\n * **LLM ergonomics.** Renames `$defs` entries to short, readable names so the `$ref`s stay legible to the model: a block's\n * `blockType` (`Code`), a node's `type` (`paragraph`), `node` for a rich-text node union, otherwise the\n * generated name with its disambiguating hash dropped. A numeric suffix keeps collisions unique.\n *\n * @example\n * { properties: { body: { $ref: '#/$defs/LexicalNodes_9FBEC708' } }, $defs: { LexicalNodes_9FBEC708: {} } }\n * → { properties: { body: { $ref: '#/$defs/node' } }, $defs: { node: {} } }\n */\nconst shortenDefinitionNames = (schema: JsonSchemaType): JsonSchemaType => {\n const definitions = schema.$defs\n if (!definitions || Object.keys(definitions).length === 0) {\n return schema\n }\n\n const shortNameFor = (name: string, definition: boolean | JsonSchemaType): string => {\n const properties = (typeof definition === 'object' && definition.properties) || {}\n const constString = (key: string): string | undefined => {\n const prop = properties[key]\n return prop && typeof prop === 'object' && typeof prop.const === 'string'\n ? prop.const\n : undefined\n }\n const members =\n typeof definition === 'object' ? (definition.anyOf ?? definition.oneOf) : undefined\n const isNodeUnion =\n Array.isArray(members) &&\n members.some((m) => typeof m === 'object' && Boolean(m.$ref || m.properties?.type))\n return (\n constString('blockType') ??\n constString('type') ??\n (isNodeUnion ? 'node' : undefined) ??\n name.replace(/_[0-9A-F]{6,}$/i, '')\n )\n }\n\n const prefix = '#/$defs/'\n const usedNames = new Map<string, number>()\n const rename = new Map<string, string>()\n for (const [name, definition] of Object.entries(definitions)) {\n const shortName = shortNameFor(name, definition)\n const used = usedNames.get(shortName) ?? 0\n usedNames.set(shortName, used + 1)\n rename.set(name, used === 0 ? shortName : `${shortName}${used + 1}`)\n }\n\n const result = mapNodes(schema, (node) => {\n if (typeof node.$ref === 'string' && node.$ref.startsWith(prefix)) {\n const name = node.$ref.slice(prefix.length)\n node.$ref = `${prefix}${rename.get(name) ?? name}`\n }\n return node\n }) as JsonSchemaType\n result.$defs = Object.fromEntries(\n Object.entries(result.$defs!).map(([name, body]) => [rename.get(name) ?? name, body]),\n )\n return result\n}\n"],"names":["sanitizeEntitySchema","schema","result","structuredClone","removeManagedFields","pointFieldsToObjects","relationshipsToIds","removeTypeGenArtifacts","dropRedundantConstType","mergeConstDiscriminatedUnions","deduplicateIntoDefinitions","shortenDefinitionNames","mapNodes","node","visit","Array","isArray","map","child","out","key","value","Object","entries","PAYLOAD_MANAGED_FIELDS","Set","properties","field","keys","prop","isRequired","required","includes","collapseNullableType","items","filter","name","has","length","type","nonNullTypes","t","transformed","fromEntries","isArrayType","isPointField","every","item","isNullable","description","latitude","longitude","processed","oneOf","isRelatedDocRef","option","some","idOptions","targetCollections","$ref","replace","assign","join","anyOf","$defs","tsType","keyword","members","merged","mergeMembersByConst","objects","member","discriminator","constValues","everyMemberPinsConst","push","const","fingerprintWithoutDiscriminator","_discriminator","otherProperties","JSON","stringify","size","uniqueConstValues","discriminatorProp","enum","MIN_SHARED_SIZE","isShareable","Boolean","counts","Map","count","set","get","forEach","values","n","sharedEntries","nameByKey","share","childKey","definitions","shortNameFor","definition","constString","undefined","isNodeUnion","m","prefix","usedNames","rename","shortName","used","startsWith","slice","body"],"mappings":"AAEA;;;;;;;;;;;CAWC,GACD,OAAO,MAAMA,uBAAuB,CAACC;IACnC,8FAA8F;IAC9F,IAAIC,SAASC,gBAAgBF;IAE7B,wHAAwH;IACxHC,SAASE,oBAAoBF;IAE7B,iHAAiH;IACjHA,SAASG,qBAAqBH;IAE9B,mHAAmH;IACnHA,SAASI,mBAAmBJ;IAE5B,sGAAsG;IACtGA,SAASK,uBAAuBL;IAEhC,2FAA2F;IAC3FA,SAASM,uBAA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T;IACAX,OAAO8D,KAAK,GAAG1C,OAAOqB,WAAW,CAC/BrB,OAAOC,OAAO,CAACrB,OAAO8D,KAAK,EAAG/C,GAAG,CAAC,CAAC,CAACmB,MAAM+E,KAAK,GAAK;YAACL,OAAOjB,GAAG,CAACzD,SAASA;YAAM+E;SAAK;IAEtF,OAAOjH;AACT"}
1
+ {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.ts"],"sourcesContent":["import type { JsonSchemaType } from '../../types.js'\n\n/**\n * Refines Payload's `input`-variant JSON Schema into an MCP create/update tool's input schema. The\n * variant already covers correctness (ID-only relationships, no managed/virtual/join fields); the\n * passes here are MCP-specific - reshaping fields for the model and shrinking the result - and keep\n * every node valid JSON Schema draft 2020-12. Each is tagged **Correctness**, **Size**, or **LLM\n * ergonomics**, with a before/after example on its definition.\n */\nexport const sanitizeEntitySchema = (schema: JsonSchemaType): JsonSchemaType => {\n // Work on a copy — the caller reuses the original schema elsewhere (e.g. when listing tools).\n let result = structuredClone(schema)\n\n // LLM ergonomics — drop the redundant `'null'` from optional arrays/objects (`['array','null']` → `'array'`).\n result = collapseOptionalContainerTypes(result)\n\n // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.\n result = pointFieldsToObjects(result)\n\n // Size — strip inert type-gen leftovers that only bloat the schema (`tsType`, block-collision notes).\n result = removeTypeGenArtifacts(result)\n\n // Size — where a `const` already pins a value, the sibling `type` is redundant; remove it.\n result = dropRedundantConstType(result)\n\n // Size — fold per-collection relationship/upload variants (identical but for `relationTo`) into one `enum`.\n result = mergeConstDiscriminatedUnions(result)\n\n // Size — pull any subschema that appears more than once into a single shared `$defs` entry.\n result = deduplicateIntoDefinitions(result)\n\n // LLM ergonomics — give `$defs` short, readable names (`Code`, `paragraph`, `node`) so the `$ref`s read nicely.\n result = shortenDefinitionNames(result)\n\n return result\n}\n\n/**\n * Rebuilds a schema bottom-up, calling `visit` on each node after its children. Shared by the\n * transforms that need to touch every node in the tree.\n */\nconst mapNodes = (node: unknown, visit: (node: JsonSchemaType) => JsonSchemaType): unknown => {\n if (Array.isArray(node)) {\n return node.map((child) => mapNodes(child, visit))\n }\n if (!node || typeof node !== 'object') {\n return node\n }\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(node)) {\n out[key] = mapNodes(value, visit)\n }\n return visit(out)\n}\n\n/**\n * **LLM ergonomics.** Collapses optional array/object types (`['array', 'null']` → `'array'`) via\n * {@link collapseNullableType}, recursing through `properties` and array items. The `required` list\n * already conveys optionality, so the `'null'` is redundant noise for the model.\n *\n * @example\n * { properties: { tags: { type: ['array', 'null'], items: {} } }, required: [] }\n * → { properties: { tags: { type: 'array', items: {} } }, required: [] }\n */\nconst collapseOptionalContainerTypes = (schema: JsonSchemaType): JsonSchemaType => {\n if (schema.properties && typeof schema.properties === 'object') {\n for (const key of Object.keys(schema.properties)) {\n const prop = schema.properties[key] as JsonSchemaType\n if (!prop || typeof prop !== 'object') {\n continue\n }\n const isRequired = Array.isArray(schema.required) && schema.required.includes(key)\n collapseNullableType(prop, isRequired)\n if (prop.properties) {\n collapseOptionalContainerTypes(prop)\n }\n if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {\n collapseOptionalContainerTypes(prop.items)\n }\n }\n }\n\n return schema\n}\n\n/**\n * Drops the `'null'` from an optional array/object type (`['array', 'null']` → `'array'`, likewise\n * `'object'`). Payload marks a field optional by unioning its type with `'null'`, but a create/update\n * tool already conveys \"optional\" through the `required` list - the client just omits the field - so the\n * `'null'` is redundant here. Dropping it shows the model a plain `type: 'array'` instead of implying it\n * should send a literal `null`.\n *\n * We never touch the `required` list, so this can't change whether a field is required. And we skip fields\n * that ARE required (`isRequired`): there a `'null'` is a value the field genuinely accepts, not optionality\n * encoding. Nullable scalars (`['string', 'null']`) are also left alone - they read fine as `string | null`.\n *\n * @example\n * optional { type: ['array', 'null'] } → { type: 'array' } (still optional, just no longer null-valued)\n * required { type: ['array', 'null'] } → unchanged\n * { type: ['string', 'null'] } → unchanged\n */\nconst collapseNullableType = (schema: JsonSchemaType, isRequired: boolean): void => {\n if (isRequired || !Array.isArray(schema.type)) {\n return\n }\n const nonNullTypes = schema.type.filter((t) => t !== 'null')\n if (nonNullTypes.length === 1 && (nonNullTypes[0] === 'array' || nonNullTypes[0] === 'object')) {\n schema.type = nonNullTypes[0]\n }\n}\n\n/**\n * **LLM ergonomics.** Rewrites a point field (stored as a two-number tuple) into a `{ longitude, latitude }` object, which\n * is far easier for the model to fill in than a positional array. This is input-only and lossless: the\n * create/update handler converts the object back to the `[longitude, latitude]` tuple Payload stores,\n * via `transformPointDataToPayload`.\n *\n * @example\n * { type: 'array', items: [{ type: 'number' }, { type: 'number' }] }\n * → { type: 'object', properties: { longitude: { type: 'number' }, latitude: { type: 'number' } }, required: ['longitude', 'latitude'] }\n */\nconst pointFieldsToObjects = (schema: JsonSchemaType): JsonSchemaType => {\n if (!schema || typeof schema !== 'object') {\n return schema\n }\n\n const transformed = { ...schema }\n\n if (transformed.properties && typeof transformed.properties === 'object') {\n transformed.properties = Object.fromEntries(\n Object.entries(transformed.properties).map(([key, value]) => {\n if (!value || typeof value !== 'object') {\n return [key, value]\n }\n const isArrayType =\n value.type === 'array' || (Array.isArray(value.type) && value.type.includes('array'))\n const isPointField =\n isArrayType &&\n Array.isArray(value.items) &&\n value.items.length === 2 &&\n value.items.every((item) => item && typeof item === 'object' && item.type === 'number')\n\n if (isPointField) {\n const isNullable = Array.isArray(value.type) && value.type.includes('null')\n return [\n key,\n {\n type: isNullable ? ['object', 'null'] : 'object',\n description: value.description || 'Geographic coordinates (longitude, latitude)',\n properties: {\n latitude: { type: 'number', description: 'Latitude coordinate' },\n longitude: { type: 'number', description: 'Longitude coordinate' },\n },\n required: ['longitude', 'latitude'],\n },\n ]\n }\n\n return [key, pointFieldsToObjects(value)]\n }),\n )\n }\n\n if (\n transformed.items &&\n typeof transformed.items === 'object' &&\n !Array.isArray(transformed.items)\n ) {\n transformed.items = pointFieldsToObjects(transformed.items)\n }\n\n return transformed\n}\n\n/**\n * **Size.** Strips type-generation leftovers that bloat the schema without helping the model: the `tsType`\n * hint (a `json-schema-to-typescript` extension; JSON Schema validators just ignore it, they don't reject it)\n * and the block-interface-collision note Payload adds to some block descriptions (the\n * `block-interface-name-collisions` docs link set in `registerBlockInterface`, see configToJSONSchema.ts).\n * Both are inert here - removing them only shrinks the schema (and spares the model irrelevant noise).\n *\n * @example\n * { type: 'object', tsType: 'SerializedBlockNode', description: 'see …#block-interface-name-collisions' }\n * → { type: 'object' }\n */\nconst removeTypeGenArtifacts = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n delete (node as { tsType?: unknown }).tsType\n const { description } = node as { description?: string }\n if (\n typeof description === 'string' &&\n description.includes('block-interface-name-collisions')\n ) {\n delete (node as { description?: unknown }).description\n }\n return node\n }) as JsonSchemaType\n\n/**\n * **Size.** Removes `type` whenever a `const` sits next to it — the constant already fixes the value.\n *\n * @example\n * { type: 'string', const: 'paragraph' } → { const: 'paragraph' }\n */\nconst dropRedundantConstType = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n if ('const' in node && 'type' in node) {\n delete (node as { type?: unknown }).type\n }\n return node\n }) as JsonSchemaType\n\n/**\n * **Size.** Merges the members of a `oneOf`/`anyOf` that are identical except for one `const`-valued property\n * into a single member with that property as an `enum`. Since the members differ only by that one\n * constant, the `enum` form accepts exactly the same values - it's just smaller. This folds the\n * per-collection relationship and upload variants, which differ only in their `relationTo` constant.\n *\n * @example\n * { oneOf: [\n * { properties: { relationTo: { const: 'posts' }, value: { type: 'string' } } },\n * { properties: { relationTo: { const: 'pages' }, value: { type: 'string' } } },\n * ] }\n * → { properties: { relationTo: { enum: ['posts', 'pages'] }, value: { type: 'string' } } }\n */\nconst mergeConstDiscriminatedUnions = (schema: JsonSchemaType): JsonSchemaType =>\n mapNodes(schema, (node) => {\n for (const keyword of ['oneOf', 'anyOf'] as const) {\n const members = node[keyword]\n if (Array.isArray(members) && members.length > 1) {\n const merged = mergeMembersByConst(members)\n if (merged) {\n delete node[keyword]\n Object.assign(node, merged)\n }\n }\n }\n return node\n }) as JsonSchemaType\n\n/** Returns the merged member for {@link mergeConstDiscriminatedUnions}, or `null` if they can't merge. */\nconst mergeMembersByConst = (members: Array<boolean | JsonSchemaType>): JsonSchemaType | null => {\n const objects = members.filter(\n (member): member is JsonSchemaType =>\n typeof member === 'object' && member !== null && typeof member.properties === 'object',\n )\n if (objects.length < 2 || objects.length !== members.length) {\n return null\n }\n\n for (const discriminator of Object.keys(objects[0]!.properties!)) {\n // Each member must pin this property to a `const`...\n const constValues: unknown[] = []\n const everyMemberPinsConst = objects.every((member) => {\n const prop = member.properties![discriminator]\n if (prop && typeof prop === 'object' && 'const' in prop) {\n constValues.push(prop.const)\n return true\n }\n return false\n })\n if (!everyMemberPinsConst) {\n continue\n }\n\n // ...and be otherwise identical (compare each member with the discriminator removed).\n const fingerprintWithoutDiscriminator = (member: JsonSchemaType): string => {\n const { [discriminator]: _discriminator, ...otherProperties } = member.properties!\n return JSON.stringify({ ...member, properties: otherProperties })\n }\n if (new Set(objects.map(fingerprintWithoutDiscriminator)).size !== 1) {\n continue\n }\n\n const uniqueConstValues = [...new Set(constValues)]\n if (uniqueConstValues.length < 2) {\n continue\n }\n\n // Replace the per-member `const` with a single `enum` of every value.\n const merged = structuredClone(objects[0]!)\n const discriminatorProp = merged.properties![discriminator]\n if (discriminatorProp && typeof discriminatorProp === 'object') {\n delete discriminatorProp.const\n discriminatorProp.enum = uniqueConstValues as NonNullable<typeof discriminatorProp.enum>\n }\n return merged\n }\n return null\n}\n\n// A `$ref` costs ~30 characters once names are shortened, so sharing a subschema only pays off when\n// it's larger than that and appears more than once.\nconst MIN_SHARED_SIZE = 64\n\n/** A subschema worth sharing: a standalone object/union/described schema, not a `$ref` or a primitive. */\nconst isShareable = (node: unknown): node is Record<string, unknown> => {\n if (!node || typeof node !== 'object' || Array.isArray(node) || '$ref' in node) {\n return false\n }\n const schema = node as JsonSchemaType\n return (\n Array.isArray(schema.oneOf) ||\n Array.isArray(schema.anyOf) ||\n Boolean(schema.properties) ||\n Boolean(schema.items) ||\n typeof schema.description === 'string'\n )\n}\n\n/**\n * **Size.** Replaces any subschema that appears more than once with a single shared `$defs` entry referenced by\n * `$ref`. Lossless — only the serialized size shrinks. A collection with several rich-text fields, for\n * example, inlines the same large lexical node schema once per field; this collapses them into one.\n *\n * @example\n * { properties: { billing: address, shipping: address } }\n * → { properties: { billing: { $ref: '#/$defs/shared_0' }, shipping: { $ref: '#/$defs/shared_0' } }, $defs: { shared_0: address } }\n */\nconst deduplicateIntoDefinitions = (schema: JsonSchemaType): JsonSchemaType => {\n // Count how often each shareable subschema appears, keyed by its serialized form.\n const counts = new Map<string, number>()\n const count = (node: unknown): void => {\n if (isShareable(node)) {\n const key = JSON.stringify(node)\n if (key.length >= MIN_SHARED_SIZE) {\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n }\n if (Array.isArray(node)) {\n node.forEach(count)\n } else if (node && typeof node === 'object') {\n Object.values(node).forEach(count)\n }\n }\n count(schema)\n\n if (![...counts.values()].some((n) => n >= 2)) {\n return schema\n }\n\n // Replace each subschema seen 2+ times with a `$ref`. The first time we meet one it becomes a shared\n // entry; we never descend into a stored entry, so shared entries never reference one another.\n const sharedEntries: Record<string, JsonSchemaType> = {}\n const nameByKey = new Map<string, string>()\n const share = (node: unknown): unknown => {\n if (isShareable(node)) {\n const key = JSON.stringify(node)\n if ((counts.get(key) ?? 0) >= 2) {\n let name = nameByKey.get(key)\n if (!name) {\n name = `shared_${nameByKey.size}`\n nameByKey.set(key, name)\n sharedEntries[name] = node\n }\n return { $ref: `#/$defs/${name}` }\n }\n }\n if (Array.isArray(node)) {\n return node.map(share)\n }\n if (node && typeof node === 'object') {\n return Object.fromEntries(\n Object.entries(node).map(([childKey, value]) => [childKey, share(value)]),\n )\n }\n return node\n }\n\n const result = share(schema) as JsonSchemaType\n result.$defs = { ...result.$defs, ...sharedEntries }\n return result\n}\n\n/**\n * **LLM ergonomics.** Renames `$defs` entries to short, readable names so the `$ref`s stay legible to the model: a block's\n * `blockType` (`Code`), a node's `type` (`paragraph`), `node` for a rich-text node union, otherwise the\n * generated name with its disambiguating hash dropped. A numeric suffix keeps collisions unique.\n *\n * @example\n * { properties: { body: { $ref: '#/$defs/LexicalNodes_9FBEC708' } }, $defs: { LexicalNodes_9FBEC708: {} } }\n * → { properties: { body: { $ref: '#/$defs/node' } }, $defs: { node: {} } }\n */\nconst shortenDefinitionNames = (schema: JsonSchemaType): JsonSchemaType => {\n const definitions = schema.$defs\n if (!definitions || Object.keys(definitions).length === 0) {\n return schema\n }\n\n const shortNameFor = (name: string, definition: boolean | JsonSchemaType): string => {\n const properties = (typeof definition === 'object' && definition.properties) || {}\n const constString = (key: string): string | undefined => {\n const prop = properties[key]\n return prop && typeof prop === 'object' && typeof prop.const === 'string'\n ? prop.const\n : undefined\n }\n const members =\n typeof definition === 'object' ? (definition.anyOf ?? definition.oneOf) : undefined\n const isNodeUnion =\n Array.isArray(members) &&\n members.some((m) => typeof m === 'object' && Boolean(m.$ref || m.properties?.type))\n return (\n constString('blockType') ??\n constString('type') ??\n (isNodeUnion ? 'node' : undefined) ??\n name.replace(/_[0-9A-F]{6,}$/i, '')\n )\n }\n\n const prefix = '#/$defs/'\n const usedNames = new Map<string, number>()\n const rename = new Map<string, string>()\n for (const [name, definition] of Object.entries(definitions)) {\n const shortName = shortNameFor(name, definition)\n const used = usedNames.get(shortName) ?? 0\n usedNames.set(shortName, used + 1)\n rename.set(name, used === 0 ? shortName : `${shortName}${used + 1}`)\n }\n\n const result = mapNodes(schema, (node) => {\n if (typeof node.$ref === 'string' && node.$ref.startsWith(prefix)) {\n const name = node.$ref.slice(prefix.length)\n node.$ref = `${prefix}${rename.get(name) ?? name}`\n }\n return node\n }) as JsonSchemaType\n result.$defs = Object.fromEntries(\n Object.entries(result.$defs!).map(([name, body]) => [rename.get(name) ?? name, body]),\n )\n return result\n}\n"],"names":["sanitizeEntitySchema","schema","result","structuredClone","collapseOptionalContainerTypes","pointFieldsToObjects","removeTypeGenArtifacts","dropRedundantConstType","mergeConstDiscriminatedUnions","deduplicateIntoDefinitions","shortenDefinitionNames","mapNodes","node","visit","Array","isArray","map","child","out","key","value","Object","entries","properties","keys","prop","isRequired","required","includes","collapseNullableType","items","type","nonNullTypes","filter","t","length","transformed","fromEntries","isArrayType","isPointField","every","item","isNullable","description","latitude","longitude","tsType","keyword","members","merged","mergeMembersByConst","assign","objects","member","discriminator","constValues","everyMemberPinsConst","push","const","fingerprintWithoutDiscriminator","_discriminator","otherProperties","JSON","stringify","Set","size","uniqueConstValues","discriminatorProp","enum","MIN_SHARED_SIZE","isShareable","oneOf","anyOf","Boolean","counts","Map","count","set","get","forEach","values","some","n","sharedEntries","nameByKey","share","name","$ref","childKey","$defs","definitions","shortNameFor","definition","constString","undefined","isNodeUnion","m","replace","prefix","usedNames","rename","shortName","used","startsWith","slice","body"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,MAAMA,uBAAuB,CAACC;IACnC,8FAA8F;IAC9F,IAAIC,SAASC,gBAAgBF;IAE7B,8GAA8G;IAC9GC,SAASE,+BAA+BF;IAExC,iHAAiH;IACjHA,SAASG,qBAAqBH;IAE9B,sGAAsG;IACtGA,SAASI,uBAAuBJ;IAEhC,2FAA2F;IAC3FA,SAASK,uBAAuBL;IAEhC,4GAA4G;IAC5GA,SAASM,8BAA8BN;IAEvC,4FAA4F;IAC5FA,SAASO,2BAA2BP;IAEpC,gHAAgH;IAChHA,SAASQ,uBAAuBR;IAEhC,OAAOA;AACT,EAAC;AAED;;;CAGC,GACD,MAAMS,WAAW,CAACC,MAAeC;IAC/B,IAAIC,MAAMC,OAAO,CAACH,OAAO;QACvB,OAAOA,KAAKI,GAAG,CAAC,CAACC,QAAUN,SAASM,OAAOJ;IAC7C;IACA,IAAI,CAACD,QAAQ,OAAOA,SAAS,UAAU;QACr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,MAAMC,OAAO,CAACiC,YACdA,QAAQiC,IAAI,CAAC,CAACe,IAAM,OAAOA,MAAM,YAAYvB,QAAQuB,EAAET,IAAI,IAAIS,EAAEzE,UAAU,EAAEQ;QAC/E,OACE8D,YAAY,gBACZA,YAAY,WACXE,CAAAA,cAAc,SAASD,SAAQ,KAChCR,KAAKW,OAAO,CAAC,mBAAmB;IAEpC;IAEA,MAAMC,SAAS;IACf,MAAMC,YAAY,IAAIxB;IACtB,MAAMyB,SAAS,IAAIzB;IACnB,KAAK,MAAM,CAACW,MAAMM,WAAW,IAAIvE,OAAOC,OAAO,CAACoE,aAAc;QAC5D,MAAMW,YAAYV,aAAaL,MAAMM;QACrC,MAAMU,OAAOH,UAAUrB,GAAG,CAACuB,cAAc;QACzCF,UAAUtB,GAAG,CAACwB,WAAWC,OAAO;QAChCF,OAAOvB,GAAG,CAACS,MAAMgB,SAAS,IAAID,YAAY,GAAGA,YAAYC,OAAO,GAAG;IACrE;IAEA,MAAMpG,SAASS,SAASV,QAAQ,CAACW;QAC/B,IAAI,OAAOA,KAAK2E,IAAI,KAAK,YAAY3E,KAAK2E,IAAI,CAACgB,UAAU,CAACL,SAAS;YACjE,MAAMZ,OAAO1E,KAAK2E,IAAI,CAACiB,KAAK,CAACN,OAAO/D,MAAM;YAC1CvB,KAAK2E,IAAI,GAAG,GAAGW,SAASE,OAAOtB,GAAG,CAACQ,SAASA,MAAM;QACpD;QACA,OAAO1E;IACT;IACAV,OAAOuF,KAAK,GAAGpE,OAAOgB,WAAW,CAC/BhB,OAAOC,OAAO,CAACpB,OAAOuF,KAAK,EAAGzE,GAAG,CAAC,CAAC,CAACsE,MAAMmB,KAAK,GAAK;YAACL,OAAOtB,GAAG,CAACQ,SAASA;YAAMmB;SAAK;IAEtF,OAAOvG;AACT"}
@@ -1,10 +1,11 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js';
3
3
  describe('sanitizeEntitySchema', ()=>{
4
- it('keeps a Lexical node union strict (oneOf) while simplifying relationship values to IDs', ()=>{
5
- // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field:
6
- // a `$defs` node union (a `oneOf` of node shapes) where a relationship node's `value` is either
7
- // an ID or a `$ref` to the populated related collection.
4
+ it('renames the Lexical node-union definition to a short name and keeps it a strict oneOf', ()=>{
5
+ // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field
6
+ // (Payload's `input` variant): a `$defs` node union (a `oneOf` of node shapes). The input variant
7
+ // already types the relationship node's `value` as a bare ID - there is no populated-doc `$ref` to
8
+ // reduce here (the variant did that upstream), so sanitize leaves the value untouched.
8
9
  const standalone = {
9
10
  type: 'object',
10
11
  $defs: {
@@ -30,14 +31,8 @@ describe('sanitizeEntitySchema', ()=>{
30
31
  const: 'relationship'
31
32
  },
32
33
  value: {
33
- oneOf: [
34
- {
35
- type: 'string'
36
- },
37
- {
38
- $ref: '#/$defs/posts'
39
- }
40
- ]
34
+ type: 'string',
35
+ description: 'The related document ID.'
41
36
  }
42
37
  },
43
38
  required: [
@@ -45,18 +40,6 @@ describe('sanitizeEntitySchema', ()=>{
45
40
  ]
46
41
  }
47
42
  ]
48
- },
49
- posts: {
50
- type: 'object',
51
- additionalProperties: false,
52
- properties: {
53
- id: {
54
- type: 'string'
55
- },
56
- title: {
57
- type: 'string'
58
- }
59
- }
60
43
  }
61
44
  },
62
45
  properties: {
@@ -85,7 +68,7 @@ describe('sanitizeEntitySchema', ()=>{
85
68
  type: 'object',
86
69
  $defs: {
87
70
  // The node union is renamed to a short, readable `node`, and stays a strict discriminated
88
- // `oneOf` - not loosened to `anyOf`...
71
+ // `oneOf` - not loosened to `anyOf`.
89
72
  node: {
90
73
  oneOf: [
91
74
  {
@@ -107,10 +90,10 @@ describe('sanitizeEntitySchema', ()=>{
107
90
  type: {
108
91
  const: 'relationship'
109
92
  },
110
- // ...while the relationship `value` is simplified to a bare ID (the populated-doc `$ref` is dropped).
93
+ // The value is already ID-only from the input variant - left as-is.
111
94
  value: {
112
95
  type: 'string',
113
- description: 'The ID of the related "posts" document.'
96
+ description: 'The related document ID.'
114
97
  }
115
98
  },
116
99
  required: [
@@ -118,22 +101,14 @@ describe('sanitizeEntitySchema', ()=>{
118
101
  ]
119
102
  }
120
103
  ]
121
- },
122
- posts: {
123
- type: 'object',
124
- additionalProperties: false,
125
- properties: {
126
- id: {
127
- type: 'string'
128
- },
129
- title: {
130
- type: 'string'
131
- }
132
- }
133
104
  }
134
105
  },
135
106
  properties: {
136
- // `id` is dropped - it's a Payload-managed field MCP clients never set.
107
+ // Managed fields (createdAt/updatedAt/_status) are excluded upstream by the `input` variant;
108
+ // `id` stays because it's a valid optional input (a client may supply a custom ID).
109
+ id: {
110
+ type: 'string'
111
+ },
137
112
  content: {
138
113
  type: 'object',
139
114
  properties: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.spec.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest'\n\nimport type { JsonSchemaType } from '../../types.js'\n\nimport { sanitizeEntitySchema } from './sanitizeEntitySchema.js'\n\ndescribe('sanitizeEntitySchema', () => {\n it('keeps a Lexical node union strict (oneOf) while simplifying relationship values to IDs', () => {\n // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field:\n // a `$defs` node union (a `oneOf` of node shapes) where a relationship node's `value` is either\n // an ID or a `$ref` to the populated related collection.\n const standalone: JsonSchemaType = {\n type: 'object',\n $defs: {\n LexicalNodes_ABCDEF12: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n properties: { type: { const: 'paragraph' } },\n required: ['type'],\n },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n type: { const: 'relationship' },\n value: { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] },\n },\n required: ['type'],\n },\n ],\n },\n posts: {\n type: 'object',\n additionalProperties: false,\n properties: { id: { type: 'string' }, title: { type: 'string' } },\n },\n },\n properties: {\n id: { type: 'string' },\n content: {\n type: 'object',\n properties: {\n root: {\n type: 'object',\n properties: {\n children: { type: 'array', items: { $ref: '#/$defs/LexicalNodes_ABCDEF12' } },\n },\n },\n },\n },\n },\n }\n\n expect(sanitizeEntitySchema(standalone)).toStrictEqual({\n type: 'object',\n $defs: {\n // The node union is renamed to a short, readable `node`, and stays a strict discriminated\n // `oneOf` - not loosened to `anyOf`...\n node: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n properties: { type: { const: 'paragraph' } },\n required: ['type'],\n },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n type: { const: 'relationship' },\n // ...while the relationship `value` is simplified to a bare ID (the populated-doc `$ref` is dropped).\n value: { type: 'string', description: 'The ID of the related \"posts\" document.' },\n },\n required: ['type'],\n },\n ],\n },\n posts: {\n type: 'object',\n additionalProperties: false,\n properties: { id: { type: 'string' }, title: { type: 'string' } },\n },\n },\n properties: {\n // `id` is dropped - it's a Payload-managed field MCP clients never set.\n content: {\n type: 'object',\n properties: {\n root: {\n type: 'object',\n properties: {\n children: { type: 'array', items: { $ref: '#/$defs/node' } },\n },\n },\n },\n },\n },\n })\n })\n})\n"],"names":["describe","expect","it","sanitizeEntitySchema","standalone","type","$defs","LexicalNodes_ABCDEF12","oneOf","additionalProperties","properties","const","required","value","$ref","posts","id","title","content","root","children","items","toStrictEqual","node","description"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhEH,SAAS,wBAAwB;IAC/BE,GAAG,0FAA0F;QAC3F,iGAAiG;QACjG,gGAAgG;QAChG,yDAAyD;QACzD,MAAME,aAA6B;YACjCC,MAAM;YACNC,OAAO;gBACLC,uBAAuB;oBACrBC,OAAO;wBACL;4BACEH,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCAAEL,MAAM;oCAAEM,OAAO;gCAAY;4BAAE;4BAC3CC,UAAU;gCAAC;6BAAO;wBACpB;wBACA;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YACF;YACAK,YAAY;gBACV,wEAAwE;gBACxEQ,SAAS;oBACPb,MAAM;oBACNK,YAAY;wBACVS,MAAM;4BACJd,MAAM;4BACNK,YAAY;gCACVU,UAAU;oCAAEf,MAAM;oCAASgB,OAAO;wCAAEP,MAAM;oCAAe;gCAAE;4BAC7D;wBACF;oBACF;gBACF;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/utils/schemaConversion/sanitizeEntitySchema.spec.ts"],"sourcesContent":["import { describe, expect, it } from 'vitest'\n\nimport type { JsonSchemaType } from '../../types.js'\n\nimport { sanitizeEntitySchema } from './sanitizeEntitySchema.js'\n\ndescribe('sanitizeEntitySchema', () => {\n it('renames the Lexical node-union definition to a short name and keeps it a strict oneOf', () => {\n // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field\n // (Payload's `input` variant): a `$defs` node union (a `oneOf` of node shapes). The input variant\n // already types the relationship node's `value` as a bare ID - there is no populated-doc `$ref` to\n // reduce here (the variant did that upstream), so sanitize leaves the value untouched.\n const standalone: JsonSchemaType = {\n type: 'object',\n $defs: {\n LexicalNodes_ABCDEF12: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n properties: { type: { const: 'paragraph' } },\n required: ['type'],\n },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n type: { const: 'relationship' },\n value: { type: 'string', description: 'The related document ID.' },\n },\n required: ['type'],\n },\n ],\n },\n },\n properties: {\n id: { type: 'string' },\n content: {\n type: 'object',\n properties: {\n root: {\n type: 'object',\n properties: {\n children: { type: 'array', items: { $ref: '#/$defs/LexicalNodes_ABCDEF12' } },\n },\n },\n },\n },\n },\n }\n\n expect(sanitizeEntitySchema(standalone)).toStrictEqual({\n type: 'object',\n $defs: {\n // The node union is renamed to a short, readable `node`, and stays a strict discriminated\n // `oneOf` - not loosened to `anyOf`.\n node: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n properties: { type: { const: 'paragraph' } },\n required: ['type'],\n },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n type: { const: 'relationship' },\n // The value is already ID-only from the input variant - left as-is.\n value: { type: 'string', description: 'The related document ID.' },\n },\n required: ['type'],\n },\n ],\n },\n },\n properties: {\n // Managed fields (createdAt/updatedAt/_status) are excluded upstream by the `input` variant;\n // `id` stays because it's a valid optional input (a client may supply a custom ID).\n id: { type: 'string' },\n content: {\n type: 'object',\n properties: {\n root: {\n type: 'object',\n properties: {\n children: { type: 'array', items: { $ref: '#/$defs/node' } },\n },\n },\n },\n },\n },\n })\n })\n})\n"],"names":["describe","expect","it","sanitizeEntitySchema","standalone","type","$defs","LexicalNodes_ABCDEF12","oneOf","additionalProperties","properties","const","required","value","description","id","content","root","children","items","$ref","toStrictEqual","node"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,oBAAoB,QAAQ,4BAA2B;AAEhEH,SAAS,wBAAwB;IAC/BE,GAAG,yFAAyF;QAC1F,gGAAgG;QAChG,kGAAkG;QAClG,mGAAmG;QACnG,uFAAuF;QACvF,MAAME,aAA6B;YACjCC,MAAM;YACNC,OAAO;gBACLC,uBAAuB;oBACrBC,OAAO;wBACL;4BACEH,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCAAEL,MAAM;oCAAEM,OAAO;gCAAY;4BAAE;4BAC3CC,UAAU;gCAAC;6BAAO;wBACpB;wBACA;4BACEP,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCACVL,MAAM;oCAAEM,OAAO;gCAAe;gCAC9BE,OAAO;oCAAER,MAAM;oCAAUS,aAAa;gCAA2B;4BACnE;4BACAF,UAAU;gCAAC;6BAAO;wBACpB;qBACD;gBACH;YACF;YACAF,YAAY;gBACVK,IAAI;oBAAEV,MAAM;gBAAS;gBACrBW,SAAS;oBACPX,MAAM;oBACNK,YAAY;wBACVO,MAAM;4BACJZ,MAAM;4BACNK,YAAY;gCACVQ,UAAU;oCAAEb,MAAM;oCAASc,OAAO;wCAAEC,MAAM;oCAAgC;gCAAE;4BAC9E;wBACF;oBACF;gBACF;YACF;QACF;QAEAnB,OAAOE,qBAAqBC,aAAaiB,aAAa,CAAC;YACrDhB,MAAM;YACNC,OAAO;gBACL,0FAA0F;gBAC1F,qCAAqC;gBACrCgB,MAAM;oBACJd,OAAO;wBACL;4BACEH,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCAAEL,MAAM;oCAAEM,OAAO;gCAAY;4BAAE;4BAC3CC,UAAU;gCAAC;6BAAO;wBACpB;wBACA;4BACEP,MAAM;4BACNI,sBAAsB;4BACtBC,YAAY;gCACVL,MAAM;oCAAEM,OAAO;gCAAe;gCAC9B,oEAAoE;gCACpEE,OAAO;oCAAER,MAAM;oCAAUS,aAAa;gCAA2B;4BACnE;4BACAF,UAAU;gCAAC;6BAAO;wBACpB;qBACD;gBACH;YACF;YACAF,YAAY;gBACV,6FAA6F;gBAC7F,oFAAoF;gBACpFK,IAAI;oBAAEV,MAAM;gBAAS;gBACrBW,SAAS;oBACPX,MAAM;oBACNK,YAAY;wBACVO,MAAM;4BACJZ,MAAM;4BACNK,YAAY;gCACVQ,UAAU;oCAAEb,MAAM;oCAASc,OAAO;wCAAEC,MAAM;oCAAe;gCAAE;4BAC7D;wBACF;oBACF;gBACF;YACF;QACF;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-mcp",
3
- "version": "4.0.0-canary.4",
3
+ "version": "4.0.0-canary.6",
4
4
  "description": "MCP (Model Context Protocol) capabilities with Payload",
5
5
  "keywords": [
6
6
  "plugin",
@@ -62,10 +62,10 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "@payloadcms/eslint-config": "3.28.0",
65
- "payload": "4.0.0-canary.4"
65
+ "payload": "4.0.0-canary.6"
66
66
  },
67
67
  "peerDependencies": {
68
- "payload": "4.0.0-canary.4"
68
+ "payload": "4.0.0-canary.6"
69
69
  },
70
70
  "//deps_notes": {
71
71
  "zod": "zod is a hard dependency of @modelcontextprotocol/server, thus we can safely use it without it impacting bundle size. Make extra sure the zod version here matches exactly what's defined in the dependencies of @modelcontextprotocol/server to avoid duplicate versions being installed.",
@@ -9,11 +9,6 @@ import {
9
9
 
10
10
  import type { JsonSchemaType } from '../../types.js'
11
11
 
12
- import {
13
- getCollectionVirtualFieldNames,
14
- getGlobalVirtualFieldNames,
15
- } from '../getVirtualFieldNames.js'
16
- import { removeVirtualFieldsFromSchema } from './removeVirtualFieldsFromSchema.js'
17
12
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js'
18
13
 
19
14
  export const getCollectionInputSchema = ({
@@ -29,11 +24,7 @@ export const getCollectionInputSchema = ({
29
24
  return null
30
25
  }
31
26
 
32
- return buildEntityInputSchema({
33
- entity: collection,
34
- req,
35
- virtualFieldNames: getCollectionVirtualFieldNames(req.payload.config, collectionSlug),
36
- })
27
+ return buildEntityInputSchema({ entity: collection, req })
37
28
  }
38
29
 
39
30
  export const getGlobalInputSchema = ({
@@ -49,30 +40,23 @@ export const getGlobalInputSchema = ({
49
40
  return null
50
41
  }
51
42
 
52
- return buildEntityInputSchema({
53
- entity: global,
54
- req,
55
- virtualFieldNames: getGlobalVirtualFieldNames(req.payload.config, globalSlug),
56
- })
43
+ return buildEntityInputSchema({ entity: global, req })
57
44
  }
58
45
 
59
46
  const buildEntityInputSchema = ({
60
47
  entity,
61
48
  req,
62
- virtualFieldNames,
63
49
  }: {
64
50
  entity: SanitizedCollectionConfig | SanitizedGlobalConfig
65
51
  req: PayloadRequest
66
- virtualFieldNames: string[]
67
52
  }): JsonSchemaType =>
53
+ // The `input` variant is already the write shape; sanitizeEntitySchema only adds MCP-specific passes.
68
54
  sanitizeEntitySchema(
69
- removeVirtualFieldsFromSchema(
70
- entityToStandaloneJSONSchema({
71
- config: req.payload.config,
72
- defaultIDType: req.payload.db.defaultIDType,
73
- entity,
74
- i18n: req.i18n,
75
- }) as unknown as JsonSchemaType,
76
- virtualFieldNames,
77
- ),
55
+ entityToStandaloneJSONSchema({
56
+ config: req.payload.config,
57
+ defaultIDType: req.payload.db.defaultIDType,
58
+ entity,
59
+ i18n: req.i18n,
60
+ variant: 'input',
61
+ }) as unknown as JsonSchemaType,
78
62
  )
@@ -5,10 +5,11 @@ import type { JsonSchemaType } from '../../types.js'
5
5
  import { sanitizeEntitySchema } from './sanitizeEntitySchema.js'
6
6
 
7
7
  describe('sanitizeEntitySchema', () => {
8
- it('keeps a Lexical node union strict (oneOf) while simplifying relationship values to IDs', () => {
9
- // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field:
10
- // a `$defs` node union (a `oneOf` of node shapes) where a relationship node's `value` is either
11
- // an ID or a `$ref` to the populated related collection.
8
+ it('renames the Lexical node-union definition to a short name and keeps it a strict oneOf', () => {
9
+ // Shaped like the schema the MCP server prepares for a collection with a Lexical richText field
10
+ // (Payload's `input` variant): a `$defs` node union (a `oneOf` of node shapes). The input variant
11
+ // already types the relationship node's `value` as a bare ID - there is no populated-doc `$ref` to
12
+ // reduce here (the variant did that upstream), so sanitize leaves the value untouched.
12
13
  const standalone: JsonSchemaType = {
13
14
  type: 'object',
14
15
  $defs: {
@@ -25,17 +26,12 @@ describe('sanitizeEntitySchema', () => {
25
26
  additionalProperties: false,
26
27
  properties: {
27
28
  type: { const: 'relationship' },
28
- value: { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] },
29
+ value: { type: 'string', description: 'The related document ID.' },
29
30
  },
30
31
  required: ['type'],
31
32
  },
32
33
  ],
33
34
  },
34
- posts: {
35
- type: 'object',
36
- additionalProperties: false,
37
- properties: { id: { type: 'string' }, title: { type: 'string' } },
38
- },
39
35
  },
40
36
  properties: {
41
37
  id: { type: 'string' },
@@ -57,7 +53,7 @@ describe('sanitizeEntitySchema', () => {
57
53
  type: 'object',
58
54
  $defs: {
59
55
  // The node union is renamed to a short, readable `node`, and stays a strict discriminated
60
- // `oneOf` - not loosened to `anyOf`...
56
+ // `oneOf` - not loosened to `anyOf`.
61
57
  node: {
62
58
  oneOf: [
63
59
  {
@@ -71,21 +67,18 @@ describe('sanitizeEntitySchema', () => {
71
67
  additionalProperties: false,
72
68
  properties: {
73
69
  type: { const: 'relationship' },
74
- // ...while the relationship `value` is simplified to a bare ID (the populated-doc `$ref` is dropped).
75
- value: { type: 'string', description: 'The ID of the related "posts" document.' },
70
+ // The value is already ID-only from the input variant - left as-is.
71
+ value: { type: 'string', description: 'The related document ID.' },
76
72
  },
77
73
  required: ['type'],
78
74
  },
79
75
  ],
80
76
  },
81
- posts: {
82
- type: 'object',
83
- additionalProperties: false,
84
- properties: { id: { type: 'string' }, title: { type: 'string' } },
85
- },
86
77
  },
87
78
  properties: {
88
- // `id` is dropped - it's a Payload-managed field MCP clients never set.
79
+ // Managed fields (createdAt/updatedAt/_status) are excluded upstream by the `input` variant;
80
+ // `id` stays because it's a valid optional input (a client may supply a custom ID).
81
+ id: { type: 'string' },
89
82
  content: {
90
83
  type: 'object',
91
84
  properties: {
@@ -1,30 +1,22 @@
1
1
  import type { JsonSchemaType } from '../../types.js'
2
2
 
3
3
  /**
4
- * Turns the JSON Schema that Payload generates for a collection or global into the input schema for
5
- * an MCP create/update tool. In short, it:
6
- *
7
- * - drops fields a client can't set (`id`, `createdAt`, the draft `_status`, …),
8
- * - rewrites Payload-specific field shapes (points, relationships) into plain JSON the model can fill,
9
- * - and shrinks the result so it's cheaper for the model to read,
10
- *
11
- * while keeping every node valid JSON Schema draft 2020-12. Each step below is tagged with why it runs -
12
- * **Correctness** (valid input the API accepts), **Size** (equivalence-preserving shrink), or **LLM
13
- * ergonomics** (easier for the model to read/fill) - and carries a before/after example on its definition.
4
+ * Refines Payload's `input`-variant JSON Schema into an MCP create/update tool's input schema. The
5
+ * variant already covers correctness (ID-only relationships, no managed/virtual/join fields); the
6
+ * passes here are MCP-specific - reshaping fields for the model and shrinking the result - and keep
7
+ * every node valid JSON Schema draft 2020-12. Each is tagged **Correctness**, **Size**, or **LLM
8
+ * ergonomics**, with a before/after example on its definition.
14
9
  */
15
10
  export const sanitizeEntitySchema = (schema: JsonSchemaType): JsonSchemaType => {
16
11
  // Work on a copy — the caller reuses the original schema elsewhere (e.g. when listing tools).
17
12
  let result = structuredClone(schema)
18
13
 
19
- // Correctness — drop the fields a client can't set (id, createdAt, updatedAt, draft _status) + collapse nullable types.
20
- result = removeManagedFields(result)
14
+ // LLM ergonomics — drop the redundant `'null'` from optional arrays/objects (`['array','null']` `'array'`).
15
+ result = collapseOptionalContainerTypes(result)
21
16
 
22
17
  // LLM ergonomics — rewrite point fields from a `[number, number]` tuple into a `{ longitude, latitude }` object.
23
18
  result = pointFieldsToObjects(result)
24
19
 
25
- // Correctness — a relationship value can be an ID or a populated doc; on input only the ID is valid, so keep that.
26
- result = relationshipsToIds(result)
27
-
28
20
  // Size — strip inert type-gen leftovers that only bloat the schema (`tsType`, block-collision notes).
29
21
  result = removeTypeGenArtifacts(result)
30
22
 
@@ -58,26 +50,20 @@ const mapNodes = (node: unknown, visit: (node: JsonSchemaType) => JsonSchemaType
58
50
  for (const [key, value] of Object.entries(node)) {
59
51
  out[key] = mapNodes(value, visit)
60
52
  }
61
- return visit(out as JsonSchemaType)
53
+ return visit(out)
62
54
  }
63
55
 
64
- // Payload sets these on every document, so an MCP client never provides them when creating/updating.
65
- const PAYLOAD_MANAGED_FIELDS = new Set(['_status', 'createdAt', 'id', 'updatedAt'])
66
-
67
56
  /**
68
- * **Correctness.** Removes the fields a client can't set on create/update - `id`, `createdAt`, `updatedAt`, and the draft
69
- * `_status` - from every field object's `properties` and `required` (recursing into nested objects and
70
- * array items). Along the way it also collapses optional array/object types via {@link collapseNullableType}.
57
+ * **LLM ergonomics.** Collapses optional array/object types (`['array', 'null']` `'array'`) via
58
+ * {@link collapseNullableType}, recursing through `properties` and array items. The `required` list
59
+ * already conveys optionality, so the `'null'` is redundant noise for the model.
71
60
  *
72
61
  * @example
73
- * { properties: { id: { type: 'string' }, tags: { type: ['array', 'null'], items: {} } }, required: ['id', 'tags'] }
74
- * → { properties: { tags: { type: 'array', items: {} } }, required: ['tags'] }
62
+ * { properties: { tags: { type: ['array', 'null'], items: {} } }, required: [] }
63
+ * → { properties: { tags: { type: 'array', items: {} } }, required: [] }
75
64
  */
76
- const removeManagedFields = (schema: JsonSchemaType): JsonSchemaType => {
65
+ const collapseOptionalContainerTypes = (schema: JsonSchemaType): JsonSchemaType => {
77
66
  if (schema.properties && typeof schema.properties === 'object') {
78
- for (const field of PAYLOAD_MANAGED_FIELDS) {
79
- delete schema.properties[field]
80
- }
81
67
  for (const key of Object.keys(schema.properties)) {
82
68
  const prop = schema.properties[key] as JsonSchemaType
83
69
  if (!prop || typeof prop !== 'object') {
@@ -86,21 +72,14 @@ const removeManagedFields = (schema: JsonSchemaType): JsonSchemaType => {
86
72
  const isRequired = Array.isArray(schema.required) && schema.required.includes(key)
87
73
  collapseNullableType(prop, isRequired)
88
74
  if (prop.properties) {
89
- removeManagedFields(prop)
75
+ collapseOptionalContainerTypes(prop)
90
76
  }
91
77
  if (prop.items && typeof prop.items === 'object' && !Array.isArray(prop.items)) {
92
- removeManagedFields(prop.items)
78
+ collapseOptionalContainerTypes(prop.items)
93
79
  }
94
80
  }
95
81
  }
96
82
 
97
- if (Array.isArray(schema.required)) {
98
- schema.required = schema.required.filter((name) => !PAYLOAD_MANAGED_FIELDS.has(name))
99
- if (schema.required.length === 0) {
100
- delete schema.required
101
- }
102
- }
103
-
104
83
  return schema
105
84
  }
106
85
 
@@ -193,82 +172,6 @@ const pointFieldsToObjects = (schema: JsonSchemaType): JsonSchemaType => {
193
172
  return transformed
194
173
  }
195
174
 
196
- /**
197
- * **Correctness.** Reduces relationship/upload fields to the IDs a client actually sends. Payload types the value as
198
- * "an ID or the full related document" - but the populated-document form only appears in read responses;
199
- * on create/update you always reference a relationship by its ID. So we drop that `$ref` option, leaving
200
- * the bare ID. A single remaining target collapses inline (with a description naming the target
201
- * collection); several targets become an `anyOf` of IDs.
202
- *
203
- * @example
204
- * { oneOf: [{ type: 'string' }, { $ref: '#/$defs/posts' }] }
205
- * → { type: 'string', description: 'The ID of the related "posts" document.' }
206
- */
207
- const relationshipsToIds = (schema: JsonSchemaType): JsonSchemaType => {
208
- if (!schema || typeof schema !== 'object') {
209
- return schema
210
- }
211
-
212
- const processed = { ...schema }
213
-
214
- if (Array.isArray(processed.oneOf)) {
215
- const isRelatedDocRef = (option: unknown): option is { $ref: string } =>
216
- !!option && typeof option === 'object' && '$ref' in option
217
-
218
- if (processed.oneOf.some(isRelatedDocRef)) {
219
- // A relationship value is "an ID, or the populated related document". Keep the ID option(s) and
220
- // drop the `$ref`s to the related collections, since a client only ever sends the ID.
221
- const idOptions = processed.oneOf
222
- .filter((option) => !isRelatedDocRef(option))
223
- .map((option) => (typeof option === 'object' ? relationshipsToIds(option) : option))
224
- const targetCollections = processed.oneOf
225
- .filter(isRelatedDocRef)
226
- .map((option) => option.$ref.replace('#/$defs/', ''))
227
-
228
- if (idOptions.length === 1) {
229
- delete processed.oneOf
230
- Object.assign(processed, idOptions[0])
231
- if (targetCollections.length > 0 && !processed.description) {
232
- processed.description = `The ID of the related "${targetCollections.join('" or "')}" document.`
233
- }
234
- } else if (idOptions.length > 1) {
235
- delete processed.oneOf
236
- processed.anyOf = idOptions
237
- }
238
- } else {
239
- processed.oneOf = processed.oneOf.map((option) =>
240
- typeof option === 'object' ? relationshipsToIds(option) : option,
241
- )
242
- }
243
- }
244
-
245
- if (processed.properties && typeof processed.properties === 'object') {
246
- processed.properties = Object.fromEntries(
247
- Object.entries(processed.properties).map(([key, value]) => [
248
- key,
249
- typeof value === 'object' ? relationshipsToIds(value) : value,
250
- ]),
251
- )
252
- }
253
-
254
- if (processed.items && typeof processed.items === 'object' && !Array.isArray(processed.items)) {
255
- processed.items = relationshipsToIds(processed.items)
256
- }
257
-
258
- // Lexical node unions and blocks live under `$defs` and have their own relationship fields, so walk
259
- // those too — otherwise their `$ref`s would dangle once we don't bundle the related collections.
260
- if (processed.$defs && typeof processed.$defs === 'object') {
261
- processed.$defs = Object.fromEntries(
262
- Object.entries(processed.$defs).map(([key, value]) => [
263
- key,
264
- typeof value === 'object' ? relationshipsToIds(value) : value,
265
- ]),
266
- )
267
- }
268
-
269
- return processed
270
- }
271
-
272
175
  /**
273
176
  * **Size.** Strips type-generation leftovers that bloat the schema without helping the model: the `tsType`
274
177
  * hint (a `json-schema-to-typescript` extension; JSON Schema validators just ignore it, they don't reject it)
@@ -448,7 +351,7 @@ const deduplicateIntoDefinitions = (schema: JsonSchemaType): JsonSchemaType => {
448
351
  if (!name) {
449
352
  name = `shared_${nameByKey.size}`
450
353
  nameByKey.set(key, name)
451
- sharedEntries[name] = node as JsonSchemaType
354
+ sharedEntries[name] = node
452
355
  }
453
356
  return { $ref: `#/$defs/${name}` }
454
357
  }
@@ -1,7 +0,0 @@
1
- import type { JsonSchemaType } from '../../types.js';
2
- /**
3
- * Removes virtual fields from a JSON Schema by name so they don't appear
4
- * in the generated MCP tool input schema.
5
- */
6
- export declare function removeVirtualFieldsFromSchema(schema: JsonSchemaType, virtualFieldNames: string[]): JsonSchemaType;
7
- //# sourceMappingURL=removeVirtualFieldsFromSchema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"removeVirtualFieldsFromSchema.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAEpD;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,MAAM,EAAE,cAAc,EACtB,iBAAiB,EAAE,MAAM,EAAE,GAC1B,cAAc,CAiBhB"}
@@ -1,20 +0,0 @@
1
- /**
2
- * Removes virtual fields from a JSON Schema by name so they don't appear
3
- * in the generated MCP tool input schema.
4
- */ export function removeVirtualFieldsFromSchema(schema, virtualFieldNames) {
5
- if (virtualFieldNames.length === 0) {
6
- return schema;
7
- }
8
- for (const name of virtualFieldNames){
9
- delete schema?.properties?.[name];
10
- }
11
- if (Array.isArray(schema.required)) {
12
- schema.required = schema.required.filter((field)=>!virtualFieldNames.includes(field));
13
- if (schema.required.length === 0) {
14
- delete schema.required;
15
- }
16
- }
17
- return schema;
18
- }
19
-
20
- //# sourceMappingURL=removeVirtualFieldsFromSchema.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../src/utils/schemaConversion/removeVirtualFieldsFromSchema.ts"],"sourcesContent":["import type { JsonSchemaType } from '../../types.js'\n\n/**\n * Removes virtual fields from a JSON Schema by name so they don't appear\n * in the generated MCP tool input schema.\n */\nexport function removeVirtualFieldsFromSchema(\n schema: JsonSchemaType,\n virtualFieldNames: string[],\n): JsonSchemaType {\n if (virtualFieldNames.length === 0) {\n return schema\n }\n\n for (const name of virtualFieldNames) {\n delete schema?.properties?.[name]\n }\n\n if (Array.isArray(schema.required)) {\n schema.required = schema.required.filter((field) => !virtualFieldNames.includes(field))\n if (schema.required.length === 0) {\n delete schema.required\n }\n }\n\n return schema\n}\n"],"names":["removeVirtualFieldsFromSchema","schema","virtualFieldNames","length","name","properties","Array","isArray","required","filter","field","includes"],"mappings":"AAEA;;;CAGC,GACD,OAAO,SAASA,8BACdC,MAAsB,EACtBC,iBAA2B;IAE3B,IAAIA,kBAAkBC,MAAM,KAAK,GAAG;QAClC,OAAOF;IACT;IAEA,KAAK,MAAMG,QAAQF,kBAAmB;QACpC,OAAOD,QAAQI,YAAY,CAACD,KAAK;IACnC;IAEA,IAAIE,MAAMC,OAAO,CAACN,OAAOO,QAAQ,GAAG;QAClCP,OAAOO,QAAQ,GAAGP,OAAOO,QAAQ,CAACC,MAAM,CAAC,CAACC,QAAU,CAACR,kBAAkBS,QAAQ,CAACD;QAChF,IAAIT,OAAOO,QAAQ,CAACL,MAAM,KAAK,GAAG;YAChC,OAAOF,OAAOO,QAAQ;QACxB;IACF;IAEA,OAAOP;AACT"}
@@ -1,27 +0,0 @@
1
- import type { JsonSchemaType } from '../../types.js'
2
-
3
- /**
4
- * Removes virtual fields from a JSON Schema by name so they don't appear
5
- * in the generated MCP tool input schema.
6
- */
7
- export function removeVirtualFieldsFromSchema(
8
- schema: JsonSchemaType,
9
- virtualFieldNames: string[],
10
- ): JsonSchemaType {
11
- if (virtualFieldNames.length === 0) {
12
- return schema
13
- }
14
-
15
- for (const name of virtualFieldNames) {
16
- delete schema?.properties?.[name]
17
- }
18
-
19
- if (Array.isArray(schema.required)) {
20
- schema.required = schema.required.filter((field) => !virtualFieldNames.includes(field))
21
- if (schema.required.length === 0) {
22
- delete schema.required
23
- }
24
- }
25
-
26
- return schema
27
- }