d365fo-mcp 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/bridge/D365MetadataBridge/Program.cs +2 -1
  3. package/bridge/D365MetadataBridge/Services/CrossReferenceService.cs +230 -25
  4. package/bridge/D365MetadataBridge/Services/MetadataWriteService.cs +8 -2
  5. package/dist/bridge/bridgeAdapter.js +79 -18
  6. package/dist/bridge/bridgeTypes.d.ts +4 -0
  7. package/dist/cli/commands/doctor.d.ts +8 -0
  8. package/dist/cli/commands/doctor.js +24 -0
  9. package/dist/config/settings.js +22 -0
  10. package/dist/index.js +1 -1
  11. package/dist/metadata/symbolIndex.d.ts +42 -0
  12. package/dist/metadata/symbolIndex.js +73 -8
  13. package/dist/scripts/build-database.js +78 -7
  14. package/dist/scripts/build-fts.js +78 -7
  15. package/dist/scripts/extract-metadata.js +18 -0
  16. package/dist/scripts/startupIndexWorker.js +60 -7
  17. package/dist/server/toolAnnotations.js +1 -1
  18. package/dist/server/toolSchemas/buildD365foProject.d.ts +8 -0
  19. package/dist/server/toolSchemas/buildD365foProject.js +8 -0
  20. package/dist/server/toolSchemas/d365foFile.js +9 -8
  21. package/dist/server/toolSchemas/findReferences.d.ts +0 -1
  22. package/dist/server/toolSchemas/findReferences.js +3 -4
  23. package/dist/server/toolSchemas/index.d.ts +8 -1
  24. package/dist/tools/analysis/findReferences.d.ts +33 -0
  25. package/dist/tools/analysis/findReferences.js +221 -18
  26. package/dist/tools/d365foFile.d.ts +2 -1
  27. package/dist/tools/d365foFile.js +9 -2
  28. package/dist/tools/readers/edtInfo.d.ts +21 -0
  29. package/dist/tools/readers/edtInfo.js +50 -5
  30. package/dist/tools/readers/tableInfo.js +24 -1
  31. package/dist/tools/sdlc/aosRuntime.d.ts +51 -0
  32. package/dist/tools/sdlc/aosRuntime.js +246 -0
  33. package/dist/tools/sdlc/aosRuntimePowerShell.d.ts +3 -0
  34. package/dist/tools/sdlc/aosRuntimePowerShell.js +176 -0
  35. package/dist/tools/sdlc/aosWebConfig.d.ts +9 -0
  36. package/dist/tools/sdlc/aosWebConfig.js +50 -0
  37. package/dist/tools/sdlc/buildProject.d.ts +24 -2
  38. package/dist/tools/sdlc/buildProject.js +549 -154
  39. package/dist/tools/smart/codeGen.js +8 -0
  40. package/dist/tools/smart/generateSmartTable.d.ts +3 -3
  41. package/dist/tools/smart/generateSmartTable.js +3 -3
  42. package/dist/tools/specs/opSpecs.js +46 -0
  43. package/dist/tools/write/createProject.d.ts +27 -0
  44. package/dist/tools/write/createProject.js +188 -0
  45. package/dist/tools/write/directXmlWriters.js +4 -0
  46. package/dist/tools/write/modifyD365File.js +5 -4
  47. package/dist/tools/write/projectAction.d.ts +12 -0
  48. package/dist/tools/write/projectAction.js +175 -0
  49. package/dist/utils/configManager.d.ts +10 -2
  50. package/dist/utils/configManager.js +16 -2
  51. package/dist/utils/formExtensionControlXml.js +59 -19
  52. package/dist/utils/pathContainment.d.ts +6 -0
  53. package/dist/utils/pathContainment.js +58 -0
  54. package/dist/workspace/projectScaffold.d.ts +117 -0
  55. package/dist/workspace/projectScaffold.js +568 -0
  56. package/package.json +4 -4
