d365fo-mcp 1.22.0 → 1.23.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 (93) hide show
  1. package/dist/bridge/bridgeAdapter.d.ts +5 -4
  2. package/dist/bridge/bridgeAdapter.js +88 -30
  3. package/dist/bridge/bridgeTypes.d.ts +13 -0
  4. package/dist/cli/commands/doctor.d.ts +5 -0
  5. package/dist/cli/commands/doctor.js +34 -0
  6. package/dist/config/settings.js +83 -0
  7. package/dist/index.js +28 -1
  8. package/dist/metadata/symbolIndex.d.ts +81 -1
  9. package/dist/metadata/symbolIndex.js +234 -21
  10. package/dist/metadata/types.d.ts +13 -0
  11. package/dist/metadata/xmlParser.d.ts +21 -0
  12. package/dist/metadata/xmlParser.js +47 -2
  13. package/dist/prompts/systemInstructions.d.ts +4 -2
  14. package/dist/prompts/systemInstructions.js +10 -5
  15. package/dist/scripts/build-database.js +287 -16
  16. package/dist/scripts/build-fts.js +287 -16
  17. package/dist/scripts/extract-metadata.js +125 -16
  18. package/dist/scripts/startupIndexWorker.js +224 -16
  19. package/dist/server/mcpServer.js +3 -0
  20. package/dist/server/serverMode.d.ts +5 -0
  21. package/dist/server/serverMode.js +6 -0
  22. package/dist/server/toolSchemas/d365foFile.js +1 -1
  23. package/dist/server/toolSchemas/index.d.ts +8 -1
  24. package/dist/server/toolSchemas/updateSymbolIndex.d.ts +4 -0
  25. package/dist/server/toolSchemas/updateSymbolIndex.js +7 -4
  26. package/dist/server/toolSchemas/validateObjectNaming.d.ts +4 -1
  27. package/dist/server/toolSchemas/validateObjectNaming.js +7 -4
  28. package/dist/tools/analysis/exactLabelLookup.d.ts +35 -0
  29. package/dist/tools/analysis/exactLabelLookup.js +187 -0
  30. package/dist/tools/analysis/findReferences.d.ts +2 -1
  31. package/dist/tools/analysis/findReferences.js +129 -22
  32. package/dist/tools/analysis/search.js +13 -3
  33. package/dist/tools/analysis/validateObjectNaming.js +16 -6
  34. package/dist/tools/analysis/validateXpp.js +56 -6
  35. package/dist/tools/knowledge/analyzeExtensionPoints.js +4 -2
  36. package/dist/tools/knowledge/apiUsagePatterns.js +2 -1
  37. package/dist/tools/knowledge/findCocExtensions.js +19 -12
  38. package/dist/tools/knowledge/findEventHandlers.js +2 -1
  39. package/dist/tools/knowledge/xppKnowledge.js +121 -22
  40. package/dist/tools/labels.js +10 -0
  41. package/dist/tools/prepare/prepareChange.js +8 -3
  42. package/dist/tools/prepare/prepareCreate.js +6 -1
  43. package/dist/tools/readers/getWorkspaceInfo.js +46 -7
  44. package/dist/tools/readers/mapInfo.js +35 -29
  45. package/dist/tools/readers/objectXml.js +11 -14
  46. package/dist/tools/readers/queryInfo.js +13 -4
  47. package/dist/tools/readers/reportInfo.js +5 -4
  48. package/dist/tools/readers/viewInfo.d.ts +5 -3
  49. package/dist/tools/readers/viewInfo.js +81 -30
  50. package/dist/tools/sdlc/modelReindex.d.ts +34 -0
  51. package/dist/tools/sdlc/modelReindex.js +194 -0
  52. package/dist/tools/sdlc/updateSymbolIndex.js +38 -9
  53. package/dist/tools/smart/codeGen.js +47 -13
  54. package/dist/tools/specs/d365foFileOpSpecs.js +28 -1
  55. package/dist/tools/specs/generateObjectOpSpecs.js +6 -1
  56. package/dist/tools/specs/labelsOpSpecs.js +28 -1
  57. package/dist/tools/specs/opSpecs.js +2 -2
  58. package/dist/tools/write/createD365File.js +22 -4
  59. package/dist/tools/write/createLabel.d.ts +4 -0
  60. package/dist/tools/write/createLabel.js +13 -10
  61. package/dist/tools/write/directXmlWriters.d.ts +44 -3
  62. package/dist/tools/write/directXmlWriters.js +245 -33
  63. package/dist/tools/write/modifyD365File.d.ts +4 -0
  64. package/dist/tools/write/modifyD365File.js +21 -3
  65. package/dist/tools/xml/menuExtensionXml.d.ts +146 -0
  66. package/dist/tools/xml/menuExtensionXml.js +312 -0
  67. package/dist/tools/xml/menuXml.d.ts +27 -0
  68. package/dist/tools/xml/menuXml.js +84 -0
  69. package/dist/tools/xml/xmlTemplateGenerator.js +11 -1
  70. package/dist/types/context.d.ts +7 -0
  71. package/dist/utils/baseObjectXml.js +79 -2
  72. package/dist/utils/crossModelWriteGuard.js +11 -0
  73. package/dist/utils/extensionNameFormat.d.ts +108 -0
  74. package/dist/utils/extensionNameFormat.js +243 -0
  75. package/dist/utils/indexStaleness.js +5 -2
  76. package/dist/utils/indexedXmlLookup.d.ts +36 -12
  77. package/dist/utils/indexedXmlLookup.js +43 -15
  78. package/dist/utils/labelText.d.ts +18 -0
  79. package/dist/utils/labelText.js +20 -0
  80. package/dist/utils/modelClassifier.js +6 -0
  81. package/dist/utils/modelPrefixInference.js +5 -1
  82. package/dist/utils/objectNaming.d.ts +54 -0
  83. package/dist/utils/objectNaming.js +103 -0
  84. package/dist/utils/objectNamingRules.d.ts +7 -0
  85. package/dist/utils/objectNamingRules.js +120 -2
  86. package/dist/workspace/projectFile.js +10 -3
  87. package/dist/xref/sqliteXrefProvider.d.ts +188 -0
  88. package/dist/xref/sqliteXrefProvider.js +737 -0
  89. package/dist/xref/xrefPaths.d.ts +99 -0
  90. package/dist/xref/xrefPaths.js +392 -0
  91. package/dist/xref/xrefSource.d.ts +66 -0
  92. package/dist/xref/xrefSource.js +98 -0
  93. package/package.json +2 -1
