d365fo-mcp 1.26.0 → 1.26.1

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.
package/dist/index.js CHANGED
@@ -9,7 +9,6 @@ import './bootstrapEnv.js';
9
9
  import { fileURLToPath } from 'url';
10
10
  import { dirname, resolve } from 'path';
11
11
  import express from 'express';
12
- import compression from 'compression';
13
12
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
14
13
  import { createXppMcpServer } from './server/mcpServer.js';
15
14
  import { createStreamableHttpTransport } from './server/transport.js';
@@ -23,7 +22,8 @@ import { initializeDatabase } from './database/download.js';
23
22
  import { initializeConfig, getConfigManager } from './utils/configManager.js';
24
23
  import { SERVER_MODE, LOCAL_TOOLS, TOOL_PROFILE, EXTRA_TOOLS, isToolEnabled } from './server/serverMode.js';
25
24
  import { TOOL_ANNOTATIONS } from './server/toolAnnotations.js';
26
- import { apiKeyAuth, authStartupError, resolveBindHost } from './middleware/apiKeyAuth.js';
25
+ import { authStartupError, resolveBindHost } from './middleware/apiKeyAuth.js';
26
+ import { installHttpMiddleware } from './middleware/httpPipeline.js';
27
27
  import { VERSION } from './version.js';
28
28
  import { setInitializeParams } from './utils/stdioSessionInfo.js';
29
29
  import { firstRunHint } from './server/firstRunHint.js';