package/README.md CHANGED
@@ -52,7 +52,7 @@ This server pre-indexes your entire D365FO installation (580 000+ symbols across
52
52
  | 🛡️ **Grounded generation** | Fail-closed gates: `prepare` issues grounding tokens, `validate_code(mode="references")` proves every identifier, `validate_code(mode="syntax")` enforces best practices — hallucinated code never reaches disk |
53
53
  | 🧩 **Form pattern engine** | Complete catalog of Microsoft form patterns and sub-patterns: recommends the right pattern, clones reference forms with datasource re-binding, **deterministically expands** patterns that have no reference form, **auto-repairs** a form's missing required controls, validates structure and blocks invalid writes |
54
54
  | ✍️ **Safe metadata writes** | C# bridge uses Microsoft's own `IMetadataProvider` wherever it can express the object; the few types and ops it cannot go through structured XML writers with ambiguity guards — never blind string replacement. Automatic `.rnrproj` registration, one-call undo |
55
- | 🏗️ **SDLC integration** | MSBuild compilation with structured diagnostics, DB sync, xppbp best practices, SysTestRunner — all from chat |
55
+ | 🏗️ **SDLC integration** | MSBuild compilation with structured diagnostics, DB sync, xppbp best practices, SysTestRunner — all from chat. Optional `restartAos: true` refreshes the matching local IIS/IIS Express runtime after a successful build and requested sync. [Runtime restart](docs/AOS_RUNTIME_RESTART.md) |
56
56
  | 📐 **X++ knowledge base** | Queryable rules: select grammar, CoC authoring, financial dimensions, the posting engine (`LedgerVoucher`), number sequences, `SysExtension`, Electronic Reporting, AX2012→D365FO migration — prevents deprecated APIs |
57
57
 
58
58
  ### Pattern-grounded form development
@@ -530,7 +530,8 @@ Options:
530
530
  Microsoft-shipped metadata in UDE environments.
531
531
  --bin-path <path> Explicit DLL directory (UDE: microsoftPackagesPath\bin). If omitted, uses {packages-path}\bin.
532
532
  --xref-server <server> SQL Server for cross-reference DB (default: localhost)
533
- --xref-database <db> Cross-reference database name (default: DYNAMICSXREFDB)
533
+ --xref-database <db> Cross-reference database name, e.g. DYNAMICSXREFDB
534
+ (no default: without it cross-references are off)
534
535
  --log-file <path> Write all diagnostic logs to this file (append mode)
535
536
  --help Show this help
536
537
 
@@ -169,11 +169,16 @@ namespace D365MetadataBridge.Services
169
169
 
170
170
  var pathVariants = new List<string>();
171
171
  bool memberQualified = false;
172
- if (objectPath.StartsWith("/"))
172
+ if (objectPath.Contains("/"))
173
173
  {
174
- // Explicit AOT path — use exactly as given (e.g. /Tables/SalesTable/Methods/initFromX).
174
+ // Explicit path — as given: an AOT path ("/Tables/SalesTable/Methods/initFromX")
175
+ // or a metadata one ("Table/SalesTable"). An X++ one gets its metadata twin below.
175
176
  pathVariants.Add(objectPath);
176
- memberQualified = objectPath.Contains("/Methods/") || objectPath.Contains("/Fields/");
177
+ memberQualified = objectPath.Contains("/Methods/") || objectPath.Contains("/Fields/") ||
178
+ objectPath.Contains("/Method/") || objectPath.Contains("/TableField") ||
179
+ objectPath.Contains("/EnumValues/") || objectPath.Contains("/EnumValue/") ||
180
+ objectPath.Contains("/TableIndexs/") || objectPath.Contains("/TableIndex/") ||
181
+ objectPath.Contains("/TableFieldGroups/") || objectPath.Contains("/TableFieldGroup/");
177
182
  }
178
183
  else if (objectPath.Contains("."))
179
184
  {
@@ -190,16 +195,33 @@ namespace D365MetadataBridge.Services
190
195
  pathVariants.Add($"/{c}/{owner}/Methods/{member}");
191
196
  pathVariants.Add($"/{c}/{owner}/Fields/{member}");
192
197
  }
198
+ pathVariants.Add($"/Enums/{owner}/EnumValues/{member}");
199
+ // "Form.DataSource.method": a form data source's method.
200
+ var ownerDot = owner.IndexOf('.');
201
+ if (ownerDot > 0 && owner.IndexOf('.', ownerDot + 1) < 0)
202
+ pathVariants.Add($"/Forms/{owner.Substring(0, ownerDot)}/DataSources/{owner.Substring(ownerDot + 1)}/Methods/{member}");
193
203
  }
194
204
  else
195
205
  {
196
206
  // Bare name — we do not know which AOT type it is, so try every container
197
- // that can be the TARGET of a reference. All of these were verified against a
198
- // live DYNAMICSXREFDB: the target convention is plural + leading slash, even
199
- // though SOURCE paths for declarative metadata use the singular, slash-free
200
- // form ("EdtString/Foo?HelpText") that parseLabelSource() on the TS side
201
- // handles. In particular an EDT is "/Edts/<name>" — NOT "/EdtString/<name>":
202
- // the concrete subtype appears only in source paths.
207
+ // that can be the TARGET of a reference. A target is stored in one of TWO
208
+ // shapes, depending on which provider wrote the reference:
209
+ //
210
+ // X++ code (provider Xppc.exe): plural + leading slash — "/Tables/<name>",
211
+ // "/Edts/<name>", children "/Tables/<name>/Fields/<f>", ".../Methods/<m>".
212
+ // Declarative metadata (provider Metadata): singular, NO leading slash, and
213
+ // for an EDT its concrete subtype — "Table/<name>", "Form/<name>",
214
+ // "EdtString/<name>", children "Table/<name>/TableFieldString/<f>",
215
+ // "Table/<name>/Method/<m>". Source paths of these rows carry the referencing
216
+ // property ("Form/F/FormDataSourceRoot/<name>?Table").
217
+ //
218
+ // Only the first shape used to be queried, on the belief — stated here — that
219
+ // targets were always plural + slash. On a live DYNAMICSXREFDB (platform
220
+ // 7.0.7858, 19.5M references) the second shape holds 2.3M of them, every one
221
+ // Kind 2: a table's form data sources, relations, entity mappings and field
222
+ // bindings, and the table fields typed with an EDT. A where-used on a custom
223
+ // table returned 334 of its 785 references; on a custom EDT, 12 of 108, and
224
+ // none of the fields using it.
203
225
  //
204
226
  // Edts/Maps/Reports/MenuItem* were missing here, so a where-used on any of
205
227
  // them returned zero rows and the TS caller silently degraded to its
@@ -217,6 +239,17 @@ namespace D365MetadataBridge.Services
217
239
  }