@@ -23,6 +23,7 @@
23
23
  import type { BridgeClient } from './bridgeClient.js';
24
24
  import type { BridgeAttempt } from './bridgeFailure.js';
25
25
  import type { BridgeCompletionResult, BridgeSmartTableResult } from './bridgeTypes.js';
26
+ import { type XrefSource } from '../xref/xrefSource.js';
26
27
  /** Standard MCP tool response shape */
27
28
  export interface ToolResult {
28
29
  content: Array<{
@@ -139,7 +140,7 @@ export type BridgeReferencesOutcome = {
139
140
  } | {
140
141
  status: 'unavailable';
141
142
  };
142
- export declare function tryBridgeReferences(bridge: BridgeClient | undefined, target: string | string[], limit?: number, displayName?: string, formatAs?: 'default' | 'label'): Promise<BridgeReferencesOutcome>;
143
+ export declare function tryBridgeReferences(bridge: XrefSource | undefined, target: string | string[], limit?: number, displayName?: string, formatAs?: 'default' | 'label'): Promise<BridgeReferencesOutcome>;
143
144
  export interface BridgeSearchOptions {
144
145
  /**
145
146
  * Exact-name hits the caller already resolved from the SQLite index with an
@@ -588,9 +589,9 @@ declare function memberLine(m: {
588
589
  signature?: string;
589
590
  }): string;
590
591
  declare function formatCompletion(r: BridgeCompletionResult, prefix?: string): string;
591
- export declare function tryBridgeCocExtensions(bridge: BridgeClient | undefined, baseClassName: string, methodName?: string): Promise<ToolResult | null>;
592
- export declare function tryBridgeEventHandlers(bridge: BridgeClient | undefined, targetName: string, eventName?: string, handlerType?: string): Promise<ToolResult | null>;
593
- export declare function tryBridgeApiUsageCallers(bridge: BridgeClient | undefined, apiName: string, limit?: number): Promise<ToolResult | null>;
592
+ export declare function tryBridgeCocExtensions(bridge: XrefSource | undefined, baseClassName: string, methodName?: string): Promise<ToolResult | null>;
593
+ export declare function tryBridgeEventHandlers(bridge: XrefSource | undefined, targetName: string, eventName?: string, handlerType?: string): Promise<ToolResult | null>;
594
+ export declare function tryBridgeApiUsageCallers(bridge: XrefSource | undefined, apiName: string, limit?: number): Promise<ToolResult | null>;
594
595
  /**
595
596
  * Internals exposed for tests only. `formatCompletion` renders a member list,
596
597
  * and a member list that cannot be trusted to name its members is worse than no
@@ -31,6 +31,8 @@ import { rankCustomFirst, isExactNameMatch } from '../utils/exactMatchRanking.js
31
31
  import { COMPACT_METHODS_HINT, fullBodyHint } from '../utils/methodBodyHint.js';
32
32
  import { subscriberAccessLevelValue } from '../utils/subscriberAccessLevel.js';
33
33
  import { pageFields, fieldsHeading, fieldsFooter, createControlBudget, chargeControl, chargeSkippedSubtree, controlsFooter, } from '../utils/payloadBudget.js';
34
+ import { xrefSourceLabel, isSqliteXref } from '../xref/xrefSource.js';
35
+ import { XREF_SQLITE_COUNT_CAP } from '../xref/sqliteXrefProvider.js';
34
36
  // TABLE
35
37
  const TABLE_METHOD_PAGE_SIZE = 25;
36
38
  /**
@@ -547,6 +549,8 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
547
549
  let exact = true;
548
550
  let exactTotal = 0;
549
551
  let exactMetadata = 0;
552
+ // The SQLite provider counts up to a cap: its totals are then lower bounds.
553
+ let totalCapped = false;
550
554
  for (const t of targets) {
551
555
  try {
552
556
  const r = await bridge.findReferences(t);
@@ -554,6 +558,8 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
554
558
  errored = true;
555
559
  if (r?.references?.length)
556
560
  merged.push(...r.references);
561
+ if (r?.totalCapped)
562
+ totalCapped = true;
557
563
  if (typeof r?.total === 'number') {
558
564
  exactTotal += r.total;
559
565
  exactMetadata += r.metadataTotal ?? 0;
@@ -578,7 +584,7 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
578
584
  // properties rather than X++ code — so they get a dedicated formatter that
579
585
  // groups by source object type and surfaces the referencing property.
580
586
  if (formatAs === 'label') {
581
- return { status: 'ok', result: formatLabelReferences(merged, label, limit) };
587
+ return { status: 'ok', result: formatLabelReferences(merged, label, limit, xrefSourceLabel(bridge)) };
582
588
  }
583
589
  {
584
590
  const refs = { count: merged.length, references: merged };
@@ -586,11 +592,20 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
586
592
  const total = exact ? exactTotal : refs.count;
587
593
  const metadataTotal = exact ? exactMetadata : returnedMetadata;
588
594
  const sampled = exact && refs.count < exactTotal;
595
+ // Lower-bound marks for the SQLite cap only; a bridge's output stays as it was.
596
+ const plus = totalCapped ? '+' : '';
597
+ const who = isSqliteXref(bridge) ? 'The xref SQLite file' : 'The bridge';
589
598
  let out = `# References to \`${label}\`\n\n`;
590
- out += `**Total:** ${total}${capped ? '+' : ''} reference(s) found${sampled ? ` (showing ${refs.count})` : ''}\n`;
591
- out += `_Source: C# bridge (DYNAMICSXREFDB) — X++ code and declarative metadata references_\n\n`;
592
- if (sampled) {
593
- out += `> ℹ️ The bridge returns up to ${XREF_ROW_CAP} rows per lookup for code and for metadata: the totals are exact, ` +
599
+ out += `**Total:** ${total}${capped || totalCapped ? '+' : ''} reference(s) found${sampled ? ` (showing ${refs.count})` : ''}\n`;
600
+ out += `_Source: ${xrefSourceLabel(bridge)} — X++ code and declarative metadata references_\n\n`;
601
+ if (sampled && totalCapped) {
602
+ out += `> ℹ️ ${who} returns up to ${XREF_ROW_CAP} rows per lookup for code and for metadata and counts up to ` +
603
+ `${isSqliteXref(bridge) ? bridge.countCap : XREF_SQLITE_COUNT_CAP} references each: more exist than counted, ` +
604
+ `and the rows below are a sample. ` +
605
+ `Narrow the target (e.g. \`Owner.member\`) for a complete list.\n\n`;
606
+ }
607
+ else if (sampled) {
608
+ out += `> ℹ️ ${who} returns up to ${XREF_ROW_CAP} rows per lookup for code and for metadata: the totals are exact, ` +
594
609
  `the rows below are a sample. Narrow the target (e.g. \`Owner.member\`) for a complete list.\n\n`;
595
610
  }
596
611
  else if (capped) {
@@ -611,7 +626,7 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
611
626
  for (const [type, count] of byType) {
612
627
  out += `- **${type}**: ${count} reference(s)\n`;
613
628
  }
614
- out += `- From X++ code: ${total - metadataTotal} · from declarative metadata: ${metadataTotal}\n`;
629
+ out += `- From X++ code: ${total - metadataTotal}${plus} · from declarative metadata: ${metadataTotal}${plus}\n`;
615
630
  out += `\n`;
616
631
  // Top callers
617
632
  const sortedCallers = [...topCallers.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10);
@@ -645,7 +660,7 @@ export async function tryBridgeReferences(bridge, target, limit = 50, displayNam
645
660
  for (const [heading, rows, share, groupTotal] of groups) {
646
661
  if (rows.length === 0)
647
662
  continue;
648
- out += `### ${heading} (${share < groupTotal ? `${share} of ${groupTotal}` : share})\n\n`;
663
+ out += `### ${heading} (${share < groupTotal ? `${share} of ${groupTotal}${plus}` : share})\n\n`;
649
664
  for (const r of rows.slice(0, share))
650
665
  out += renderRow(r);
651
666
  out += `\n`;
@@ -763,7 +778,7 @@ function parseLabelSource(sourcePath) {
763
778
  * explicit — a label is typically referenced far more from metadata (form
764
779
  * captions, field/EDT labels, menu-item captions, …) than from X++ code.
765
780
  */
766
- function formatLabelReferences(references, label, limit) {
781
+ function formatLabelReferences(references, label, limit, source) {
767
782
  const parsed = references.map(r => ({
768
783
  ...parseLabelSource(r.sourcePath),
769
784
  module: r.sourceModule,
@@ -771,7 +786,7 @@ function formatLabelReferences(references, label, limit) {
771
786
  }));
772
787
  let out = `# References to label \`${label}\`\n\n`;
773
788
  out += `**Total:** ${references.length} reference(s) found\n`;
774
- out += `_Source: C# bridge (DYNAMICSXREFDB) — includes both X++ code and declarative metadata references_\n\n`;
789
+ out += `_Source: ${source} — includes both X++ code and declarative metadata references_\n\n`;
775
790
  // Summary: count by source object type (most-referenced first). This counts
776
791
  // ALL references, whereas the detail section below is capped at `limit` — so
777
792
  // each truncated group carries a "showing X of Y" marker to keep the two
@@ -1325,6 +1340,9 @@ const BRIDGE_MODIFY_OPS = new Set([
1325
1340
  'add-module-reference', 'remove-module-reference',
1326
1341
  'add-display-method', 'add-table-method',
1327
1342
  'add-field-modification', 'add-menu-item-to-menu',
1343
+ // No C# op adds a submenu: served by a direct-XML writer on a menu (already in
1344
+ // BRIDGE_MODIFY_TYPES) and, through XML_ONLY_MODIFY_PAIRS, on a menu extension.
1345
+ 'add-submenu',
1328
1346
  // No C# op exists for query ranges on entities — served entirely by a
1329
1347
  // direct-XML writer (data-entity is already in BRIDGE_MODIFY_TYPES).
1330
1348
  'add-query-range', 'remove-query-range',
@@ -1373,6 +1391,12 @@ const XML_ONLY_MODIFY_PAIRS = {
1373
1391
  // this pair the caller would get "the bridge could not resolve the object" instead
1374
1392
  // of the operation actually running.
1375
1393
  'report-design': new Set(['report']),
1394
+ // The C# AddMenuItemToMenu reads an AxMenu and cannot resolve "BaseMenu.Suffix",
1395
+ // and `menu-extension` cannot join BRIDGE_MODIFY_TYPES without claiming every other
1396
+ // op on it too. Without this pair the extension the cross-model guard sends an
1397
+ // agent to create could not be filled at all.
1398
+ 'add-menu-item-to-menu': new Set(['menu-extension']),
1399
+ 'add-submenu': new Set(['menu-extension']),
1376
1400
  };
1377
1401
  /**
1378
1402
  * Names the properties the bridge could not write, for appending to a success message.
@@ -2671,38 +2695,68 @@ export async function tryBridgeCocExtensions(bridge, baseClassName, methodName)
2671
2695
  const result = await bridge.findExtensionClasses(baseClassName);
2672
2696
  if (!result)
2673
2697
  return null;
2674
- return { content: [{ type: 'text', text: formatCocExtensions(result, methodName) }] };
2698
+ return { content: [{ type: 'text', text: formatCocExtensions(result, methodName, xrefSourceLabel(bridge)) }] };
2675
2699
  }
2676
2700
  catch (e) {
2677
2701
  recordBridgeFailure(`findExtensionClasses(${baseClassName})`, e);
2678
2702
  return null;
2679
2703
  }
2680
2704
  }
2681
- function formatCocExtensions(r, methodNameFilter) {
2705
+ function formatCocExtensions(r, methodNameFilter, source) {
2682
2706
  let out = `CoC Extensions of: ${r.baseClassName}\n`;
2683
- out += `_Source: C# bridge (DYNAMICSXREFDB)_\n\n`;
2707
+ out += `_Source: ${source}_\n\n`;
2684
2708
  if (r.count === 0) {
2685
2709
  out += `No class extensions found via cross-reference database.\n`;
2686
2710
  return out;
2687
2711
  }
2688
- // Apply method filter if specified
2689
- let filtered = r.extensions;
2690
- if (methodNameFilter) {
2691
- filtered = r.extensions.filter(ext => ext.wrappedMethods?.some(m => m.toLowerCase() === methodNameFilter.toLowerCase())
2692
- || !ext.wrappedMethods || ext.wrappedMethods.length === 0);
2693
- }
2694
2712
  // Dedupe by class name ONCE, before anything is counted. A class carries a single
2695
2713
  // [ExtensionOf] and the bridge keys its results by class name, so a duplicate cannot
2696
2714
  // reach here today — but the count and the list it introduces have to agree whatever
2697
2715
  // arrives, and skipping an entry inside the render loop after the heading above it had
2698
2716
  // already counted that entry is exactly how the two come apart.
2699
2717
  const byClassName = new Map();
2700
- for (const ext of filtered) {
2718
+ for (const ext of r.extensions) {
2701
2719
  if (!byClassName.has(ext.className))
2702
2720
  byClassName.set(ext.className, ext);
2703
2721
  }
2704
2722
  const unique = [...byClassName.values()];
2705
- out += `Found ${unique.length} extension class(es)${methodNameFilter ? ` wrapping "${methodNameFilter}"` : ''}:\n\n`;
2723
+ if (!methodNameFilter) {
2724
+ out += `Found ${unique.length} extension class(es):\n\n`;
2725
+ return out + formatCocGroups(unique);
2726
+ }
2727
+ // With a method filter, "Found N … wrapping m" counts only the classes whose wrap list names
2728
+ // m. It used to count every class with an EMPTY list as well — a leftover from when the list
2729
+ // held every base method the class called — so "Found 12 extension class(es) wrapping
2730
+ // validateWrite" listed ten classes that wrap something else. The bridge sends a list for
2731
+ // every class (WrappedMethods = new List<string>()), so empty means "wraps nothing". Those
2732
+ // classes are still worth seeing, under their own heading and count; a class with no list at
2733
+ // all (an older bridge, another source) is unknown, and is never counted as a wrapper either.
2734
+ const wanted = methodNameFilter.toLowerCase();
2735
+ const wrappers = [];
2736
+ const others = [];
2737
+ const unknown = [];
2738
+ for (const ext of unique) {
2739
+ if (!ext.wrappedMethods)
2740
+ unknown.push(ext);
2741
+ else if (ext.wrappedMethods.some(m => m.toLowerCase() === wanted))
2742
+ wrappers.push(ext);
2743
+ else
2744
+ others.push(ext);
2745
+ }
2746
+ out += `Found ${wrappers.length} extension class(es) wrapping "${methodNameFilter}":\n\n`;
2747
+ out += formatCocGroups(wrappers);
2748
+ if (others.length > 0) {
2749
+ out += `Other extension classes of ${r.baseClassName} (no wrap of "${methodNameFilter}" recorded): ${others.length}\n\n`;
2750
+ out += formatCocGroups(others);
2751
+ }
2752
+ if (unknown.length > 0) {
2753
+ out += `Extension classes of ${r.baseClassName}, wraps unknown (the source sent no wrap list): ${unknown.length}\n\n`;
2754
+ out += formatCocGroups(unknown);
2755
+ }
2756
+ return out;
2757
+ }
2758
+ function formatCocGroups(extensions) {
2759
+ let out = '';
2706
2760
  // Grouped by the element each class actually extends, never pooled into one list. A name can
2707
2761
  // denote several objects at once — "SalesTable" is a table (14 extensions) AND a form (17),
2708
2762
  // and the form's data sources, controls and data fields are each extended separately again
@@ -2710,7 +2764,7 @@ function formatCocExtensions(r, methodNameFilter) {
2710
2764
  // to write a table CoC that 34 form extensions were its concern, and hid which of the form's
2711
2765
  // NINE data sources with an `active` method was already wrapped.
2712
2766
  const groups = new Map();
2713
- for (const ext of unique) {
2767
+ for (const ext of extensions) {
2714
2768
  const key = ext.extendedElement ?? '';
2715
2769
  const bucket = groups.get(key) ?? [];
2716
2770
  bucket.push(ext);
@@ -2775,19 +2829,22 @@ export async function tryBridgeEventHandlers(bridge, targetName, eventName, hand
2775
2829
  const result = await bridge.findEventSubscribers(targetName, eventName, handlerType);
2776
2830
  if (!result)
2777
2831
  return null;
2778
- return { content: [{ type: 'text', text: formatEventHandlers(result) }] };
2832
+ return { content: [{ type: 'text', text: formatEventHandlers(result, xrefSourceLabel(bridge)) }] };
2779
2833
  }
2780
2834
  catch (e) {
2781
2835
  recordBridgeFailure(`findEventSubscribers(${targetName})`, e);
2782
2836
  return null;
2783
2837
  }
2784
2838
  }
2785
- function formatEventHandlers(r) {
2839
+ function formatEventHandlers(r, source) {
2786
2840
  let out = `Event Handlers for: ${r.targetName}\n`;
2787
- out += `_Source: C# bridge (DYNAMICSXREFDB)_\n\n`;
2841
+ out += `_Source: ${source}_\n\n`;
2842
+ const scanNote = r.scanCapped
2843
+ ? `> ⚠️ Only the first ${r.scanned ?? '?'} references to ${r.targetName} were examined: more handlers may exist.\n`
2844
+ : '';
2788
2845
  if (r.count === 0) {
2789
2846
  out += `No event handlers found via cross-reference database.\n`;
2790
- return out;
2847
+ return out + scanNote;
2791
2848
  }
2792
2849
  out += `Found ${r.count} handler(s):\n\n`;
2793
2850
  // Group by handler type
@@ -2812,7 +2869,7 @@ function formatEventHandlers(r) {
2812
2869
  }
2813
2870
  out += `\n`;
2814
2871
  }
2815
- return out;
2872
+ return out + scanNote;
2816
2873
  }
2817
2874
  // API USAGE CALLERS via XREF (P5)
2818
2875
  export async function tryBridgeApiUsageCallers(bridge, apiName, limit = 200) {
@@ -2822,17 +2879,18 @@ export async function tryBridgeApiUsageCallers(bridge, apiName, limit = 200) {
2822
2879
  const result = await bridge.findApiUsageCallers(apiName, limit);
2823
2880
  if (!result || result.totalCallers === 0)
2824
2881
  return null;
2825
- return { content: [{ type: 'text', text: formatApiUsageCallers(result) }] };
2882
+ return { content: [{ type: 'text', text: formatApiUsageCallers(result, xrefSourceLabel(bridge)) }] };
2826
2883
  }
2827
2884
  catch (e) {
2828
2885
  recordBridgeFailure(`findApiUsageCallers(${apiName})`, e);
2829
2886
  return null;
2830
2887
  }
2831
2888
  }
2832
- function formatApiUsageCallers(r) {
2889
+ function formatApiUsageCallers(r, source) {
2833
2890
  let out = `# API Usage: ${r.apiName}\n\n`;
2834
- out += `**Total references:** ${r.totalCallers} from ${r.uniqueClasses} unique class(es)\n`;
2835
- out += `_Source: C# bridge (DYNAMICSXREFDB)_\n\n`;
2891
+ out += `**Total references:** ${r.totalCallers}${r.more ? '+' : ''} from ${r.uniqueClasses} unique class(es)` +
2892
+ `${r.more ? ` (more available: the first ${r.totalCallers} found are shown)` : ''}\n`;
2893
+ out += `_Source: ${source}_\n\n`;
2836
2894
  out += `## Top Callers by Class\n\n`;
2837
2895
  for (const cls of r.callersByClass.slice(0, 30)) {
2838
2896
  out += `- **${cls.callerClass}** (${cls.callCount} call(s))`;
@@ -283,6 +283,11 @@ export interface BridgeReferenceResult {
283
283
  /** Every matching reference, and how many of them are declarative metadata. Absent from older bridges. */
284
284
  total?: number;
285
285
  metadataTotal?: number;
286
+ /**
287
+ * Set by the xref SQLite provider when a count stopped at its cap: total and
288
+ * metadataTotal are then lower bounds. The bridge counts without a cap.
289
+ */
290
+ totalCapped?: boolean;
286
291
  references: BridgeReferenceInfo[];
287
292
  /** 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". */
288
293
  error?: string;
@@ -602,6 +607,12 @@ export interface BridgeEventSubscriberResult {
602
607
  count: number;
603
608
  handlers: BridgeEventSubscriberEntry[];
604
609
  _source: string;
610
+ /**
611
+ * Set by the xref SQLite provider when it examined only the first `scanned`
612
+ * references to the target (its scan cap): more handlers may exist.
613
+ */
614
+ scanCapped?: boolean;
615
+ scanned?: number;
605
616
  }
606
617
  export interface BridgeApiUsageCallerEntry {
607
618
  callerClass: string;
@@ -623,5 +634,7 @@ export interface BridgeApiUsageCallersResult {
623
634
  callersByClass: BridgeApiUsageCallersByClass[];
624
635
  callers: BridgeApiUsageCallerEntry[];
625
636
  _source: string;
637
+ /** Set by the xref SQLite provider when more callers exist than were returned. */
638
+ more?: boolean;
626
639
  }
627
640
  //# sourceMappingURL=bridgeTypes.d.ts.map
@@ -94,6 +94,11 @@ export declare function checkTrace(store: SettingsStore, label: string, free?: (
94
94
  * (relations, form data sources, fields using an EDT). Null when configured.
95
95
  */
96
96
  export declare function checkXrefConfigured(store: SettingsStore): CheckResult | null;
97
+ /**
98
+ * The xref SQLite file (D365FO_XREF_SQLITE_PATH), opened the way the server opens
99
+ * it: read-only, validated, then closed. Null when none is configured.
100
+ */
101
+ export declare function checkXrefSqlite(store: SettingsStore): CheckResult | null;
97
102
  /**
98
103
  * A built bridge, judged against the sources it was compiled from (#1115). An
99
104
  * update can leave an old binary in place while it moves the bridge sources,
@@ -10,6 +10,8 @@ import { relative, resolve } from 'node:path';
10
10
  import { p } from '../ui.js';
11
11
  import { serializeValue, settingByPath } from '../../config/settings.js';
12
12
  import { xrefSetupAdvice } from '../../config/xrefSetup.js';
13
+ import { SqliteXrefProvider } from '../../xref/sqliteXrefProvider.js';
14
+ import { xrefSqliteCounting } from '../../xref/xrefSource.js';
13
15
  import { bridgeFreshness } from '../bridgeSources.js';
14
16
  import { bridgeBuildCommand, dataRoot, installMode, isWindows, paths, repoRoot } from '../context.js';
15
17
  import { commandExists } from '../exec.js';
@@ -557,6 +559,35 @@ export function checkXrefConfigured(store) {
557
559
  fix: xrefSetupAdvice(s => s),
558
560
  };
559
561
  }
562
+ /**
563
+ * The xref SQLite file (D365FO_XREF_SQLITE_PATH), opened the way the server opens
564
+ * it: read-only, validated, then closed. Null when none is configured.
565
+ */
566
+ export function checkXrefSqlite(store) {
567
+ // Same precedence as the server: the real environment (an .mcp.json `env` block) first.
568
+ const file = process.env.D365FO_XREF_SQLITE_PATH?.trim() || readPath(store, settingByPath('index.xrefSqlitePath'), '');
569
+ if (!file)
570
+ return null;
571
+ const provider = new SqliteXrefProvider(file, () => { });
572
+ try {
573
+ const st = provider.status();
574
+ if (st.state === 'ok') {
575
+ return {
576
+ severity: 'ok',
577
+ message: `Cross-reference SQLite file: exported ${st.exportedAt ?? '(unknown)'}, ${st.modules} modules, ` +
578
+ `totals ${xrefSqliteCounting(st)} (${file})`,
579
+ };
580
+ }
581
+ return {
582
+ severity: 'warn',
583
+ message: `Cross-reference SQLite file not usable — ${st.reason} (${file}); find_references falls back to a name-based search`,
584
+ fix: 'point D365FO_XREF_SQLITE_PATH (index.xrefSqlitePath) at a complete DYNAMICSXREFDB export with meta.schema 1, or unset it',
585
+ };
586
+ }
587
+ finally {
588
+ provider.close();
589
+ }
590
+ }
560
591
  /**
561
592
  * A built bridge, judged against the sources it was compiled from (#1115). An
562
593
  * update can leave an old binary in place while it moves the bridge sources,
@@ -682,6 +713,9 @@ export async function doctorCommand() {
682
713
  else {
683
714
  emit({ severity: 'info', message: `C# bridge skipped (Windows-only) — platform is ${process.platform}` });
684
715
  }
716
+ const xrefSqlite = checkXrefSqlite(root.store);
717
+ if (xrefSqlite)
718
+ emit(xrefSqlite);
685
719
  // Instances
686
720
  const instances = listInstances();
687
721
  if (instances.length > 0) {
@@ -318,6 +318,75 @@ export const SETTINGS = [
318
318
  { value: 'prefix-leading', hint: 'CtsoCustTable_Extension — embeds the extension prefix, leading (e.g. Avanade Development Guidelines)' },
319
319
  ],
320
320
  },
321
+ {
322
+ path: 'naming.elementNameFormat',
323
+ env: 'EXTENSION_ELEMENT_NAME_FORMAT',
324
+ section: 'naming',
325
+ tier: 'advanced',
326
+ type: 'string',
327
+ label: 'Name format for element extensions',
328
+ description: 'A fixed name shape for every element extension (tables, forms, EDTs, enums, menus, menu items, security ' +
329
+ 'objects …), `{0}` = the extended object: `{0}.Contoso` names the InventTable extension `InventTable.Contoso`. ' +
330
+ 'Set, it replaces `naming.extensionStyle` for element extensions; create, prepare and validate_object_naming ' +
331
+ 'all apply it. Empty (the default) = the style decides, as before. See ' +
332
+ '[Extension name formats](CUSTOM_EXTENSIONS.md#extension-name-formats).',
333
+ placeholder: '{0}.Contoso',
334
+ },
335
+ {
336
+ path: 'naming.classNameFormat',
337
+ env: 'EXTENSION_CLASS_NAME_FORMAT',
338
+ section: 'naming',
339
+ tier: 'advanced',
340
+ type: 'string',
341
+ label: 'Name format for extension classes',
342
+ description: 'A fixed name shape for CoC extension classes, `{0}` = the extended object; `_Extension` is always appended: ' +
343
+ '`Contoso_{0}Cls` names the SalesFormLetter extension `Contoso_SalesFormLetterCls_Extension`. Used for classes, ' +
344
+ 'and for tables and forms that have no format of their own. Which format applies depends on the TYPE of the ' +
345
+ 'extended object, which comes from the call (the `[ExtensionOf(tableStr(…))]` in sourceCode, or ' +
346
+ '`properties.baseObjectType`) and is never guessed from a name. Set, it replaces `naming.extensionClassStyle`. ' +
347
+ 'Empty (the default) = the style decides, as before.',
348
+ placeholder: 'Contoso_{0}Cls',
349
+ },
350
+ {
351
+ path: 'naming.classNameFormatTable',
352
+ env: 'EXTENSION_CLASS_NAME_FORMAT_TABLE',
353
+ section: 'naming',
354
+ tier: 'advanced',
355
+ type: 'string',
356
+ label: 'Name format for extension classes of tables',
357
+ description: 'Like `naming.classNameFormat`, for extension classes of TABLES (`[ExtensionOf(tableStr(…))]`); `_Extension` ' +
358
+ 'is appended: `Contoso_{0}Dbt` → `Contoso_InventTableDbt_Extension`. Empty = `naming.classNameFormat`.',
359
+ placeholder: 'Contoso_{0}Dbt',
360
+ },
361
+ {
362
+ path: 'naming.classNameFormatForm',
363
+ env: 'EXTENSION_CLASS_NAME_FORMAT_FORM',
364
+ section: 'naming',
365
+ tier: 'advanced',
366
+ type: 'string',
367
+ label: 'Name format for extension classes of forms',
368
+ description: 'Like `naming.classNameFormat`, for extension classes of FORMS (`[ExtensionOf(formStr(…))]`); `_Extension` ' +
369
+ 'is appended: `Contoso_{0}Frm` → `Contoso_InventTableFrm_Extension`. Empty = `naming.classNameFormat`.',
370
+ placeholder: 'Contoso_{0}Frm',
371
+ },
372
+ {
373
+ path: 'naming.undefinedNameFormat',
374
+ env: 'EXTENSION_NAME_FORMAT_UNDEFINED',
375
+ section: 'naming',
376
+ tier: 'advanced',
377
+ type: 'enum',
378
+ label: 'Extension classes no format defines',
379
+ description: 'Only read while an extension class name format is set. Decides the extension classes none of them defines — ' +
380
+ 'of form data sources and controls, views, data entities, maps …, and calls that do not state the extended ' +
381
+ 'object\'s type. `ask`: the tool does not invent a name; it answers "ask the user for the name and call again ' +
382
+ 'with an explicit name". `class-format`: `naming.classNameFormat` names them. An explicit full name (ending in ' +
383
+ '`_Extension`) is accepted for these cases either way.',
384
+ default: 'ask',
385
+ choices: [
386
+ { value: 'ask', hint: 'the tool asks for the name — the user decides' },
387
+ { value: 'class-format', hint: 'naming.classNameFormat names them' },
388
+ ],
389
+ },
321
390
  // ── index ────────────────────────────────────────────────────────────────
322
391
  {
323
392
  path: 'index.extractMode',
@@ -383,6 +452,20 @@ export const SETTINGS = [
383
452
  'Defaults to <dbPath>-labels.db.',
384
453
  default: './data/xpp-metadata-labels.db',
385
454
  },
455
+ {
456
+ path: 'index.xrefSqlitePath',
457
+ env: 'D365FO_XREF_SQLITE_PATH',
458
+ section: 'index',
459
+ tier: 'advanced',
460
+ type: 'path',
461
+ label: 'Cross-reference SQLite file',
462
+ description: 'A SQLite export of DYNAMICSXREFDB (tables Modules, Names, References; meta.schema 1) for a server without ' +
463
+ 'the C# bridge, e.g. a shared read-only server. find_references and the extension/event/API-usage lookups ' +
464
+ 'then answer from it instead of a name-based search; the bridge still takes precedence when it has the ' +
465
+ 'database. Opened read-only and immutable on first use: replace the file by rename, never in place (on Windows ' +
466
+ 'an open file cannot be renamed over: stop the server, replace the file, start it again). ' +
467
+ 'A missing or invalid file is logged and ignored. get_workspace_info shows its export date.',
468
+ },
386
469
  {
387
470
  path: 'index.metadataPath',
388
471
  env: 'METADATA_PATH',
package/dist/index.js CHANGED
@@ -28,6 +28,7 @@ import { VERSION } from './version.js';
28
28
  import { setInitializeParams } from './utils/stdioSessionInfo.js';
29
29
  import { setModelObjectNameSource } from './utils/modelPrefixInference.js';
30
30
  import { trackBridgeStartup } from './bridge/bridgeReadiness.js';
31
+ import { describeXrefSource } from './xref/xrefSource.js';
31
32
  import { startLoopLagMonitor } from './utils/loopLag.js';
32
33
  import { warmPackagesRoots } from './utils/packagesRoot.js';
33
34
  import { startupIndexBegan, setStartupIndexProgress, clearStartupIndexProgress, } from './utils/startupProgress.js';
@@ -434,6 +435,25 @@ async function initializeServices() {
434
435
  throw error;
435
436
  }
436
437
  }
438
+ /**
439
+ * Report the xref SQLite file once the bridge has settled: the source tools will
440
+ * use, and for the file its export date — or why it cannot be used. Only when
441
+ * D365FO_XREF_SQLITE_PATH is set; opening it is a few small reads.
442
+ */
443
+ function logXrefSqlite(context) {
444
+ if (!context.xrefSqlite)
445
+ return;
446
+ try {
447
+ const d = describeXrefSource(context);
448
+ if (d.kind === 'none')
449
+ log.warn(`Cross-references: ${d.line}`);
450
+ else
451
+ log.ok(`Cross-references: ${d.line}`);
452
+ }
453
+ catch (e) {
454
+ log.warn(`Cross-references: the xref SQLite file could not be checked: ${e}`);
455
+ }
456
+ }
437
457
  async function initializeBridge(targetContext) {
438
458
  try {
439
459
  const { createBridgeClient } = await import('./bridge/bridgeClient.js');
@@ -717,7 +737,13 @@ async function main() {
717
737
  // and cross-reference queries — only available on Windows VMs with D365FO.
718
738
  // The attempt is tracked on the context so bridge-backed tools called in the
719
739
  // first seconds wait for it instead of reporting a phantom "not connected".
720
- stubContext.bridgeStartup = trackBridgeStartup(initializeBridge(stubContext).then(s => (s.ok ? log.ok(s.summary) : log.warn(s.summary))));
740
+ stubContext.bridgeStartup = trackBridgeStartup(initializeBridge(stubContext).then(s => {
741
+ if (s.ok)
742
+ log.ok(s.summary);
743
+ else
744
+ log.warn(s.summary);
745
+ logXrefSqlite(stubContext);
746
+ }));
721
747
  // Step 4: load real database in the background
722
748
  const dbLoadStart = Date.now();
723
749
  initializeServices().then(({ symbolIndex, parser, workspaceScanner, hybridSearch }) => {
@@ -874,6 +900,7 @@ async function main() {
874
900
  log.warn(status.summary);
875
901
  if (status.detail)
876
902
  log.detail(status.detail);
903
+ logXrefSqlite(context);
877
904
  }
878
905
  console.log('');
879
906
  const toolCatalog = [