d365fo-mcp 1.26.1 → 1.26.2

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.
@@ -555,6 +555,16 @@ var SETTINGS = [
555
555
  description: 'Builds the labels database so labels(action="search") and label reuse work. Disabling it speeds up the build and shrinks the index, at the cost of label lookup.',
556
556
  default: true
557
557
  },
558
+ {
559
+ path: "index.reindexChangedOnStartup",
560
+ env: "REINDEX_CHANGED_ON_STARTUP",
561
+ section: "index",
562
+ tier: "advanced",
563
+ type: "boolean",
564
+ label: "Re-index changed custom models on start",
565
+ description: "Shortly after start, re-index the files of the custom models of the workspace that changed while the server was not running (a git pull, a branch switch, a Visual Studio session), in the background, as update_symbol_index(model) does. Off = the index stays as it was until update_symbol_index runs.",
566
+ default: true
567
+ },
558
568
  {
559
569
  path: "index.labelLanguages",
560
570
  env: "LABEL_LANGUAGES",
@@ -954,6 +964,16 @@ var SETTINGS = [
954
964
  description: "Circuit breaker: after this many respawns within 60 s the server stops trying.",
955
965
  default: 3
956
966
  },
967
+ {
968
+ path: "bridge.platformCheckMs",
969
+ env: "BRIDGE_PLATFORM_CHECK_MS",
970
+ section: "bridge",
971
+ tier: "advanced",
972
+ type: "int",
973
+ label: "Platform check interval (ms)",
974
+ description: "How often, at most, a bridge call checks whether the platform changed (a new XPP config, or a junction moved to a newer platform folder) and restarts the bridge on it. 0 = off.",
975
+ default: 6e4
976
+ },
957
977
  {
958
978
  path: "bridge.exePath",
959
979
  env: "D365FO_BRIDGE_EXE_PATH",
@@ -555,6 +555,16 @@ var SETTINGS = [
555
555
  description: 'Builds the labels database so labels(action="search") and label reuse work. Disabling it speeds up the build and shrinks the index, at the cost of label lookup.',
556
556
  default: true
557
557
  },
558
+ {
559
+ path: "index.reindexChangedOnStartup",
560
+ env: "REINDEX_CHANGED_ON_STARTUP",
561
+ section: "index",
562
+ tier: "advanced",
563
+ type: "boolean",
564
+ label: "Re-index changed custom models on start",
565
+ description: "Shortly after start, re-index the files of the custom models of the workspace that changed while the server was not running (a git pull, a branch switch, a Visual Studio session), in the background, as update_symbol_index(model) does. Off = the index stays as it was until update_symbol_index runs.",
566
+ default: true
567
+ },
558
568
  {
559
569
  path: "index.labelLanguages",
560
570
  env: "LABEL_LANGUAGES",
@@ -954,6 +964,16 @@ var SETTINGS = [
954
964
  description: "Circuit breaker: after this many respawns within 60 s the server stops trying.",
955
965
  default: 3
956
966
  },
967
+ {
968
+ path: "bridge.platformCheckMs",
969
+ env: "BRIDGE_PLATFORM_CHECK_MS",
970
+ section: "bridge",
971
+ tier: "advanced",
972
+ type: "int",
973
+ label: "Platform check interval (ms)",
974
+ description: "How often, at most, a bridge call checks whether the platform changed (a new XPP config, or a junction moved to a newer platform folder) and restarts the bridge on it. 0 = off.",
975
+ default: 6e4
976
+ },
957
977
  {
958
978
  path: "bridge.exePath",
959
979
  env: "D365FO_BRIDGE_EXE_PATH",
@@ -705,6 +705,16 @@ var SETTINGS = [
705
705
  description: 'Builds the labels database so labels(action="search") and label reuse work. Disabling it speeds up the build and shrinks the index, at the cost of label lookup.',
706
706
  default: true
707
707
  },
708
+ {
709
+ path: "index.reindexChangedOnStartup",
710
+ env: "REINDEX_CHANGED_ON_STARTUP",
711
+ section: "index",
712
+ tier: "advanced",
713
+ type: "boolean",
714
+ label: "Re-index changed custom models on start",
715
+ description: "Shortly after start, re-index the files of the custom models of the workspace that changed while the server was not running (a git pull, a branch switch, a Visual Studio session), in the background, as update_symbol_index(model) does. Off = the index stays as it was until update_symbol_index runs.",
716
+ default: true
717
+ },
708
718
  {
709
719
  path: "index.labelLanguages",
710
720
  env: "LABEL_LANGUAGES",
@@ -1104,6 +1114,16 @@ var SETTINGS = [
1104
1114
  description: "Circuit breaker: after this many respawns within 60 s the server stops trying.",
1105
1115
  default: 3
1106
1116
  },
1117
+ {
1118
+ path: "bridge.platformCheckMs",
1119
+ env: "BRIDGE_PLATFORM_CHECK_MS",
1120
+ section: "bridge",
1121
+ tier: "advanced",
1122
+ type: "int",
1123
+ label: "Platform check interval (ms)",
1124
+ description: "How often, at most, a bridge call checks whether the platform changed (a new XPP config, or a junction moved to a newer platform folder) and restarts the bridge on it. 0 = off.",
1125
+ default: 6e4
1126
+ },
1107
1127
  {
1108
1128
  path: "bridge.exePath",
1109
1129
  env: "D365FO_BRIDGE_EXE_PATH",
@@ -3423,6 +3443,7 @@ Point the installation at a drive with room (a full index needs several GB): re-
3423
3443
  return wrapped;
3424
3444
  }
3425
3445
  async indexMetadataDirectory(metadataPath, modelNames, opts) {
3446
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
3426
3447
  const report = (p) => {
3427
3448
  try {
3428
3449
  opts?.onProgress?.(p);
@@ -3580,6 +3601,7 @@ Point the installation at a drive with room (a full index needs several GB): re-
3580
3601
  log.ok(`Indexed ${models.length} model(s) in ${duration}s (FTS rebuilt in ${ftsDuration}s)`);
3581
3602
  }
3582
3603
  this.touchLastIndexed();
3604
+ for (const model of models) this.setModelSyncedAt(model, startedAt);
3583
3605
  }
3584
3606
  /**
3585
3607
  * Sort models by JSON file count descending.
@@ -4562,9 +4584,13 @@ Point the installation at a drive with room (a full index needs several GB): re-
4562
4584
  }
4563
4585
  /** Every distinct file path the symbols table holds for a model. */
4564
4586
  getModelFilePaths(model) {
4565
- const rows = this.getReadDb().prepare(
4566
- `SELECT DISTINCT file_path FROM symbols WHERE model = ? COLLATE NOCASE`
4567
- ).all(model);
4587
+ const db = this.getReadDb();
4588
+ const key = model.toLowerCase();
4589
+ const spellings = db.prepare(`SELECT DISTINCT model FROM symbols`).all().map((r) => r.model).filter((m) => m?.toLowerCase() === key);
4590
+ if (spellings.length === 0) return [];
4591
+ const rows = db.prepare(
4592
+ `SELECT DISTINCT file_path FROM symbols WHERE model IN (${spellings.map(() => "?").join(", ")})`
4593
+ ).all(...spellings);
4568
4594
  return rows.map((r) => r.file_path);
4569
4595
  }
4570
4596
  /** Every path indexed_files records for a model, as stored. */
@@ -4587,6 +4613,29 @@ Point the installation at a drive with room (a full index needs several GB): re-
4587
4613
  }
4588
4614
  }
4589
4615
  /** ISO timestamp of the last full or incremental index update, or null. */
4616
+ /**
4617
+ * The moment up to which this model's files are known to be in the index: the start of
4618
+ * the build that indexed it, or of the last start-up pass that brought it up to date.
4619
+ * Unlike last_indexed_at, a single file write does not move it.
4620
+ */
4621
+ getModelSyncedAt(model) {
4622
+ try {
4623
+ const row = this.getReadDb().prepare(
4624
+ `SELECT value FROM _index_meta WHERE key = ?`
4625
+ ).get(`model_synced_at:${model.toLowerCase()}`);
4626
+ return row?.value ?? null;
4627
+ } catch {
4628
+ return null;
4629
+ }
4630
+ }
4631
+ setModelSyncedAt(model, isoTime) {
4632
+ try {
4633
+ this.db.prepare(
4634
+ `INSERT OR REPLACE INTO _index_meta (key, value) VALUES (?, ?)`
4635
+ ).run(`model_synced_at:${model.toLowerCase()}`, isoTime);
4636
+ } catch {
4637
+ }
4638
+ }
4590
4639
  getLastIndexedAt() {
4591
4640
  try {
4592
4641
  const row = this.getReadDb().prepare(
@@ -180,6 +180,11 @@ export class CustomHttpTransport {
180
180
  setupRoutes() {
181
181
  // Apply rate limiting
182
182
  this.app.use('/mcp', apiRateLimiter);
183
+ // There is no server-to-client stream. A streamable HTTP client asks for one with
184
+ // GET and expects 405 when there is none; it reports a 404 as a failure.
185
+ this.app.get('/mcp', (_req, res) => {
186
+ res.status(405).set('Allow', 'POST').end();
187
+ });
183
188
  // MCP endpoint - direct JSON-RPC
184
189
  this.app.post('/mcp', async (req, res) => {
185
190
  // Declare here so the catch block can clean it up regardless of where an error fires
@@ -10,6 +10,8 @@ import { COMPACT_METHODS_HINT, SOURCE_UNAVAILABLE_HINT, INDEXED_BODIES_HINT, ful
10
10
  import { readIndexedMethodSources } from '../../utils/indexedMethodSource.js';
11
11
  import { isBinaryIsvPath } from '../../metadata/binaryModelImport.js';
12
12
  import { methodOffsetPastEndNote, methodRangeText } from '../../utils/payloadBudget.js';
13
+ import { diskFallbackNote, indexFromDisk, prependNote } from './diskFallback.js';
14
+ import { canonicalSymbolName } from '../../utils/symbolLookup.js';
13
15
  const METHOD_PAGE_SIZE = 15;
14
16
  /** Ceiling on one method body inside a class LISTING (both render paths). */
15
17
  const BODY_PREVIEW_CHARS = 200;
@@ -52,8 +54,30 @@ export async function classInfoTool(request, context) {
52
54
  if (bridgeResult) {
53
55
  return bridgeResult;
54
56
  }
55
- // Query database next
56
- const classSymbol = symbolIndex.getSymbolByName(args.className, 'class');
57
+ // Query database next. X++ names are case-insensitive and this lookup is not: fall
58
+ // back to the indexed spelling, which the method lookups below need too.
59
+ const findClass = () => {
60
+ const exact = symbolIndex.getSymbolByName(args.className, 'class');
61
+ if (exact)
62
+ return exact;
63
+ const canonical = canonicalSymbolName(symbolIndex.getReadDb(), args.className, ['class']);
64
+ if (!canonical || canonical === args.className)
65
+ return exact;
66
+ args.className = canonical;
67
+ return symbolIndex.getSymbolByName(canonical, 'class');
68
+ };
69
+ let classSymbol = findClass();
70
+ // Index miss: a class written outside this server is in the model folder before it is
71
+ // in the index. Index that file and answer from it (see diskFallback.ts).
72
+ let diskNote = '';
73
+ if (!classSymbol) {
74
+ const diskPath = await indexFromDisk('class', args.className, undefined, context);
75
+ if (diskPath) {
76
+ classSymbol = findClass();
77
+ if (classSymbol)
78
+ diskNote = diskFallbackNote(diskPath);
79
+ }
80
+ }
57
81
  if (!classSymbol) {
58
82
  const typeMismatch = buildObjectTypeMismatchMessage(symbolIndex.getReadDb(), args.className);
59
83
  return {
@@ -68,7 +92,7 @@ export async function classInfoTool(request, context) {
68
92
  }
69
93
  // compact=true (default): serve entirely from DB — no filesystem access, instant response
70
94
  if (args.compact !== false) {
71
- return buildDbOnlyResponse(args.className, classSymbol, symbolIndex, args.methodOffset ?? 0, 'compact');
95
+ return prependNote(await buildDbOnlyResponse(args.className, classSymbol, symbolIndex, args.methodOffset ?? 0, 'compact'), diskNote);
72
96
  }
73
97
  // compact=false: parse XML for source bodies, with timeout guard to avoid hanging
74
98
  let classInfo = { success: false };
@@ -83,10 +107,10 @@ export async function classInfoTool(request, context) {
83
107
  }
84
108
  if (!classInfo.success || !classInfo.data) {
85
109
  // Fallback to DB when XML not available (build agent, no D365FO install, timeout)
86
- return buildDbOnlyResponse(args.className, classSymbol, symbolIndex, args.methodOffset ?? 0, 'source-unavailable');
110
+ return prependNote(await buildDbOnlyResponse(args.className, classSymbol, symbolIndex, args.methodOffset ?? 0, 'source-unavailable'), diskNote);
87
111
  }
88
112
  const cls = classInfo.data;
89
- let output = `# Class: ${cls.name}\n\n`;
113
+ let output = `${diskNote}# Class: ${cls.name}\n\n`;
90
114
  if (cls.extends) {
91
115
  output += `**Extends:** ${cls.extends}\n`;
92
116
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Index miss → the file on disk.
3
+ *
4
+ * A file written outside this server (Visual Studio, a script, another tool, a git pull)
5
+ * is in the model folder but not in the symbol index until someone runs
6
+ * update_symbol_index. The table, enum, view, query and map readers already looked on
7
+ * disk on a miss. The class, form and EDT readers answered "not found" instead, and the
8
+ * agent then concluded the object did not exist, or recreated it.
9
+ *
10
+ * These readers now look in the model folder on a miss and index that one file (the same
11
+ * step update_symbol_index(filePath) runs), so the answer and every later read come from
12
+ * the index as usual.
13
+ */
14
+ import type { XppServerContext } from '../../types/context.js';
15
+ /**
16
+ * The path of `name` in the model folder after indexing it, or null when there is no such
17
+ * file. An indexing failure is logged and still returns the path: the file is there, and
18
+ * the caller can read it directly.
19
+ */
20
+ export declare function indexFromDisk(objectType: string, name: string, modelName: string | undefined, context: XppServerContext): Promise<string | null>;
21
+ /** The line a reply carries when its answer came from a file the index did not have yet. */
22
+ export declare function diskFallbackNote(diskPath: string): string;
23
+ /** Prefix the first text block of a tool result with `note`. */
24
+ export declare function prependNote<T extends {
25
+ content?: Array<{
26
+ type: string;
27
+ text?: string;
28
+ }>;
29
+ }>(result: T, note: string): T;
30
+ //# sourceMappingURL=diskFallback.d.ts.map
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Index miss → the file on disk.
3
+ *
4
+ * A file written outside this server (Visual Studio, a script, another tool, a git pull)
5
+ * is in the model folder but not in the symbol index until someone runs
6
+ * update_symbol_index. The table, enum, view, query and map readers already looked on
7
+ * disk on a miss. The class, form and EDT readers answered "not found" instead, and the
8
+ * agent then concluded the object did not exist, or recreated it.
9
+ *
10
+ * These readers now look in the model folder on a miss and index that one file (the same
11
+ * step update_symbol_index(filePath) runs), so the answer and every later read come from
12
+ * the index as usual.
13
+ */
14
+ import { findD365FileOnDisk } from '../../utils/objectFileLookup.js';
15
+ import { canonicalSymbolName } from '../../utils/symbolLookup.js';
16
+ import { indexOneFile } from '../sdlc/updateSymbolIndex.js';
17
+ /**
18
+ * The path of `name` in the model folder after indexing it, or null when there is no such
19
+ * file. An indexing failure is logged and still returns the path: the file is there, and
20
+ * the caller can read it directly.
21
+ */
22
+ export async function indexFromDisk(objectType, name, modelName, context) {
23
+ try {
24
+ // Indexed under another casing: nothing is missing, and indexing the file again on
25
+ // every such read would be a write per read.
26
+ const canonical = canonicalSymbolName(context.symbolIndex.getReadDb(), name, [objectType]);
27
+ if (canonical && canonical !== name)
28
+ return null;
29
+ }
30
+ catch { /* no usable index — look on disk */ }
31
+ let diskPath;
32
+ try {
33
+ diskPath = await findD365FileOnDisk(objectType, name, modelName);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ if (!diskPath)
39
+ return null;
40
+ try {
41
+ const result = await indexOneFile(diskPath, context);
42
+ if (result.isError)
43
+ console.error(`[diskFallback] Indexing ${diskPath} failed: ${result.text}`);
44
+ }
45
+ catch (err) {
46
+ console.error(`[diskFallback] Indexing ${diskPath} failed: ${err instanceof Error ? err.message : err}`);
47
+ }
48
+ return diskPath;
49
+ }
50
+ /** The line a reply carries when its answer came from a file the index did not have yet. */
51
+ export function diskFallbackNote(diskPath) {
52
+ return `> ℹ️ Not in the symbol index yet: read from ${diskPath} and indexed now.\n\n`;
53
+ }
54
+ /** Prefix the first text block of a tool result with `note`. */
55
+ export function prependNote(result, note) {
56
+ const first = result.content?.[0];
57
+ if (note && first && typeof first.text === 'string')
58
+ first.text = note + first.text;
59
+ return result;
60
+ }
61
+ //# sourceMappingURL=diskFallback.js.map
@@ -12,6 +12,7 @@ import { normalizeFieldBaseType } from '../../utils/axFieldTypes.js';
12
12
  import { describeKernelEdt } from '../../knowledge/kernelEdts.js';
13
13
  import { integerText } from '../../utils/integerText.js';
14
14
  import { binaryIsvNotice, isBinaryIsvPath } from '../../metadata/binaryModelImport.js';
15
+ import { diskFallbackNote, indexFromDisk, prependNote } from './diskFallback.js';
15
16
  const GetEdtInfoArgsSchema = z.object({
16
17
  edtName: z.string().describe('Name of the Extended Data Type (EDT)'),
17
18
  modelName: z.string().optional().describe('Model name (auto-detected if not provided)'),
@@ -48,6 +49,12 @@ export async function getEdtInfoTool(request, context) {
48
49
  const sqliteResult = getEdtFromIndex(symbolIndex, edtName, modelName);
49
50
  if (sqliteResult)
50
51
  return sqliteResult;
52
+ // Index miss: an EDT written outside this server is in the model folder before it is in
53
+ // the index. Indexing the file also fills edt_metadata (see diskFallback.ts).
54
+ const diskPath = await indexFromDisk('edt', edtName, modelName, context);
55
+ const fromDisk = diskPath ? getEdtFromIndex(symbolIndex, edtName, modelName) : null;
56
+ if (diskPath && fromDisk)
57
+ return prependNote(fromDisk, diskFallbackNote(diskPath));
51
58
  return {
52
59
  content: [{
53
60
  type: 'text',
@@ -15,6 +15,8 @@ import { readIndexedXml, resolveIndexedObject } from '../../utils/indexedXmlLook
15
15
  import { isCustomModel } from '../../utils/modelClassifier.js';
16
16
  import { countFormControls, findControlElementOrderViolations, formatElementOrderViolations, } from '../../validation/formControlElementOrder.js';
17
17
  import { describeBridgeStartup } from '../../bridge/bridgeReadiness.js';
18
+ import * as path from 'path';
19
+ import { diskFallbackNote, indexFromDisk, prependNote } from './diskFallback.js';
18
20
  import { assertWritePathAllowed } from '../../utils/pathContainment.js';
19
21
  import { createControlBudget, chargeControl, chargeSkippedSubtree, controlsFooter, DEFAULT_MAX_CONTROLS, FORM_METHOD_PAGE_SIZE, methodOffsetPastEndNote, methodRangeText, moreMethodsNote, } from '../../utils/payloadBudget.js';
20
22
  const GetFormInfoArgsSchema = z.object({
@@ -96,6 +98,18 @@ export async function getFormInfoTool(request, context) {
96
98
  }
97
99
  catch { /* not a usable AxForm XML — fall through to the error below */ }
98
100
  }
101
+ // Index miss: a form written outside this server is in the model folder before it is in
102
+ // the index. Index that file and answer from it (see diskFallback.ts).
103
+ const diskPath = await indexFromDisk('form', formName, args.modelName, context);
104
+ if (diskPath) {
105
+ try {
106
+ const diskXml = await fs.readFile(diskPath, 'utf-8');
107
+ const model = path.basename(path.dirname(path.dirname(diskPath)));
108
+ const result = await parseAndFormatForm(formName, model, diskXml, includeControls, includeDataSources, includeMethods, searchControl, maxControls, methodOffset);
109
+ return prependNote(result, diskFallbackNote(diskPath));
110
+ }
111
+ catch { /* not a usable AxForm XML — fall through */ }
112
+ }
99
113
  // The XML was unreachable and a search was asked for. The bridge can still
100
114
  // describe the form, but it cannot filter — say so rather than returning a
101
115
  // full tree that looks like the search found everything.
@@ -24,11 +24,40 @@ import type { XppServerContext } from '../../types/context.js';
24
24
  export declare function resolveModelFolder(model: string, context: XppServerContext): Promise<string | null>;
25
25
  /** Every file update_symbol_index can index: XML in an Ax* folder, and label text files. */
26
26
  export declare function listModelFiles(folder: string): string[];
27
- export declare function reindexModel(model: string, context: XppServerContext): Promise<{
27
+ export interface ReindexOptions {
28
+ /**
29
+ * Epoch ms. A file with no recorded mtime counts as changed only when it is newer than
30
+ * this. Without it, such a file is always read (the first pass reads the whole model).
31
+ * The startup pass sets it to the index's last update, so a model the full build indexed
32
+ * (which records no per-file mtimes) is not read in full on every start.
33
+ */
34
+ unrecordedSince?: number;
35
+ }
36
+ export declare function reindexModel(model: string, context: XppServerContext, options?: ReindexOptions): Promise<{
28
37
  content: {
29
38
  type: string;
30
39
  text: string;
31
40
  }[];
32
41
  isError?: boolean | undefined;
33
42
  }>;
43
+ /**
44
+ * Bring the index in line with files changed while the server was not running (a git pull,
45
+ * a branch switch, a Visual Studio session), once, in the background after start-up.
46
+ *
47
+ * Runs reindexModel for each model, one at a time with a yield between models, so a
48
+ * request is never queued behind more than one model's walk. A model whose files are all
49
+ * indexed costs one directory walk and one stat per file. Returns one log line per model
50
+ * that changed, and never throws.
51
+ */
52
+ export declare function reindexChangedModels(models: string[], context: XppServerContext): Promise<string[]>;
53
+ /**
54
+ * The custom models this workspace develops: the configured model, the models registered
55
+ * as custom at run time, and the CUSTOM_MODELS entries that are names (not masks).
56
+ */
57
+ export declare function workspaceCustomModels(configuredModel?: string | null): string[];
58
+ /**
59
+ * Schedule reindexChangedModels once, STARTUP_REINDEX_DELAY_MS after start-up, unless
60
+ * REINDEX_CHANGED_ON_STARTUP=false. The timer is unref'd, so it never keeps the process alive.
61
+ */
62
+ export declare function scheduleStartupReindex(context: XppServerContext, log: (line: string) => void, delayMs?: number): void;
34
63
  //# sourceMappingURL=modelReindex.d.ts.map
@@ -16,7 +16,7 @@
16
16
  import fs from 'fs';
17
17
  import path from 'path';
18
18
  import { bridgeRefreshProvider } from '../../bridge/index.js';
19
- import { isCustomModel } from '../../utils/modelClassifier.js';
19
+ import { getAutoDetectedCustomModels, getCustomModels, isCustomModel } from '../../utils/modelClassifier.js';
20
20
  import { getConfigManager } from '../../utils/configManager.js';
21
21
  import { resetMetadataMtimeCache } from '../../utils/indexStaleness.js';
22
22
  import { indexOneFile, isAotFolder } from './updateSymbolIndex.js';
@@ -60,7 +60,9 @@ export async function resolveModelFolder(model, context) {
60
60
  continue;
61
61
  }
62
62
  for (const pkg of packages) {
63
- if (!pkg.isDirectory())
63
+ // A package linked into the packages root (a junction or symlink to a repository)
64
+ // is not a "directory" to a Dirent; existsSync below follows the link.
65
+ if (!pkg.isDirectory() && !pkg.isSymbolicLink())
64
66
  continue;
65
67
  const candidate = path.join(root, pkg.name, model);
66
68
  if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory())
@@ -96,7 +98,7 @@ export function listModelFiles(folder) {
96
98
  walk(folder, false);
97
99
  return files;
98
100
  }
99
- export async function reindexModel(model, context) {
101
+ export async function reindexModel(model, context, options = {}) {
100
102
  const fail = (text) => ({ content: [{ type: 'text', text }], isError: true });
101
103
  // A Microsoft model is tens of thousands of files and changes only with a platform
102
104
  // update, which is what build-database is for.
@@ -115,12 +117,13 @@ export async function reindexModel(model, context) {
115
117
  const { symbolIndex } = context;
116
118
  const onDisk = listModelFiles(folder);
117
119
  const recorded = symbolIndex.getIndexedFileMtimes?.(model) ?? new Map();
118
- const firstPass = recorded.size === 0;
120
+ const since = options.unrecordedSince;
121
+ const firstPass = recorded.size === 0 && since === undefined;
119
122
  const changed = onDisk.filter(fp => {
120
123
  const was = recorded.get(fp.toLowerCase());
121
- if (was === undefined)
122
- return true;
123
124
  try {
125
+ if (was === undefined)
126
+ return since === undefined || fs.statSync(fp).mtimeMs > since;
124
127
  return fs.statSync(fp).mtimeMs !== was;
125
128
  }
126
129
  catch {
@@ -164,6 +167,9 @@ export async function reindexModel(model, context) {
164
167
  const failures = [];
165
168
  const names = [];
166
169
  for (const fp of [...changed, ...deleted]) {
170
+ // Types indexed without a parser finish in microtasks; yield so requests are served
171
+ // between files, however many changed.
172
+ await new Promise(resolve => setImmediate(resolve));
167
173
  const result = await indexOneFile(fp, context);
168
174
  if (result.isError)
169
175
  failures.push(result.text);
@@ -191,4 +197,90 @@ export async function reindexModel(model, context) {
191
197
  ...(failures.length > 0 && failures.length === changed.length + deleted.length ? { isError: true } : {}),
192
198
  };
193
199
  }
200
+ /** A file changed this shortly before the model's stamp is read again (clock skew, writes in flight). */
201
+ const STARTUP_TOLERANCE_MS = 60_000;
202
+ /**
203
+ * Bring the index in line with files changed while the server was not running (a git pull,
204
+ * a branch switch, a Visual Studio session), once, in the background after start-up.
205
+ *
206
+ * Runs reindexModel for each model, one at a time with a yield between models, so a
207
+ * request is never queued behind more than one model's walk. A model whose files are all
208
+ * indexed costs one directory walk and one stat per file. Returns one log line per model
209
+ * that changed, and never throws.
210
+ */
211
+ export async function reindexChangedModels(models, context) {
212
+ const index = context.symbolIndex;
213
+ // Only for a model with no stamp of its own (an index built before stamps existed):
214
+ // every write moves last_indexed_at, so it can hide an older change.
215
+ const fallback = Date.parse(index.getLastIndexedAt?.() ?? '');
216
+ const lines = [];
217
+ for (const model of models) {
218
+ await new Promise(resolve => setImmediate(resolve));
219
+ try {
220
+ const synced = Date.parse(index.getModelSyncedAt?.(model) ?? '');
221
+ const since = Number.isFinite(synced) ? synced : fallback;
222
+ if (!Number.isFinite(since))
223
+ continue;
224
+ const startedAt = new Date().toISOString();
225
+ const result = await reindexModel(model, context, { unrecordedSince: since - STARTUP_TOLERANCE_MS });
226
+ const text = result.content[0]?.text ?? '';
227
+ // A failed file stays unrecorded, so the stamp must not move past it.
228
+ if (!result.isError && !text.includes('file(s) failed'))
229
+ index.setModelSyncedAt?.(model, startedAt);
230
+ if (result.isError || !/re-indexed from/.test(text))
231
+ continue;
232
+ const indexed = /Indexed : (\d+)/.exec(text)?.[1] ?? '?';
233
+ const removed = /Removed : (\d+)/.exec(text)?.[1] ?? '?';
234
+ lines.push(`${model}: ${indexed} changed or new, ${removed} deleted`);
235
+ }
236
+ catch (err) {
237
+ lines.push(`${model}: skipped (${err instanceof Error ? err.message : err})`);
238
+ }
239
+ }
240
+ return lines;
241
+ }
242
+ /** Delay after start-up before the background pass, so it does not compete with the first requests. */
243
+ const STARTUP_REINDEX_DELAY_MS = 15_000;
244
+ /** At most this many models are checked at start-up. */
245
+ const STARTUP_REINDEX_MAX_MODELS = 20;
246
+ /**
247
+ * The custom models this workspace develops: the configured model, the models registered
248
+ * as custom at run time, and the CUSTOM_MODELS entries that are names (not masks).
249
+ */
250
+ export function workspaceCustomModels(configuredModel) {
251
+ const names = [
252
+ ...(configuredModel ? [configuredModel] : []),
253
+ ...getAutoDetectedCustomModels(),
254
+ ...getCustomModels().filter(m => !m.includes('*') && !m.startsWith('!')),
255
+ ];
256
+ const seen = new Set();
257
+ return names.filter(n => {
258
+ const key = n.toLowerCase();
259
+ if (seen.has(key) || !isCustomModel(n))
260
+ return false;
261
+ seen.add(key);
262
+ return true;
263
+ }).slice(0, STARTUP_REINDEX_MAX_MODELS);
264
+ }
265
+ /**
266
+ * Schedule reindexChangedModels once, STARTUP_REINDEX_DELAY_MS after start-up, unless
267
+ * REINDEX_CHANGED_ON_STARTUP=false. The timer is unref'd, so it never keeps the process alive.
268
+ */
269
+ export function scheduleStartupReindex(context, log, delayMs = STARTUP_REINDEX_DELAY_MS) {
270
+ if (process.env.REINDEX_CHANGED_ON_STARTUP?.trim().toLowerCase() === 'false')
271
+ return;
272
+ const timer = setTimeout(async () => {
273
+ try {
274
+ const configMgr = getConfigManager();
275
+ const configured = configMgr.getModelName() ?? (await configMgr.getAutoDetectedModelName());
276
+ const lines = await reindexChangedModels(workspaceCustomModels(configured), context);
277
+ for (const line of lines)
278
+ log(`Re-indexed files changed since the last index: ${line}`);
279
+ }
280
+ catch (err) {
281
+ log(`Start-up re-index skipped: ${err instanceof Error ? err.message : err}`);
282
+ }
283
+ }, delayMs);
284
+ timer.unref?.();
285
+ }
194
286
  //# sourceMappingURL=modelReindex.js.map
@@ -13,6 +13,23 @@ export declare function isAotFolder(segment: string): boolean;
13
13
  * when the path carries no AOT folder at all.
14
14
  */
15
15
  export declare function classifyAotFolder(aotFolder: string): XppSymbol['type'];
16
+ /**
17
+ * update_symbol_index as a client calls it: every filePath must be under a configured
18
+ * package root, because the file is read into the index and later reads answer from it.
19
+ * The server's own callers use updateSymbolIndexTool with paths they have checked.
20
+ */
21
+ export declare const updateSymbolIndexRequest: (params: any, context: XppServerContext) => Promise<{
22
+ content: {
23
+ type: string;
24
+ text: string;
25
+ }[];
26
+ isError: boolean;
27
+ } | {
28
+ content: {
29
+ type: string;
30
+ text: string;
31
+ }[];
32
+ }>;
16
33
  export declare const updateSymbolIndexTool: (params: any, context: XppServerContext) => Promise<{
17
34
  content: {
18
35
  type: string;
@@ -5,6 +5,7 @@ import { parseLabelFile } from '../../metadata/labelParser.js';
5
5
  import { renderMethodSignature } from '../../metadata/xppDeclaration.js';
6
6
  import { bridgeRefreshProvider } from '../../bridge/index.js';
7
7
  import { getLastRefreshStartedAt } from '../../bridge/debouncedRefresh.js';
8
+ import { assertReadRootAllowed } from '../../utils/pathContainment.js';
8
9
  // Tool registration (name, description, inputSchema) lives in
9
10
  // src/server/toolSchemas/updateSymbolIndex.ts — the single source of truth for tool
10
11
  // instructions. It is NOT in mcpServer.ts; that file only spreads the
@@ -200,6 +201,26 @@ async function refreshBridgeForBatch(context, filePaths) {
200
201
  return { note: `Bridge refresh skipped: ${e?.message ?? e}`, redundant: false };
201
202
  }
202
203
  }
204
+ /**
205
+ * update_symbol_index as a client calls it: every filePath must be under a configured
206
+ * package root, because the file is read into the index and later reads answer from it.
207
+ * The server's own callers use updateSymbolIndexTool with paths they have checked.
208
+ */
209
+ export const updateSymbolIndexRequest = async (params, context) => {
210
+ for (const filePath of normalizeFilePaths(params?.filePath)) {
211
+ const allowed = await assertReadRootAllowed(filePath);
212
+ if (!allowed.ok) {
213
+ return {
214
+ content: [{
215
+ type: 'text',
216
+ text: `❌ update_symbol_index: filePath rejected, nothing was indexed.\n${allowed.reason}`,
217
+ }],
218
+ isError: true,
219
+ };
220
+ }
221
+ }
222
+ return updateSymbolIndexTool(params, context);
223
+ };
203
224
  export const updateSymbolIndexTool = async (params, context) => {
204
225
  const filePaths = normalizeFilePaths(params?.filePath);
205
226
  const model = typeof params?.model === 'string' ? params.model.trim() : '';