218
240
  }
219
241
 
242
+ // Every X++-shaped target also exists in the metadata shape; query both,
243
+ // whichever way the target was given. A table field or enum value may also come
244
+ // from an extension, which is matched by pattern (see AddExtensionMembers).
245
+ var extensionPatterns = new List<string>();
246
+ foreach (var p in pathVariants.ToList())
247
+ {
248
+ AddMetadataTwins(p, pathVariants);
249
+ AddExtensionMembers(p, extensionPatterns);
250
+ }
251
+ pathVariants = pathVariants.Distinct(StringComparer.Ordinal).ToList();
252
+
220
253
  // Also add sub-paths (methods, fields) so we catch method-level references.
221
254
  // A member-qualified target already points at an exact leaf path, so adding
222
255
  // "/%" children would wrongly pull in unrelated nested references — skip it.
@@ -241,31 +274,52 @@ namespace D365MetadataBridge.Services
241
274
  allParams.Add(($"@P{i}", pathVariants[i]));
242
275
  }
243
276
  var likeConditions = new List<string>();
244
- for (int i = 0; i < extraPaths.Count; i++)
277
+ var likePatterns = extraPaths.Concat(extensionPatterns).ToList();
278
+ for (int i = 0; i < likePatterns.Count; i++)
245
279
  {
246
280
  var pname = $"@L{i}";
247
281
  likeConditions.Add($"tgt.Path LIKE {pname}");
248
- allParams.Add((pname, extraPaths[i]));
282
+ allParams.Add((pname, likePatterns[i]));
249
283
  }
250
284
 
251
285
  var whereClause = $"tgt.Path IN ({string.Join(",", paramNames)})";
252
286
  if (likeConditions.Count > 0)
253
287
  whereClause += $" OR {string.Join(" OR ", likeConditions)}";
254
288
 
289
+ // Rows are capped PER SHAPE and the totals counted separately. With one cap for
290
+ // both, rows sorted by source path put every "/Classes/…" code row before any
291
+ // "Form/…" metadata row, so a table with 500 code references (CustTable)
292
+ // returned no metadata at all — the very rows this lookup exists to add. The
293
+ // candidate names are resolved once: the LIKEs against Names are the costly
294
+ // part, the joins on [References].TargetId are indexed. The totals join the
295
+ // source name exactly as the rows do: [References] keeps rows whose SourceId is
296
+ // no longer in Names (77 of the 93 references to one table field on a live
297
+ // database), and counting those made the rows look like a sample of a total
298
+ // nobody could list.
299
+ string ShapeRows(string shape) => $@"
300
+ SELECT * FROM (
301
+ SELECT TOP ({RowsPerShape})
302
+ src.Path AS SourcePath, t.Path AS TargetPath, sm.Module AS SourceModule,
303
+ r.Kind, r.Line, r.[Column]
304
+ FROM #xrefTargets t
305
+ INNER JOIN [References] r ON r.TargetId = t.Id
306
+ INNER JOIN dbo.Names src ON src.Id = r.SourceId
307
+ LEFT JOIN dbo.Modules sm ON sm.Id = src.ModuleId
308
+ WHERE {shape}
309
+ ORDER BY src.Path, r.Line) AS shapeRows";
255
310
  var query = $@"
256
- SELECT TOP 500
257
- src.Path AS SourcePath,
258
- tgt.Path AS TargetPath,
259
- sm.Module AS SourceModule,
260
- r.Kind,
261
- r.Line,
262
- r.[Column]
263
- FROM [References] r
264
- INNER JOIN dbo.Names tgt ON tgt.Id = r.TargetId
265
- INNER JOIN dbo.Names src ON src.Id = r.SourceId
266
- LEFT JOIN dbo.Modules sm ON sm.Id = src.ModuleId
267
- WHERE ({whereClause})
268
- ORDER BY src.Path, r.Line";
311
+ SELECT tgt.Id, tgt.Path INTO #xrefTargets FROM dbo.Names tgt WHERE ({whereClause});
312
+ SELECT SourcePath, TargetPath, SourceModule, Kind, Line, [Column] FROM (
313
+ {ShapeRows("t.Path LIKE N'/%'")}
314
+ UNION ALL
315
+ {ShapeRows("t.Path NOT LIKE N'/%'")}
316
+ ) AS rows
317
+ ORDER BY CASE WHEN TargetPath LIKE N'/%' THEN 0 ELSE 1 END, SourcePath, Line;
318
+ SELECT COUNT(*), SUM(CASE WHEN t.Path LIKE N'/%' THEN 0 ELSE 1 END)
319
+ FROM #xrefTargets t INNER JOIN [References] r ON r.TargetId = t.Id
320
+ INNER JOIN dbo.Names src ON src.Id = r.SourceId;
321
+ DROP TABLE #xrefTargets;";
322
+ int total = 0, metadataTotal = 0;
269
323
 