@@ -842,14 +842,8 @@ async function main() {
842
842
  const app = express();
843
843
  // Trust proxy - required for Azure App Service (behind reverse proxy)
844
844
  app.set('trust proxy', 1);
845
- // Compress responses — JSON search results can be 50–200 KB;
846
- // gzip typically gives 70–80 % reduction and Azure egress billing benefits.
847
- app.use(compression());
848
- app.use(express.json());
849
- // API key authentication — enforced when API_KEY env var is set.
850
- // Must be after express.json() but before route handlers.
851
- // /health is excluded so Azure health probes still work unauthenticated.
852
- app.use(apiKeyAuth);
845
+ // Compression, API key check and body parsing, in that order.
846
+ installHttpMiddleware(app);
853
847
  // Health check endpoint — dynamic: reflects serverState at request time
854
848
  app.get('/health', (_req, res) => {
855
849
  const ready = serverState.isReady;
@@ -0,0 +1,14 @@
1
+ import { type Express } from 'express';
2
+ /**
3
+ * The middleware every HTTP request passes before a route sees it.
4
+ *
5
+ * The order is the contract. The API key is checked on headers alone, so it goes
6
+ * first: no byte of a request body is read for a caller who is not accepted.
7
+ *
8
+ * Request bodies are not decompressed (`inflate: false`, answered with 415).
9
+ * MCP requests are small JSON, and with no API_KEY, or with authentication
10
+ * delegated upstream, the check above lets everyone through, so a decompressor
11
+ * on the request path would be open to them.
12
+ */
13
+ export declare function installHttpMiddleware(app: Express): void;
14
+ //# sourceMappingURL=httpPipeline.d.ts.map
@@ -0,0 +1,23 @@
1
+ import compression from 'compression';
2
+ import express from 'express';
3
+ import { apiKeyAuth } from './apiKeyAuth.js';
4
+ /**
5
+ * The middleware every HTTP request passes before a route sees it.
6
+ *
7
+ * The order is the contract. The API key is checked on headers alone, so it goes
8
+ * first: no byte of a request body is read for a caller who is not accepted.
9
+ *
10
+ * Request bodies are not decompressed (`inflate: false`, answered with 415).
11
+ * MCP requests are small JSON, and with no API_KEY, or with authentication
12
+ * delegated upstream, the check above lets everyone through, so a decompressor
13
+ * on the request path would be open to them.
14
+ */
15
+ export function installHttpMiddleware(app) {
16
+ // Compress responses — JSON search results can be 50–200 KB;
17
+ // gzip typically gives 70–80 % reduction and Azure egress billing benefits.
18
+ app.use(compression());
19
+ // Enforced when API_KEY is set; /health stays open for Azure health probes.
20
+ app.use(apiKeyAuth);
21
+ app.use(express.json({ inflate: false }));
22
+ }
23
+ //# sourceMappingURL=httpPipeline.js.map
@@ -465,7 +465,21 @@ export async function getWorkspaceInfoTool(request, context) {
465
465
  `workspace's projects and version control. Check with the user that this setting is wanted ` +
466
466
  `before you write into such a model.`);
467
467
  }
468
- if (isPlaceholder) {
468
+ // A server nobody has set up has no model by design. The first-run hint in
469
+ // front of this result already tells the user what to do (run setup), so a
470
+ // second, contradicting instruction ("fix modelName in .mcp.json") would only
471
+ // compete with it.
472
+ const notSetUp = !!context.firstRunHint;
473
+ if (notSetUp) {
474
+ // Nothing to add — see notSetUp. Not "configuration looks valid" either.
475
+ }
476
+ else if (isPlaceholder && !modelName) {
477
+ const rawDetectedModel = await configManager.getRawAutoDetectedModelName();
478
+ lines.push(``, `⛔ CONFIGURATION PROBLEM — no model name is configured or detected.`, ``, `**YOU MUST STOP** and tell the user:`, `> The MCP server does not know which D365FO model to work on.`, rawDetectedModel
479
+ ? `> ✅ Auto-detected from .rnrproj: **${rawDetectedModel}** — set \`modelName\` to \`"${rawDetectedModel}"\`.`
480
+ : `> ⚠️ No .rnrproj was found — make sure the MCP server is running in the right directory.`, `>`, `> Please check that:`, `> 1. The MCP server is running in the correct workspace directory`, `> 2. The server's configuration (d365fo-mcp.json, or the .mcp.json / mcp.json entry) sets modelName`, `> 3. The projectPath points to a valid .rnrproj file`, `>`, `> Do you want to fix the configuration first, or continue with built-in tools (limited functionality)?`);
481
+ }
482
+ else if (isPlaceholder) {
469
483
  const rawDetectedModel = await configManager.getRawAutoDetectedModelName();
470
484
  const detectedHint = rawDetectedModel
471
485
  ? `> ✅ Auto-detected from .rnrproj: **${rawDetectedModel}**\n` +
@@ -24,6 +24,34 @@ export declare function normalizeElementType(raw: string): string;
24
24
  * caller will act on.
25
25
  */
26
26
  export declare function describeNonRun(output: string, targetName?: string): string;
27
+ /** How an xppbp process ended, when it did not end with exit code 0 (execFile's error fields). */
28
+ export interface XppbpFailure {
29
+ code?: number | string | null;
30
+ signal?: string | null;
31
+ killed?: boolean;
32
+ message?: string;
33
+ }
34
+ /**
35
+ * An xppbp run that broke off, as a sentence — or '' when it finished.
36
+ *
37
+ * "No findings" is a pass only when the checker reached the end. A crashed run
38
+ * prints no findings either, and with the exit code unread it came back as
39
+ * `✅ BP Check passed`.
40
+ *
41
+ * xppbp 7.0.7996.33 exited 0 on every completed run probed (with warnings, and
42
+ * with an "element not found" error), 1 on a rejected argument and 6 on a fatal
43
+ * error. A non-zero exit is still accepted when the run printed its tally AND
44
+ * reported something: those findings are real, and they cannot read as a pass.
45
+ */
46
+ export declare function describeFailedRun(output: string, failure?: XppbpFailure): string;
47
+ /**
48
+ * Does a run_bp_check reply say that something went unchecked? A refusal or a
49
+ * broken-off run starts with "❌", a batch marks the object, a build result puts
50
+ * the reply under its best-practices heading, and a diff with nothing in it never
51
+ * starts xppbp. Such a reply with no finding in it is no evidence of a clean
52
+ * object — the eval oracle must not score it as one.
53
+ */
54
+ export declare function replyLeavesBpUnchecked(reply: string): boolean;
27
55
  /** Elements xppbp reported as not compiled (its CompilerMetadataMissing warning). */
28
56
  export declare function uncompiledElements(output: string): string[];
29
57
  /**
@@ -157,6 +157,64 @@ export function describeNonRun(output, targetName) {
157
157
  }
158
158
  return '';
159
159
  }
160
+ /** Does the output report anything — a finding line, or a non-zero tally? */
161
+ function hasIssues(output) {
162
+ // xppbp emits either "BPError..."/XML <Diagnostic severity="error"> or
163
+ // "BestPractices Warning/Error: ..." — both count as a violation.
164
+ return /BPError|<Diagnostic|severity="error"|BestPractices (Warning|Error):/i.test(output)
165
+ || /severity\s*[:=]\s*error/i.test(output)
166
+ || /^Warnings:\s*[1-9]/m.test(output)
167
+ || /^Errors:\s*[1-9]/m.test(output);
168
+ }
169
+ /** The closing tally of a run that got to the end. */
170
+ const TALLY_PATTERN = /^\s*Errors:\s*\d+\s*$/m;
171
+ /** e.g. "MetadataProvider Fatal Error: No module with the name … could be found". */
172
+ const FATAL_LINE_PATTERN = /^\s*(?:\w+ )?Fatal Error:/m;
173
+ /**
174
+ * An xppbp run that broke off, as a sentence — or '' when it finished.
175
+ *
176
+ * "No findings" is a pass only when the checker reached the end. A crashed run
177
+ * prints no findings either, and with the exit code unread it came back as
178
+ * `✅ BP Check passed`.
179
+ *
180
+ * xppbp 7.0.7996.33 exited 0 on every completed run probed (with warnings, and
181
+ * with an "element not found" error), 1 on a rejected argument and 6 on a fatal
182
+ * error. A non-zero exit is still accepted when the run printed its tally AND
183
+ * reported something: those findings are real, and they cannot read as a pass.
184
+ */
185
+ export function describeFailedRun(output, failure) {
186
+ const how = !failure ? ''
187
+ : failure.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' ? 'xppbp printed more output than the server can hold, and was stopped'
188
+ : failure.killed ? 'xppbp was stopped before it finished (the time limit is 5 minutes per run)'
189
+ : typeof failure.code === 'number' ? `xppbp exited with code ${failure.code}`
190
+ : failure.signal ? `xppbp was terminated by ${failure.signal}`
191
+ : `xppbp could not be run (${failure.message ?? failure.code})`;
192
+ if (FATAL_LINE_PATTERN.test(output)) {
193
+ return `${how || 'xppbp finished'} after reporting a fatal error, so the check is incomplete.`;
194
+ }
195
+ if (failure && !(TALLY_PATTERN.test(output) && hasIssues(output))) {
196
+ return `${how} without a completed result, so the absence of findings below proves nothing.`;
197
+ }
198
+ if (!output.trim()) {
199
+ return 'xppbp printed nothing, so there is no evidence that any rule ran.';
200
+ }
201
+ return '';
202
+ }
203
+ /**
204
+ * Does a run_bp_check reply say that something went unchecked? A refusal or a
205
+ * broken-off run starts with "❌", a batch marks the object, a build result puts
206
+ * the reply under its best-practices heading, and a diff with nothing in it never
207
+ * starts xppbp. Such a reply with no finding in it is no evidence of a clean
208
+ * object — the eval oracle must not score it as one.
209
+ */
210
+ export function replyLeavesBpUnchecked(reply) {
211
+ const text = reply.replace(/^/, '').trim();
212
+ return text === ''
213
+ || text.startsWith('❌')
214
+ || text.startsWith('✅ Nothing to check')
215
+ || /^❌ BP Check\b|── ❌ NOT CHECKED|^⚠️ bpCheck requested but could not run/m.test(text)
216
+ || /^--- Best practices \(bpCheck=true\)[^\n]*\n❌/m.test(text);
217
+ }
160
218
  /** Elements xppbp reported as not compiled (its CompilerMetadataMissing warning). */
161
219
  export function uncompiledElements(output) {
162
220
  const names = new Set();
@@ -689,25 +747,28 @@ export const runBpCheckTool = async (params, context) => {
689
747
  ];
690
748
  // One entry per object; `null` is the unfiltered whole-model run.
691
749
  const runTargets = targets.length > 0 ? targets : [null];
692
- const combinedByTarget = await withOperationLock(`bp:${modelName}`, async () => {
750
+ const runs = await withOperationLock(`bp:${modelName}`, async () => {
693
751
  // The flag style is a property of the installed xppbp, not of the object:
694
752
  // once one works, later objects in the batch start from it instead of
695
753
  // paying the fallback chain again.
696
754
  let preferredStyle = 0;
697
- const outputs = [];
755
+ const results = [];
698
756
  for (const target of runTargets) {
699
757
  let combined = '';
758
+ let failure;
700
759
  for (let i = preferredStyle; i < styles.length; i++) {
701
760
  const args = styles[i].build(target);
702
761
  console.error(`[run_bp_check] Attempt ${i + 1} (${styles[i].label}) for ${selector(target)}: "${xppbpPath}" ${args.join(' ')}`);
703
762
  let stdout = '';
704
763
  let stderr = '';
764
+ failure = undefined;
705
765
  try {
706
766
  ({ stdout, stderr } = await tryXppbp(xppbpPath, args));
707
767
  }
708
768
  catch (e) {
709
769
  stdout = e.stdout ?? '';
710
770
  stderr = e.stderr ?? '';
771
+ failure = e;
711
772
  }
712
773
  combined = [stdout, stderr].filter(Boolean).join('\n').trim();
713
774
  if (!HELP_TEXT_PATTERN.test(combined) && combined !== '') {
@@ -715,10 +776,11 @@ export const runBpCheckTool = async (params, context) => {
715
776
  break;
716
777
  }
717
778
  }
718
- outputs.push(combined);
779
+ results.push({ output: combined, failure });
719
780
  }
720
- return outputs;
781
+ return results;
721
782
  });
783
+ const combinedByTarget = runs.map(r => r.output);
722
784
  // If the first target still shows help text, no flag style works on this
723
785
  // xppbp at all — report that once rather than per object.
724
786
  if (HELP_TEXT_PATTERN.test(combinedByTarget[0])) {
@@ -730,6 +792,15 @@ export const runBpCheckTool = async (params, context) => {
730
792
  isError: true
731
793
  };
732
794
  }
795
+ // Judged once, on xppbp's own output: a rejection it explains (describeNonRun),
796
+ // else a run that broke off (describeFailedRun).
797
+ const verdicts = runs.map((r, i) => {
798
+ const rejected = describeNonRun(r.output, runTargets[i]?.name);
799
+ return rejected
800
+ ? { reason: rejected, brokeOff: false }
801
+ : { reason: describeFailedRun(r.output, r.failure), brokeOff: true };
802
+ });
803
+ const nonRunByTarget = verdicts.map(v => v.reason);
733
804
  // Pipeline parity (bpPipelineParity.ts): the OperationalDomain/SubscriberAccessLevel
734
805
  // rules the pipeline's newer BP packages have and this xppbp lacks go INTO the output,
735
806
  // as detail lines, so every reader below (verdict, findings section, build summary)
@@ -740,19 +811,13 @@ export const runBpCheckTool = async (params, context) => {
740
811
  modelName,
741
812
  targets: runTargets,
742
813
  outputs: combinedByTarget,
743
- skip: combinedByTarget.map((o, i) => !!describeNonRun(o, runTargets[i]?.name)),
814
+ skip: nonRunByTarget.map(Boolean),
744
815
  indexFormAllLocal: db ? form => formDataSourcesAllLocal(form, db) : undefined,
745
816
  labelsCompiled: labelResult.success,
746
817
  parse: parseBpFindings,
747
818
  });
748
819
  for (let i = 0; i < combinedByTarget.length; i++)
749
820
  combinedByTarget[i] += parity.appended[i];
750
- // xppbp emits either "BPError..."/XML <Diagnostic severity="error"> or
751
- // "BestPractices Warning/Error: ..." — both count as a violation.
752
- const hasIssues = (output) => /BPError|<Diagnostic|severity="error"|BestPractices (Warning|Error):/i.test(output)
753
- || /severity\s*[:=]\s*error/i.test(output)
754
- || /^Warnings:\s*[1-9]/m.test(output)
755
- || /^Errors:\s*[1-9]/m.test(output);
756
821
  const header = `Model: ${modelName}` + (resolvedProjectPath ? `\nProject: ${resolvedProjectPath}` : '');
757
822
  // A clean xppbp run is routinely read as "the task is done". It is not a compile:
758
823
  // run f2e7b71a shipped a CoC method that violates SYS10028 with this line reading
@@ -772,7 +837,7 @@ export const runBpCheckTool = async (params, context) => {
772
837
  const dataDir = context?.symbolIndex?.dataDir;
773
838
  const perTarget = combinedByTarget.map(o => parseBpFindings(o));
774
839
  const baselineSound = !!dataDir
775
- && combinedByTarget.every((o, i) => !describeNonRun(o, runTargets[i]?.name)
840
+ && combinedByTarget.every((o, i) => !nonRunByTarget[i]
776
841
  && (perTarget[i].length > 0 || !hasIssues(o)));
777
842
  let view;
778
843
  if (baselineSound) {
@@ -788,12 +853,15 @@ export const runBpCheckTool = async (params, context) => {
788
853
  if (runTargets.length === 1) {
789
854
  const combined = combinedByTarget[0];
790
855
  const target = runTargets[0];
791
- const notRun = describeNonRun(combined, target?.name);
856
+ const notRun = nonRunByTarget[0];
792
857
  if (notRun) {
858
+ const headline = verdicts[0].brokeOff
859
+ ? '❌ BP Check did NOT complete — this is not a pass.'
860
+ : '❌ BP Check did NOT run — nothing was verified.';
793
861
  return {
794
862
  content: [{
795
863
  type: 'text',
796
- text: `❌ BP Check did NOT run — nothing was verified.\n\n${header}` +
864
+ text: `${headline}\n\n${header}` +
797
865
  (target ? `\nFilter: ${selector(target)}` : '') +
798
866
  `\n\n${notRun}\n\n${combined || '(no output)'}`,
799
867
  }],
@@ -823,8 +891,6 @@ export const runBpCheckTool = async (params, context) => {
823
891
  }
824
892
  // Batch: one preamble, findings grouped per object (#828).
825
893
  const { preamble, bodies } = splitSharedPreamble(combinedByTarget);
826
- // Not `.map(describeNonRun)` — that would pass the array index as the target name.
827
- const nonRunByTarget = combinedByTarget.map((output, i) => describeNonRun(output, runTargets[i]?.name));
828
894
  const notRunCount = nonRunByTarget.filter(Boolean).length;
829
895
  const issueCount = combinedByTarget.filter((o, i) => !nonRunByTarget[i]
830
896
  && (view ? freshOf(i).length > 0 : hasIssues(o))).length;
@@ -1035,25 +1035,29 @@ export async function handleGenerateSmartForm(args, symbolIndex) {
1035
1035
  }
1036
1036
  const targetPath = path.join(packagePath, resolvedModel, resolvedModel, 'AxForm', `${finalName}.xml`);
1037
1037
  const normalizedPath = targetPath.replace(/\//g, '\\');
1038
+ // normalizedPath is for the reply and the .rnrproj; the disk is reached through
1039
+ // the native path. Same string on Windows; elsewhere a backslash is a file-name
1040
+ // character, and writing to normalizedPath made one file in the working directory.
1041
+ const diskPath = targetPath;
1038
1042
  // Verify drive/root exists
1039
- const driveOrRoot = path.parse(normalizedPath).root;
1043
+ const driveOrRoot = path.parse(diskPath).root;
1040
1044
  if (driveOrRoot && !fs.existsSync(driveOrRoot)) {
1041
1045
  throw new Error(`❌ Drive or root path does not exist: ${driveOrRoot}\n\n` +
1042
1046
  `Attempting to create: ${normalizedPath}\n\n` +
1043
1047
  `Update "packagePath" in .mcp.json to match your actual D365FO installation.`);
1044
1048
  }
1045
- const dir = path.dirname(normalizedPath);
1049
+ const dir = path.dirname(diskPath);
1046
1050
  if (!fs.existsSync(dir)) {
1047
1051
  fs.mkdirSync(dir, { recursive: true });
1048
1052
  }
1049
1053
  // Only a file this call brings into being may later be deleted by undo.
1050
- const existedBefore = fs.existsSync(normalizedPath);
1051
- fs.writeFileSync(normalizedPath, normalizeD365Xml(xml), 'utf-8');
1054
+ const existedBefore = fs.existsSync(diskPath);
1055
+ fs.writeFileSync(diskPath, normalizeD365Xml(xml), 'utf-8');
1052
1056
  console.log(`[generateSmartForm] Created file: ${normalizedPath}`);
1053
1057
  // Tell the index about it, the way every create/modify path does.
1054
1058
  // Without this the object is invisible to `search` — which is now answered
1055
1059
  // from the index for untyped queries — in the very session that created it.
1056
- await upsertWrittenFileIntoIndex(normalizedPath, { symbolIndex });
1060
+ await upsertWrittenFileIntoIndex(diskPath, { symbolIndex });
1057
1061
  // Add to Visual Studio project if a projectPath is known
1058
1062
  let projectMessage = '';
1059
1063
  let addedToProject;
@@ -1035,22 +1035,26 @@ export async function handleGenerateSmartReport(args, symbolIndex, bridge) {
1035
1035
  for (const obj of generatedObjects) {
1036
1036
  const targetPath = path.join(pkgPath, resolvedModel, resolvedModel, obj.aotFolder, `${obj.objectName}.xml`);
1037
1037
  const normalizedPath = targetPath.replace(/\//g, '\\');
1038
- const dir = path.dirname(normalizedPath);
1038
+ // normalizedPath is for the reply and the .rnrproj; the disk is reached through
1039
+ // the native path. Same string on Windows; elsewhere a backslash is a file-name
1040
+ // character, and writing to normalizedPath made one file in the working directory.
1041
+ const diskPath = targetPath;
1042
+ const dir = path.dirname(diskPath);
1039
1043
  if (!fs.existsSync(dir)) {
1040
1044
  fs.mkdirSync(dir, { recursive: true });
1041
1045
  }
1042
1046
  // Guard: refuse to overwrite existing table files (would destroy existing methods, fields, etc.)
1043
- if (obj.objectType === 'table' && fs.existsSync(normalizedPath)) {
1047
+ if (obj.objectType === 'table' && fs.existsSync(diskPath)) {
1044
1048
  results.push(`⚠️ ${obj.objectType}: ${normalizedPath} — SKIPPED (file already exists, would destroy existing content). Use \`d365fo_file(action="modify")\` to modify existing tables.`);
1045
1049
  log(`Skipped existing table: ${normalizedPath}`);
1046
1050
  continue;
1047
1051
  }
1048
1052
  // Only a file this call brings into being may later be deleted by undo.
1049
- const existedBefore = fs.existsSync(normalizedPath);
1050
- fs.writeFileSync(normalizedPath, normalizeD365Xml(obj.content), 'utf-8');
1053
+ const existedBefore = fs.existsSync(diskPath);
1054
+ fs.writeFileSync(diskPath, normalizeD365Xml(obj.content), 'utf-8');
1051
1055
  // Same reason as the other generators: an object the index never hears
1052
1056
  // about is missing from the untyped `search` that now answers from it.
1053
- await upsertWrittenFileIntoIndex(normalizedPath, { symbolIndex });
1057
+ await upsertWrittenFileIntoIndex(diskPath, { symbolIndex });
1054
1058
  let projectMsg = '';
1055
1059
  let addedToProject;
1056
1060
  if (effectiveProjectPath) {
@@ -920,6 +920,10 @@ export async function handleGenerateSmartTable(args, symbolIndex, bridge) {
920
920
  const targetPath = path.join(packagePath, resolvedModel, resolvedModel, 'AxTable', `${finalName}.xml`);
921
921
  // Normalize path to Windows format (backslashes) for consistency
922
922
  const normalizedPath = targetPath.replace(/\//g, '\\');
923
+ // normalizedPath is for the reply and the .rnrproj; the disk is reached through
924
+ // the native path. Same string on Windows; elsewhere a backslash is a file-name
925
+ // character, and writing to normalizedPath made one file in the working directory.
926
+ const diskPath = targetPath;
923
927
  // Reject Windows paths when running on non-Windows (e.g. Linux Azure proxy)
924
928
  if (process.platform !== 'win32' && /^[A-Z]:\\/.test(normalizedPath)) {
925
929
  throw new Error(`❌ Cannot create D365FO file on non-Windows system!\n\n` +
@@ -929,30 +933,30 @@ export async function handleGenerateSmartTable(args, symbolIndex, bridge) {
929
933
  `Run the MCP server locally on the D365FO Windows VM.`);
930
934
  }
931
935
  // Verify drive/root exists before attempting recursive mkdir
932
- const driveOrRoot = path.parse(normalizedPath).root;
936
+ const driveOrRoot = path.parse(diskPath).root;
933
937
  if (driveOrRoot && !fs.existsSync(driveOrRoot)) {
934
938
  throw new Error(`❌ Drive or root path does not exist: ${driveOrRoot}\n\n` +
935
939
  `Attempting to create: ${normalizedPath}\n\n` +
936
940
  `Update "packagePath" in .mcp.json to match your actual D365FO installation.`);
937
941
  }
938
942
  // Create directory if needed
939
- const dir = path.dirname(normalizedPath);
943
+ const dir = path.dirname(diskPath);
940
944
  if (!fs.existsSync(dir)) {
941
945
  fs.mkdirSync(dir, { recursive: true });
942
946
  }
943
947
  // Guard: refuse to overwrite an existing table file (would destroy existing methods, fields, etc.)
944
- if (fs.existsSync(normalizedPath)) {
948
+ if (fs.existsSync(diskPath)) {
945
949
  throw new Error(`⚠️ Table "${finalName}" already exists at:\n${normalizedPath}\n\n` +
946
950
  `\`generate_object(mode="scaffold", objectType="table")\` is for **NEW** tables only.\n` +
947
951
  `Use \`d365fo_file(action="modify")\` to add fields, methods, or indexes to an existing table.\n` +
948
952
  `Use \`get_object_info(objectType="table", name="${finalName}")\` to inspect the current structure.`);
949
953
  }
950
954
  // Write file
951
- fs.writeFileSync(normalizedPath, normalizeD365Xml(xml), 'utf-8');
955
+ fs.writeFileSync(diskPath, normalizeD365Xml(xml), 'utf-8');
952
956
  // Tell the index about it, the way every create/modify path does.
953
957
  // Without this the object is invisible to `search` — which is now answered
954
958
  // from the index for untyped queries — in the very session that created it.
955
- await upsertWrittenFileIntoIndex(normalizedPath, { symbolIndex });
959
+ await upsertWrittenFileIntoIndex(diskPath, { symbolIndex });
956
960
  console.log(`[generateSmartTable] Created file: ${normalizedPath}`);
957
961
  // Add to Visual Studio project if a projectPath is known
958
962
  let projectMessage = '';
@@ -1085,6 +1085,13 @@ export async function handleCreateD365File(request, context, outcome) {
1085
1085
  logPrefix: '[create_d365fo_file]',
1086
1086
  });
1087
1087
  const { basePath, modelPath, normalizedFullPath } = target;
1088
+ // normalizedFullPath is what the user and the .rnrproj see: backslashes, as
1089
+ // on the VM. The disk is reached through the native path. On Windows the two
1090
+ // are the same string (path.join already uses backslashes there). On any
1091
+ // other OS a backslash is an ordinary file-name character, so writing to
1092
+ // normalizedFullPath made one file in the current directory, named after the
1093
+ // whole path, instead of the file under the metadata root.
1094
+ const diskPath = target.fullPath;
1088
1095
  // A package name passed as modelName resolves to the package's one model:
1089
1096
  // every step from here (bridge, project, index) works on that model.
1090
1097
  actualModelName = target.modelName;
@@ -1092,7 +1099,7 @@ export async function handleCreateD365File(request, context, outcome) {
1092
1099
  if (outcome)
1093
1100
  outcome.filePath = normalizedFullPath;
1094
1101
  // Ensure directory exists (create if needed)
1095
- const directory = path.dirname(normalizedFullPath);
1102
+ const directory = path.dirname(diskPath);
1096
1103
  // Verify drive/root exists before attempting recursive mkdir.
1097
1104
  // path.parse().root works on Windows but returns '' for Windows-style paths on POSIX,
1098
1105
  // so we extract the drive letter with a regex as a fallback.
@@ -1132,7 +1139,7 @@ export async function handleCreateD365File(request, context, outcome) {
1132
1139
  // Check if file already exists
1133
1140
  let fileExisted = false;
1134
1141
  try {
1135
- await fs.access(normalizedFullPath);
1142
+ await fs.access(diskPath);
1136
1143
  fileExisted = true;
1137
1144
  }
1138
1145
  catch {
@@ -1147,7 +1154,7 @@ export async function handleCreateD365File(request, context, outcome) {
1147
1154
  // returned only "already exists", forcing repeated read_file calls.
1148
1155
  let existingContent = '';
1149
1156
  try {
1150
- existingContent = await fs.readFile(normalizedFullPath, 'utf-8');
1157
+ existingContent = await fs.readFile(diskPath, 'utf-8');
1151
1158
  }
1152
1159
  catch { /* unreadable — fall through with no summary */ }
1153
1160
  let existingSummary = '';
@@ -1857,7 +1864,7 @@ export async function handleCreateD365File(request, context, outcome) {
1857
1864
  // classes, is refused. A bare name passes an incremental build and fails the pipeline's full
1858
1865
  // one (formDataMethodGate.ts).
1859
1866
  if (args.objectType === 'form' || args.objectType === 'form-extension') {
1860
- const existing = args.overwrite ? await fs.readFile(normalizedFullPath, 'utf-8').catch(() => null) : null;
1867
+ const existing = args.overwrite ? await fs.readFile(diskPath, 'utf-8').catch(() => null) : null;
1861
1868
  const dm = await gateFormDataMethods(xmlContent, args.objectType, finalObjectName, context?.symbolIndex, existing);
1862
1869
  if (dm.blocking.length > 0) {
1863
1870
  return {
@@ -1888,7 +1895,7 @@ export async function handleCreateD365File(request, context, outcome) {
1888
1895
  }
1889
1896
  // Write file matching D365FO convention: no BOM, CRLF, no trailing newline
1890
1897
  try {
1891
- await timer.time('xml write', () => writeFileAtomic(normalizedFullPath, normalizeD365Xml(xmlContent)));
1898
+ await timer.time('xml write', () => writeFileAtomic(diskPath, normalizeD365Xml(xmlContent)));
1892
1899
  }
1893
1900
  catch (writeError) {
1894
1901
  console.error(`[create_d365fo_file] Failed to write file:`, writeError);
@@ -1898,17 +1905,17 @@ export async function handleCreateD365File(request, context, outcome) {
1898
1905
  throw new Error(`Failed to write file to ${normalizedFullPath}.\n\n` +
1899
1906
  `Possible causes:\n` +
1900
1907
  `1. Drive K:\\ does not exist (running on Linux/Mac? Use packagePath parameter to override)\n` +
1901
- `2. Directory ${path.dirname(normalizedFullPath)} is not accessible\n` +
1908
+ `2. Directory ${directory} is not accessible\n` +
1902
1909
  `3. Insufficient permissions\n\n` +
1903
1910
  `Original error: ${errorMessage}`);
1904
1911
  }
1905
1912
  throw writeError;
1906
1913
  }
1907
1914
  // Verify file was written
1908
- const stats = await fs.stat(normalizedFullPath);
1915
+ const stats = await fs.stat(diskPath);
1909
1916
  const fileSizeKb = (stats.size / 1024).toFixed(1);
1910
1917
  console.error(`[create_d365fo_file] ✅ Written: ${normalizedFullPath} (${fileSizeKb} KB)`);
1911
- const createTagsNote = await applyCreateTags(normalizedFullPath, args.properties);
1918
+ const createTagsNote = await applyCreateTags(diskPath, args.properties);
1912
1919
  // This path paid for the rebuild TWICE: once here on the response path, and
1913
1920
  // again inside the fire-and-forget bridgeValidateAfterWrite() below, which
1914
1921
  // already goes through the same coalescer before reading the object back.
@@ -2032,9 +2039,9 @@ export async function handleCreateD365File(request, context, outcome) {
2032
2039
  }
2033
2040
  // Index the new object in-process — see the bridge paths above. Timed like
2034
2041
  // the bridge path's, which has named its phases since the same audit.
2035
- const indexNote = await timer.time('symbol index upsert', () => upsertWrittenFileIntoIndex(normalizedFullPath, context));
2042
+ const indexNote = await timer.time('symbol index upsert', () => upsertWrittenFileIntoIndex(diskPath, context));
2036
2043
  // Verify the write — see the bridge paths above.
2037
- const verifyNote = renderWriteVerification(await timer.time('write verification', () => verifyWrittenFile(normalizedFullPath, args.addToProject ? projectPathToUse : undefined, membershipOf(args.objectType, finalObjectName, actualModelName))));
2044
+ const verifyNote = renderWriteVerification(await timer.time('write verification', () => verifyWrittenFile(diskPath, args.addToProject ? projectPathToUse : undefined, membershipOf(args.objectType, finalObjectName, actualModelName))));
2038
2045
  const bpNote = await timer.time('inline BP check', () => runInlineBpCheck(args.bpCheck, args.objectType, finalObjectName, context));
2039
2046
  // Offline X++ rules on the source as written. A create hands over the whole
2040
2047
  // class, so the class-scoped rules (COC004, COC005) apply here — the cheap
@@ -2042,13 +2049,13 @@ export async function handleCreateD365File(request, context, outcome) {
2042
2049
  const xppRuleNote = validateWrittenXpp(sourceAsWritten(args.sourceCode, finalObjectName));
2043
2050
  // The scalar properties the caller passed, against the file (see the bridge
2044
2051
  // path). Keys the data-entity note below already names are left to that note.
2045
- const readBackNote = await timer.time('read-back comparison', () => verifyWriteIntent(normalizedFullPath, createIntentFor(args.objectType, args.properties, args.objectType === 'data-entity'
2052
+ const readBackNote = await timer.time('read-back comparison', () => verifyWriteIntent(diskPath, createIntentFor(args.objectType, args.properties, args.objectType === 'data-entity'
2046
2053
  ? findIgnoredEntityProperties(args.properties)
2047
2054
  : [])));
2048
2055
  // An entity with data management enabled names a staging table: create it now,
2049
2056
  // through this same handler, so the next build finds it (stagingTableProvisioning.ts).
2050
2057
  const stagingNote = args.objectType === 'data-entity'
2051
- ? await timer.time('staging table', () => provisionStagingTable({ entityName: finalObjectName, entityPath: normalizedFullPath, modelName: actualModelName, args }, context, handleCreateD365File))
2058
+ ? await timer.time('staging table', () => provisionStagingTable({ entityName: finalObjectName, entityPath: diskPath, modelName: actualModelName, args }, context, handleCreateD365File))
2052
2059
  : '';
2053
2060
  // Return success message with file path
2054
2061
  return {
@@ -292,7 +292,12 @@ export async function handleDeleteD365File(request, context) {
292
292
  // The folder is derived from the deleted object's own path — it is the
293
293
  // sibling of its Ax<Type> folder — which also gets the <Package> segment
294
294
  // right for a package != model layout without re-resolving anything.
295
- const listsFolder = path.win32.join(path.win32.dirname(path.win32.dirname(filePath)), 'AxIgnoreDiagnosticList');
295
+ // path.win32.dirname slices and keeps the path's own separators, which is
296
+ // what reads a K:\ path on any host. path.win32.join would turn a native
297
+ // POSIX path into backslashes, and off Windows readdir would then find no
298
+ // folder and skip the cleanup without a word: join with the path's own.
299
+ const sep = filePath.includes('\\') ? '\\' : '/';
300
+ const listsFolder = `${path.win32.dirname(path.win32.dirname(filePath))}${sep}AxIgnoreDiagnosticList`;
296
301
  const prefixes = suppressionPathSegmentsForObjectType(objectType, axFolder)
297
302
  .map(segment => `dynamics://${segment}/${resolvedName}`);
298
303
  const listFiles = (await fs.readdir(listsFolder).catch(() => []))
@@ -300,7 +305,7 @@ export async function handleDeleteD365File(request, context) {
300
305
  const removedMonikers = [];
301
306
  const cleanedFiles = [];
302
307
  for (const entry of listFiles) {
303
- const listPath = path.win32.join(listsFolder, entry);
308
+ const listPath = `${listsFolder}${sep}${entry}`;
304
309
  const raw = await fs.readFile(listPath, 'utf-8');
305
310
  const content = raw.replace(/^/, '').replace(/\r\n/g, '\n');
306
311
  const { xml, removed } = removeDiagnosticSuppressionsByPathPrefix(content, prefixes);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "d365fo-mcp",
3
3
  "mcpName": "io.github.dynamics365ninja/d365fo-mcp-server",
4
- "version": "1.26.0",
4
+ "version": "1.26.1",
5
5
  "description": "MCP Server for X++ Code Completion in D365 Finance & Operations",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",