270
324
  try
271
325
  {
@@ -300,6 +354,11 @@ namespace D365MetadataBridge.Services
300
354
  CallerMethod = srcSeg == "Methods" ? srcSegName : null,
301
355
  });
302
356
  }
357
+ if (reader.NextResult() && reader.Read())
358
+ {
359
+ total = reader.IsDBNull(0) ? 0 : reader.GetInt32(0);
360
+ metadataTotal = reader.IsDBNull(1) ? 0 : reader.GetInt32(1);
361
+ }
303
362
  }
304
363
  }
305
364
  }
@@ -309,7 +368,153 @@ namespace D365MetadataBridge.Services
309
368
  throw QueryFailed("findReferences", objectPath, ex);
310
369
  }
311
370
 
312
- return new { objectPath, count = references.Count, references };
371
+ // count: rows returned; total / metadataTotal: every matching reference.
372
+ return new { objectPath, count = references.Count, total, metadataTotal, references };
373
+ }
374
+
375
+ /// <summary>Rows returned per target shape (X++ code, declarative metadata).</summary>
376
+ private const int RowsPerShape = 500;
377
+
378
+ /// <summary>
379
+ /// The singular metadata type names a plural X++ container is stored under, with
380
+ /// every EDT subtype found as a target in a live DYNAMICSXREFDB.
381
+ /// </summary>
382
+ private static readonly Dictionary<string, string[]> MetadataTypes = new Dictionary<string, string[]>(StringComparer.Ordinal)
383
+ {
384
+ ["Tables"] = new[] { "Table" },
385
+ ["Classes"] = new[] { "Class" },
386
+ ["Enums"] = new[] { "Enum" },
387
+ ["Views"] = new[] { "View" },
388
+ ["DataEntityViews"] = new[] { "DataEntityView" },
389
+ ["Queries"] = new[] { "QuerySimple", "QueryComposite" },
390
+ ["Forms"] = new[] { "Form" },
391
+ ["Maps"] = new[] { "Map" },
392
+ ["Reports"] = new[] { "Report" },
393
+ ["MenuItemDisplays"] = new[] { "MenuItemDisplay" },
394
+ ["MenuItemActions"] = new[] { "MenuItemAction" },
395
+ ["MenuItemOutputs"] = new[] { "MenuItemOutput" },
396
+ ["Edts"] = new[]
397
+ {
398
+ "EdtString", "EdtReal", "EdtEnum", "EdtInt64", "EdtDate", "EdtInt", "EdtUtcDateTime",
399
+ "EdtContainer", "EdtGuid", "EdtTime",
400
+ },
401
+ };
402
+
403
+ /// <summary>
404
+ /// The segment a field is stored under in the metadata shape, per container — it
405
+ /// names the field's type, so there is one per type. Every segment found as a
406
+ /// target in a live DYNAMICSXREFDB. Listed rather than matched with
407
+ /// "TableField%": in LIKE "%" also crosses "/", so "Table/T/TableField%/Name"
408
+ /// matched the field group "Table/T/TableFieldGroup/Name" as well — and a table
409
+ /// with a field and a field group of the same name is common
410
+ /// (AccountingDistributionTemplate.Name).
411
+ /// </summary>
412
+ private static readonly Dictionary<string, string[]> MetadataFieldSegments = new Dictionary<string, string[]>(StringComparer.Ordinal)
413
+ {
414
+ ["Tables"] = new[]
415
+ {
416
+ "TableFieldString", "TableFieldEnum", "TableFieldReal", "TableFieldInt64", "TableFieldInt",
417
+ "TableFieldDate", "TableFieldUtcDateTime", "TableFieldGuid", "TableFieldContainer", "TableFieldTime",
418
+ },
419
+ ["Maps"] = new[]
420
+ {
421
+ "MapFieldString", "MapFieldEnum", "MapFieldReal", "MapFieldInt64", "MapFieldInt",
422
+ "MapFieldDate", "MapFieldUtcDateTime", "MapFieldGuid", "MapFieldContainer", "MapFieldTime",
423
+ },
424
+ ["Views"] = new[]
425
+ {
426
+ "ViewFieldBound", "ViewFieldComputedString", "ViewFieldComputedEnum", "ViewFieldComputedReal",
427
+ "ViewFieldComputedInt64", "ViewFieldComputedInt", "ViewFieldComputedDate", "ViewFieldComputedUtcDateTime",
428
+ },
429
+ ["DataEntityViews"] = new[]
430
+ {
431
+ "DataEntityViewMappedField", "DataEntityViewUnmappedFieldString", "DataEntityViewUnmappedFieldEnum",
432
+ "DataEntityViewUnmappedFieldReal", "DataEntityViewUnmappedFieldInt64", "DataEntityViewUnmappedFieldInt",
433
+ "DataEntityViewUnmappedFieldDate", "DataEntityViewUnmappedFieldUtcDateTime",
434
+ "DataEntityViewUnmappedFieldGuid", "DataEntityViewUnmappedFieldContainer",
435
+ },
436
+ };
437
+
438
+ /// <summary>
439
+ /// Add the metadata twin of an X++-shaped target path: "/Tables/T" → "Table/T",
440
+ /// "/Edts/E" → "EdtString/E", … ; for a member, "/Views/V/Methods/m" →
441
+ /// "View/V/Method/m" (tables, classes, forms, views, data entities, maps) and
442
+ /// "/Tables/T/Fields/f" → "Table/T/TableFieldString/f", "Table/T/TableFieldEnum/f", …
443
+ /// (tables, maps, views, data entities); "/Tables/T/TableIndexs/i" → "Table/T/TableIndex/i",
444
+ /// "/Tables/T/TableFieldGroups/g" → "Table/T/TableFieldGroup/g"; a form data source's
445
+ /// method "/Forms/F/DataSources/DS/Methods/m" → "Form/F/FormDataSourceRoot/DS/Method/m".
446
+ /// Metadata-shaped and unknown paths add nothing.
447
+ /// </summary>
448
+ private static void AddMetadataTwins(string xppPath, List<string> exact)
449
+ {
450
+ if (!xppPath.StartsWith("/")) return;
451
+ var parts = xppPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
452
+ if (parts.Length < 2 || !MetadataTypes.TryGetValue(parts[0], out var types)) return;
453
+ if (parts.Length == 2)
454
+ {
455
+ foreach (var t in types) exact.Add($"{t}/{parts[1]}");
456
+ }
457
+ else if (parts.Length == 4)
458
+ {
459
+ if (parts[2] == "Methods")
460
+ {
461
+ foreach (var t in types) exact.Add($"{t}/{parts[1]}/Method/{parts[3]}");
462
+ }
463
+ else if (parts[2] == "Fields" && MetadataFieldSegments.TryGetValue(parts[0], out var segments))
464
+ {
465
+ foreach (var t in types)
466
+ foreach (var s in segments) exact.Add($"{t}/{parts[1]}/{s}/{parts[3]}");
467
+ }
468
+ else if (parts[2] == "EnumValues" && parts[0] == "Enums")
469
+ {
470
+ exact.Add($"Enum/{parts[1]}/EnumValue/{parts[3]}");
471
+ }
472
+ // X++ spells these "TableIndexs" / "TableFieldGroups"; metadata singular.
473
+ else if (parts[2] == "TableIndexs")
474
+ {
475
+ foreach (var t in types) exact.Add($"{t}/{parts[1]}/TableIndex/{parts[3]}");
476
+ }
477
+ else if (parts[2] == "TableFieldGroups")
478
+ {
479
+ foreach (var t in types) exact.Add($"{t}/{parts[1]}/TableFieldGroup/{parts[3]}");
480
+ }
481
+ }
482
+ else if (parts.Length == 6 && parts[0] == "Forms" && parts[2] == "DataSources" && parts[4] == "Methods")
483
+ {
484
+ // A form data source's method: "/Forms/F/DataSources/DS/Methods/m" and
485
+ // "Form/F/FormDataSourceRoot/DS/Method/m". Every data source is stored at the
486
+ // root, joined ones included, under its own name (not its table's).
487
+ exact.Add($"Form/{parts[1]}/FormDataSourceRoot/{parts[3]}/Method/{parts[5]}");
488
+ }
489
+ }
490
+
491
+ /// <summary>
492
+ /// A field a table extension adds, and a value an enum extension adds, are stored
493
+ /// under the extension only, in both shapes: "/TableExtensions/T.Ext/Fields/f" and
494
+ /// "TableExtension/T.Ext/TableFieldString/f", "/EnumExtensions/E.Ext/EnumValues/v"
495
+ /// and "EnumExtension/E.Ext/EnumValue/v". On a live DYNAMICSXREFDB that is 17,788 and
496
+ /// 8,769 references, and a where-used on "PurchLine.&lt;added field&gt;" found none of them:
497
+ /// "/Tables/PurchLine/Fields/&lt;f&gt;" has no references at all. An extension is always
498
+ /// named "&lt;base&gt;.&lt;suffix&gt;" (every one of the 1,104 on that database), so the
499
+ /// suffix is the only wildcard; the member segment after it is exact.
500
+ /// </summary>
501
+ private static void AddExtensionMembers(string xppPath, List<string> patterns)
502
+ {
503
+ var parts = xppPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
504
+ if (!xppPath.StartsWith("/") || parts.Length != 4) return;
505
+ var baseName = EscapeLike(parts[1]);
506
+ var member = EscapeLike(parts[3]);
507
+ if (parts[0] == "Tables" && parts[2] == "Fields")
508
+ {
509
+ patterns.Add($"/TableExtensions/{baseName}.%/Fields/{member}");
510
+ foreach (var s in MetadataFieldSegments["Tables"])
511
+ patterns.Add($"TableExtension/{baseName}.%/{s}/{member}");
512
+ }
513
+ else if (parts[0] == "Enums" && parts[2] == "EnumValues")
514
+ {
515
+ patterns.Add($"/EnumExtensions/{baseName}.%/EnumValues/{member}");
516
+ patterns.Add($"EnumExtension/{baseName}.%/EnumValue/{member}");
517
+ }
313
518
  }
314
519
 
315
520
  // ============================================================
@@ -4328,8 +4328,14 @@ namespace D365MetadataBridge.Services
4328
4328
  }
4329
4329
  if (!string.IsNullOrEmpty(label))
4330
4330
  {
4331
- try { ctrl.Label = label; }
4332
- catch { unsupportedProperties.Add("label"); }
4331
+ // The caption is not always "Label": field controls carry Label, buttons
4332
+ // and menu buttons carry Text, groups and tab pages carry Caption. Always
4333
+ // assigning Label left every Button without a caption (#1047).
4334
+ var captionProperty = new[] { "Label", "Text", "Caption" }
4335
+ .Select(n => ctrlType.GetProperty(n))
4336
+ .FirstOrDefault(p => p != null && p.CanWrite && p.PropertyType == typeof(string));
4337
+ if (captionProperty != null) captionProperty.SetValue(ctrl, label);
4338
+ else unsupportedProperties.Add("label");
4333
4339
  }
4334
4340
  return ctrl;
4335
4341
  }
@@ -536,6 +536,12 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
536
536
  // transient failure as an authoritative "0 references".
537
537
  const merged = [];
538
538
  let errored = false;
539
+ // The bridge returns at most XREF_ROW_CAP rows per target shape and candidate,
540
+ // with the exact totals alongside; an older bridge returns only the rows.
541
+ let capped = false;
542
+ let exact = true;
543
+ let exactTotal = 0;
544
+ let exactMetadata = 0;
539
545
  for (const t of targets) {
540
546
  try {
541
547
  const r = await bridge.findReferences(t);
@@ -543,6 +549,15 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
543
549
  errored = true;
544
550
  if (r?.references?.length)
545
551
  merged.push(...r.references);
552
+ if (typeof r?.total === 'number') {
553
+ exactTotal += r.total;
554
+ exactMetadata += r.metadataTotal ?? 0;
555
+ }
556
+ else {
557
+ exact = false;
558
+ if ((r?.references?.length ?? 0) >= XREF_ROW_CAP)
559
+ capped = true;
560
+ }
546
561
  }
547
562
  catch (e) {
548
563
  errored = true;
@@ -562,25 +577,36 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
562
577
  }
563
578
  {
564
579
  const refs = { count: merged.length, references: merged };
580
+ const returnedMetadata = merged.filter(r => isMetadataSource(r.sourcePath)).length;
581
+ const total = exact ? exactTotal : refs.count;
582
+ const metadataTotal = exact ? exactMetadata : returnedMetadata;
583
+ const sampled = exact && refs.count < exactTotal;
565
584
  let out = `# References to \`${label}\`\n\n`;
566
- out += `**Total:** ${refs.count} reference(s) found\n`;
567
- out += `_Source: C# bridge (DYNAMICSXREFDB)_\n\n`;
585
+ out += `**Total:** ${total}${capped ? '+' : ''} reference(s) found${sampled ? ` (showing ${refs.count})` : ''}\n`;
586
+ out += `_Source: C# bridge (DYNAMICSXREFDB) — X++ code and declarative metadata references_\n\n`;
587
+ if (sampled) {
588
+ out += `> ℹ️ The bridge returns up to ${XREF_ROW_CAP} rows per lookup for code and for metadata: the totals are exact, ` +
589
+ `the rows below are a sample. Narrow the target (e.g. \`Owner.member\`) for a complete list.\n\n`;
590
+ }
591
+ else if (capped) {
592
+ out += `> ⚠️ At least one lookup reached the bridge's limit of ${XREF_ROW_CAP} rows, so the real total is higher. ` +
593
+ `Narrow the target (e.g. \`Owner.member\`) for a complete list.\n\n`;
594
+ }
568
595
  // Group by reference type for summary
569
596
  const byType = new Map();
570
597
  const topCallers = new Map();
571
598
  for (const r of refs.references) {
572
599
  const rt = r.referenceType || 'reference';
573
600
  byType.set(rt, (byType.get(rt) || 0) + 1);
574
- const caller = r.callerClass
575
- ? (r.callerMethod ? `${r.callerClass}.${r.callerMethod}` : r.callerClass)
576
- : r.sourcePath;
601
+ const caller = referenceCaller(r);
577
602
  topCallers.set(caller, (topCallers.get(caller) || 0) + 1);
578
603
  }
579
604
  // Summary by type
580
- out += `## 📊 Summary by Type\n\n`;
605
+ out += `## 📊 Summary by Type${sampled ? ' (in the rows returned)' : ''}\n\n`;
581
606
  for (const [type, count] of byType) {
582
607
  out += `- **${type}**: ${count} reference(s)\n`;
583
608
  }
609
+ out += `- From X++ code: ${total - metadataTotal} · from declarative metadata: ${metadataTotal}\n`;
584
610
  out += `\n`;
585
611
  // Top callers
586
612
  const sortedCallers = [...topCallers.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10);
@@ -592,28 +618,63 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
592
618
  out += `\n`;
593
619
  }
594
620
  // Detailed references
621
+ // Code and metadata each get a share of `limit`, so neither can crowd the
622
+ // other out of the list — rows come back code first, and a response trimmed
623
+ // to its first rows used to show code only.
595
624
  out += `## 📍 References\n\n`;
596
- const visible = refs.references.slice(0, limit);
597
- for (const r of visible) {
625
+ const metadataRows = refs.references.filter(r => isMetadataSource(r.sourcePath));
626
+ const codeRows = refs.references.filter(r => !isMetadataSource(r.sourcePath));
627
+ let codeShare = Math.min(codeRows.length, Math.ceil(limit / 2));
628
+ const metadataShare = Math.min(metadataRows.length, limit - codeShare);
629
+ codeShare = Math.min(codeRows.length, limit - metadataShare);
630
+ const renderRow = (r) => {
598
631
  const module = r.sourceModule ? ` [${r.sourceModule}]` : '';
599
632
  const loc = r.line > 0 ? `:${r.line}` : '';
600
633
  const refType = r.referenceType ? ` (${r.referenceType})` : '';
601
- const caller = r.callerClass
602
- ? (r.callerMethod ? `${r.callerClass}.${r.callerMethod}` : r.callerClass)
603
- : null;
604
- if (caller) {
605
- out += `- **${caller}**${loc}${module}${refType}\n`;
606
- }
607
- else {
608
- out += `- **${r.sourcePath}**${loc}${module}${refType}\n`;
609
- }
634
+ return `- **${referenceCaller(r)}**${loc}${module}${refType}\n`;
635
+ };
636
+ const groups = [
637
+ ['From declarative metadata', metadataRows, metadataShare, metadataTotal],
638
+ ['From X++ code', codeRows, codeShare, total - metadataTotal],
639
+ ];
640
+ for (const [heading, rows, share, groupTotal] of groups) {
641
+ if (rows.length === 0)
642
+ continue;
643
+ out += `### ${heading} (${share < groupTotal ? `${share} of ${groupTotal}` : share})\n\n`;
644
+ for (const r of rows.slice(0, share))
645
+ out += renderRow(r);
646
+ out += `\n`;
610
647
  }
611
648
  if (refs.count > limit) {
612
- out += `\n> ⚠️ Showing first ${limit} of ${refs.count} references.\n`;
649
+ out += `> ⚠️ Showing ${limit} of the ${refs.count} rows returned. Raise \`limit\` to see more.\n`;
613
650
  }
614
651
  return { status: 'ok', result: { content: [{ type: 'text', text: out }] } };
615
652
  }
616
653
  }
654
+ /** Rows the C# bridge returns per candidate path at most (its SELECT TOP 500). */
655
+ const XREF_ROW_CAP = 500;
656
+ /**
657
+ * Declarative metadata references are stored with a singular, slash-free source
658
+ * path carrying the referencing property ("Form/F/FormDataSourceRoot/T?Table");
659
+ * X++ code references with a plural, slash-prefixed one ("/Classes/C/Methods/m").
660
+ */
661
+ function isMetadataSource(sourcePath) {
662
+ return !!sourcePath && !sourcePath.startsWith('/');
663
+ }
664
+ /**
665
+ * Who references the target, for a reader: "Class.method" for code, and for
666
+ * metadata the object type, object and "member › property" (the same reading
667
+ * label where-used gives) — "Form MyJournalForm › MyCountingTrans › Table".
668
+ */
669
+ function referenceCaller(r) {
670
+ if (isMetadataSource(r.sourcePath)) {
671
+ const { type, objectName, detail } = parseLabelSource(r.sourcePath);
672
+ return `${type} ${objectName}${detail ? ` › ${detail}` : ''}`;
673
+ }
674
+ if (r.callerClass)
675
+ return r.callerMethod ? `${r.callerClass}.${r.callerMethod}` : r.callerClass;
676
+ return r.sourcePath;
677
+ }
617
678
  // LABEL REFERENCES (formatting)
618
679
  /**
619
680
  * Friendly display name for an xref source-container segment. Handles both xref
@@ -272,7 +272,11 @@ export interface BridgeReportDesign {
272
272
  }
273
273
  export interface BridgeReferenceResult {
274
274
  objectPath: string;
275
+ /** Rows returned — capped per target shape (X++ code, declarative metadata). */
275
276
  count: number;
277
+ /** Every matching reference, and how many of them are declarative metadata. Absent from older bridges. */
278
+ total?: number;
279
+ metadataTotal?: number;
276
280
  references: BridgeReferenceInfo[];
277
281
  /** Set by the C# bridge when the xref query failed in-band (e.g. SQL error) — count is 0 but this is NOT an authoritative "no references". */
278
282
  error?: string;
@@ -1,3 +1,4 @@
1
+ import { type SettingsStore } from '../settingsStore.js';
1
2
  type Severity = 'ok' | 'warn' | 'fail' | 'info';
2
3
  interface CheckResult {
3
4
  severity: Severity;
@@ -64,6 +65,13 @@ export declare function missingPathFix(setting: import('../../config/settings.js
64
65
  * naming wins (it does not) and offered the fix they had already applied (#893).
65
66
  */
66
67
  export declare function checkPrefixResolution(configuredPrefix: string, modelName: string | null, modelObjectNames: string[], label: string, pinned?: boolean): CheckResult[];
68
+ /**
69
+ * A traditional VM with no cross-reference database configured. Its XPP config
70
+ * does not exist, so nothing else names DYNAMICSXREFDB, and find_references
71
+ * silently answers from a name-based search that misses metadata references
72
+ * (relations, form data sources, fields using an EDT). Null when configured.
73
+ */
74
+ export declare function checkXrefConfigured(store: SettingsStore): CheckResult | null;
67
75
  export declare function doctorCommand(): Promise<void>;
68
76
  export {};
69
77
  //# sourceMappingURL=doctor.d.ts.map
@@ -445,6 +445,25 @@ async function probeHealth(port, label) {
445
445
  return { severity: 'info', message: `${label}: not running on port ${port} (fine unless you expect an HTTP server)` };
446
446
  }
447
447
  }
448
+ /**
449
+ * A traditional VM with no cross-reference database configured. Its XPP config
450
+ * does not exist, so nothing else names DYNAMICSXREFDB, and find_references
451
+ * silently answers from a name-based search that misses metadata references
452
+ * (relations, form data sources, fields using an EDT). Null when configured.
453
+ */
454
+ export function checkXrefConfigured(store) {
455
+ // Same precedence the server applies: the real environment (an .mcp.json
456
+ // `env` block) outranks the config file.
457
+ const name = (process.env.D365FO_XREF_DB_NAME?.trim()
458
+ || String(readSetting(store, settingByPath('bridge.xrefDbName')) ?? '').trim());
459
+ if (name)
460
+ return null;
461
+ return {
462
+ severity: 'info',
463
+ message: 'Cross-reference database not configured — find_references uses a name-based search instead of DYNAMICSXREFDB',
464
+ fix: 'set bridge.xrefDbName to DYNAMICSXREFDB (and bridge.xrefDbServer if it is not localhost), then restart the server',
465
+ };
466
+ }
448
467
  export async function doctorCommand() {
449
468
  p.intro('d365fo-mcp doctor');
450
469
  let failures = 0;
@@ -527,6 +546,11 @@ export async function doctorCommand() {
527
546
  }
528
547
  else {
529
548
  emit({ severity: 'info', message: 'No UDE XPPConfig directory — traditional VM or UDE tools not installed' });
549
+ // Only UDE's XPP config names the cross-reference database; a traditional
550
+ // VM has to configure it, or find_references never uses it.
551
+ const xref = checkXrefConfigured(root.store);
552
+ if (xref)
553
+ emit(xref);
530
554
  }
531
555
  }
532
556
  else {
@@ -729,6 +729,28 @@ export const SETTINGS = [
729
729
  label: 'Bridge diagnostic log',
730
730
  description: 'Absolute path the C# bridge appends its own diagnostics to.',
731
731
  },
732
+ {
733
+ path: 'bridge.xrefDbServer',
734
+ env: 'D365FO_XREF_DB_SERVER',
735
+ section: 'bridge',
736
+ tier: 'advanced',
737
+ type: 'string',
738
+ label: 'Cross-reference database server',
739
+ description: 'SQL Server holding the X++ cross-reference database that find_references reads through the bridge. ' +
740
+ 'Leave empty to use the XPP config (UDE), or localhost when only the database name is set. ' +
741
+ 'Takes precedence over the XPP config.',
742
+ },
743
+ {
744
+ path: 'bridge.xrefDbName',
745
+ env: 'D365FO_XREF_DB_NAME',
746
+ section: 'bridge',
747
+ tier: 'advanced',
748
+ type: 'string',
749
+ label: 'Cross-reference database name',
750
+ description: 'Name of the X++ cross-reference database — DYNAMICSXREFDB on a traditional VM, where no XPP config ' +
751
+ 'names it and find_references otherwise falls back to a name-based search. Leave empty to use the ' +
752
+ 'XPP config (UDE). Takes precedence over the XPP config.',
753
+ },
732
754
  {
733
755
  path: 'bridge.fsScanTimeoutMs',
734
756
  env: 'D365FO_FS_SCAN_TIMEOUT_MS',
package/dist/index.js CHANGED
@@ -495,7 +495,7 @@ async function initializeBridge(targetContext) {
495
495
  packagesPath = pldPath;
496
496
  }
497
497
  }
498
- // Pass xref connection details for UDE environments
498
+ // Pass xref connection details: configured (traditional VM) or the XPP config (UDE)
499
499
  const xrefServer = await configMgr.getXrefDbServer() ?? undefined;
500
500
  const xrefDatabase = await configMgr.getXrefDbName() ?? undefined;
501
501
  const bridge = await createBridgeClient({