diff --git a/CHANGELOG.md b/CHANGELOG.md index 6750489..b78f4a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this ### Fixed - Standalone CLI breakpoint tools remain usable between debug sessions. Adding, removing, and clearing breakpoints after termination, stopping, disposal, or failed startup no longer try to synchronize with an inactive adapter; saved changes are applied on the next launch (#161). +- A stop in a virtual document now reports its source location. `fileFullPath` is the document URI in the form the breakpoint tools accept, alongside the file name, current line, and following lines. +- `remove_breakpoint` finds a breakpoint in a virtual document whether its URI is written with literal spaces or percent-encoded, and `list_breakpoints` shows the decoded file name. +- `add_breakpoint` and `add_logpoint` accept a virtual document that cannot be opened yet instead of failing. The line is then not checked, and the result says so. Business Central serves a `.dal` source only once its session has stopped, which made it impossible to set a breakpoint there before the first stop. ### Added +- Breakpoint, logpoint, and removal tools now support VS Code virtual-document URIs, including Business Central `al-preview:` `.dal` sources. An optional `workingDirectory` selects the correct workspace when multiple editor windows are open. - **Claude Code auto-registration** - Claude Code is now offered in the agent selection popup and configured via `~/.claude.json`'s user-scope `mcpServers` field. Claude Desktop connects via its Custom Connector UI instead of a static config file; the README's manual configuration section covers both. ## [2.4.4] - 2026-10-25 diff --git a/README.md b/README.md index 824cd80..ddcc40e 100644 --- a/README.md +++ b/README.md @@ -84,9 +84,9 @@ DebugMCP is an MCP server that gives AI coding agents full control over the VS C | **restart_debugging** | Restart the current debug session; a fresh stop without acknowledgement returns an explicit completion-unconfirmed result, not confirmed success | None | | **get_debug_status** | Read paused/running/no-session status, the active session ID, and selected-frame details when paused; optionally wait for a pause | `waitForPauseSeconds` (optional, 0-600; bounded by the operation timeout) | | **get_debug_output** | Read captured output for one session; requires user-enabled capture and at least one filter | `sessionId` (required)
`prefix` and/or `category` (required filter; both are ANDed)
`cursor` (optional)
`limit` (optional, 1-100) | -| **add_breakpoint** | Add a breakpoint at a specific line (optionally conditional) | `fileFullPath` (required)
`line` (required, 1-based)
`condition` (optional) | -| **add_logpoint** | Add a logpoint that logs a message (instead of pausing) when a line is reached | `fileFullPath` (required)
`line` (required, 1-based)
`logMessage` (required, `{expr}` interpolated)
`condition` (optional) | -| **remove_breakpoint** | Remove a breakpoint from a specific line | `fileFullPath` (required)
`line` (required) | +| **add_breakpoint** | Add a breakpoint at a specific line (optionally conditional) | `fileFullPath` (required; path or virtual URI)
`workingDirectory` (optional; identifies the window for virtual URIs)
`line` (required, 1-based)
`condition` (optional) | +| **add_logpoint** | Add a logpoint that logs a message (instead of pausing) when a line is reached | `fileFullPath` (required; path or virtual URI)
`workingDirectory` (optional; identifies the window for virtual URIs)
`line` (required, 1-based)
`logMessage` (required, `{expr}` interpolated)
`condition` (optional) | +| **remove_breakpoint** | Remove a breakpoint from a specific line | `fileFullPath` (required; path or virtual URI)
`workingDirectory` (optional; identifies the window for virtual URIs)
`line` (required) | | **clear_all_breakpoints** | Remove all breakpoints at once | None | | **list_breakpoints** | List all active breakpoints | None | | **list_variable_names** | List names and types of variables in scope, without reading any values | `scope` (optional: 'local', 'global', 'all') | @@ -275,6 +275,23 @@ DebugMCP supports debugging for the following languages with their respective VS | **PHP** | [PHP Debug](https://marketplace.visualstudio.com/items?itemName=xdebug.php-debug) | `.php` | ✅ Fully Supported | | **Ruby** | [Ruby](https://marketplace.visualstudio.com/items?itemName=Shopify.ruby-lsp) | `.rb` | ✅ Fully Supported | | **C#/.NET** | [C#](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) | `.cs`, `.csproj` | ✅ Fully Supported | +| **AL (Business Central)** | [AL Language](https://marketplace.visualstudio.com/items?itemName=ms-dynamics-smb.al) | `.al`, virtual `.dal` | ✅ Supported with an AL launch configuration | + +### Virtual source documents + +Breakpoint tools accept native filesystem paths and VS Code virtual-document URIs. This +supports generated or downloaded sources that a language extension exposes without a local +file, including Business Central dependency objects such as +`al-preview://AlLang/.../Table/18/Customer.dal`. When multiple editor windows are open, +pass `workingDirectory` with the virtual URI so DebugMCP routes the operation to the correct +workspace. + +When execution stops in a virtual document, the debug state reports the same URI as +`fileFullPath`, so it can be passed back to the breakpoint tools unchanged. + +Some debuggers serve a virtual source only once the session has stopped. A breakpoint can +still be set in it beforehand: the line is not validated in that case, and the tool result +says so. ## Configuration diff --git a/docs/architecture/debugMCPServer.md b/docs/architecture/debugMCPServer.md index 0b58395..2f76ed5 100644 --- a/docs/architecture/debugMCPServer.md +++ b/docs/architecture/debugMCPServer.md @@ -75,6 +75,8 @@ extension. To avoid debugging the wrong workspace when several windows are open: operation to that window's `ControlServer`. The target is cached per session so hint-less follow-ups (step/continue/inspect) reach the same window. If the router window closes, a worker window takes over the port on retry. +- Breakpoint tools also accept virtual source URIs. A sole registered window is unambiguous; + with multiple windows, callers provide the optional `workingDirectory` routing hint. `DebugMCPServer` builds one handler **per MCP session** via a handler factory, which is what lets concurrent agent sessions drive debuggers in different repos simultaneously. @@ -142,7 +144,7 @@ error wins: | `continue_execution` | Continue to next breakpoint | | `pause_execution` | Interrupt a running program (no breakpoint needed) | | `restart_debugging` | Restart session | -| `add/remove_breakpoint` | Breakpoint management | +| `add/remove_breakpoint` | Breakpoint management for local paths and virtual source URIs | | `clear_all_breakpoints` | Remove all breakpoints | | `list_breakpoints` | List active breakpoints | | `get_variables_values` | Read the values of specifically named variables | diff --git a/docs/architecture/debugState.md b/docs/architecture/debugState.md index 82d0566..6b67652 100644 --- a/docs/architecture/debugState.md +++ b/docs/architecture/debugState.md @@ -22,7 +22,7 @@ Debugging operations are asynchronous - the debugger takes time to execute and u | `sessionActive` | `boolean` | Whether a debug session exists, running or stopped | | `paused` | `boolean \| null` | Observed execution state, or `null` when unobserved | | `stopSequence` | `number \| null` | Internal executor-local stopped-event marker, independent of frames and source | -| `fileFullPath` | `string \| null` | Full path to current file | +| `fileFullPath` | `string \| null` | Full path to current file, or its URI for a virtual document | | `fileName` | `string \| null` | Just the filename | | `currentLine` | `number \| null` | 1-based line number | | `currentLineContent` | `string \| null` | Content of current line | diff --git a/docs/architecture/debuggingExecutor.md b/docs/architecture/debuggingExecutor.md index a9450aa..f6a695a 100644 --- a/docs/architecture/debuggingExecutor.md +++ b/docs/architecture/debuggingExecutor.md @@ -161,6 +161,13 @@ necessarily the physical stop at the top of the stack. The call stack retains adapter order. If the selected frame is absent from the bounded stack response, its name and source remain unavailable rather than borrowing top-frame metadata. +A frame's source path may be a native path or a URI. Adapters for virtual +documents (for example Business Central `al-preview:` `.dal` sources) report a +URI; it is opened through its content provider and reported as the canonical +URI string, the same form `getBreakpoints()` uses and the breakpoint tools +accept. `normalizeSourceLocation()` maps a caller-supplied path or URI to that +form, so different spellings of one URI compare equal. + Frame/thread context is populated before source lookup. A missing or unreadable source does not discard that context or mean that execution is running. Paused status is also independent of frames: an observed stop with an empty stack still diff --git a/docs/architecture/debuggingHandler.md b/docs/architecture/debuggingHandler.md index a301640..d48beef 100644 --- a/docs/architecture/debuggingHandler.md +++ b/docs/architecture/debuggingHandler.md @@ -20,6 +20,7 @@ Debugging is inherently asynchronous - when you step over a line, the debugger t ## Responsibility - Orchestrate debugging operations (start, stop, step, breakpoints) +- Preserve language-extension virtual source URIs when opening documents and setting breakpoints - Detect when debugger state has meaningfully changed after commands - Format debug state into human/AI-readable responses - Recursively format explicitly requested structs and arrays @@ -111,6 +112,24 @@ successful DAP restart response. Actual command failures received before the result still propagate. A later rejection after an unconfirmed result is logged; the underlying request is not cancelled. Polling stops when the call returns. +### Virtual source documents + +Breakpoint and logpoint locations may be native paths or VS Code virtual-document URIs. +`src/utils/vscodeSourceUri.ts` keeps custom schemes intact instead of converting them into malformed +`file:` URIs. This is required for language-extension sources such as Business Central `.dal` +documents served through the `al-preview:` scheme. + +The handler stays host-neutral and does not parse URIs itself; it only uses the text helpers in +`src/utils/sourceUri.ts`, which are also bundled into the standalone CLI. Before looking up a breakpoint +to remove, it asks the executor for the canonical form of the requested location, so a URI +written with a literal space matches the same URI written with `%20`. Breakpoint listings +show the decoded file name. + +A breakpoint's line is validated against the source when it can be read. A virtual document +that cannot be opened yet (Business Central serves `.dal` sources only once the session has +stopped) still takes the breakpoint, with a note that the line was not checked; a missing file +on disk remains an error. + ### Root Cause Analysis When debugging stops, the handler prompts AI agents to consider whether they found the root cause or just a symptom, encouraging deeper investigation. diff --git a/src/debugMCPServer.ts b/src/debugMCPServer.ts index 2f46447..1f3bf93 100644 --- a/src/debugMCPServer.ts +++ b/src/debugMCPServer.ts @@ -258,11 +258,12 @@ export class DebugMCPServer { server.registerTool('add_breakpoint', { description: 'Set a breakpoint to pause execution at a critical line of code. Breakpoints let you inspect variables and control flow at exact moments.', inputSchema: { - fileFullPath: z.string().describe('Full path to the file'), + fileFullPath: z.string().describe('Full path or VS Code virtual-document URI of the source file'), + workingDirectory: z.string().optional().describe('Workspace directory used to select the correct VS Code window. Required for a virtual-document URI when multiple windows are open.'), line: z.number().int().describe('Line number (1-based) where the breakpoint should be set'), condition: z.string().optional().describe('Optional condition expression. When provided, execution only pauses if this expression evaluates to true at the breakpoint location.'), }, - }, async (args: { fileFullPath: string; line: number; condition?: string }) => + }, async (args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }) => this.runTool('add_breakpoint', () => debuggingHandler.handleAddBreakpoint(args))); // Read captured output @@ -281,22 +282,24 @@ export class DebugMCPServer { server.registerTool('add_logpoint', { description: 'Add a logpoint: a breakpoint that logs a message instead of pausing execution. Ideal for tracing values across many iterations or hot paths without stopping, or where a hard pause would distort timing. Embed expressions in curly braces to interpolate runtime values, e.g. "user id={user.id}".', inputSchema: { - fileFullPath: z.string().describe('Full path to the file'), + fileFullPath: z.string().describe('Full path or VS Code virtual-document URI of the source file'), + workingDirectory: z.string().optional().describe('Workspace directory used to select the correct VS Code window. Required for a virtual-document URI when multiple windows are open.'), line: z.number().int().describe('Line number (1-based) where the logpoint should be set'), logMessage: z.string().describe('Message to log when the line is reached. Wrap expressions in {curly braces} to interpolate runtime values.'), condition: z.string().optional().describe('Optional condition expression. When provided, the message is only logged if this expression evaluates to true.'), }, - }, async (args: { fileFullPath: string; line: number; logMessage: string; condition?: string }) => + }, async (args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }) => this.runTool('add_logpoint', () => debuggingHandler.handleAddLogpoint(args))); // Remove breakpoint tool server.registerTool('remove_breakpoint', { description: 'Remove a breakpoint that is no longer needed.', inputSchema: { - fileFullPath: z.string().describe('Full path to the file'), + fileFullPath: z.string().describe('Full path or VS Code virtual-document URI of the source file'), + workingDirectory: z.string().optional().describe('Workspace directory used to select the correct VS Code window. Required for a virtual-document URI when multiple windows are open.'), line: z.number().describe('Line number (1-based)'), }, - }, async (args: { fileFullPath: string; line: number }) => + }, async (args: { fileFullPath: string; workingDirectory?: string; line: number }) => this.runTool('remove_breakpoint', () => debuggingHandler.handleRemoveBreakpoint(args))); // Clear all breakpoints tool diff --git a/src/debuggingExecutor.ts b/src/debuggingExecutor.ts index a2b8fc7..9e66af0 100644 --- a/src/debuggingExecutor.ts +++ b/src/debuggingExecutor.ts @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. import * as vscode from 'vscode'; +import * as fs from 'node:fs'; import { DebugState, StackFrame } from './debugState'; import { DebugBreakpoint, DebugConfiguration, DebugSessionInfo } from './debugTypes'; import { logger } from './utils/logger'; @@ -8,6 +9,8 @@ import { withTimeout } from './utils/withTimeout'; import { getDebugStartupContext, startDebuggingWithDiagnostics } from './utils/debugStartup'; import { DebugSessionTracker } from './utils/debugSessionTracker'; import { DebugOutputBuffer, IDebugOutputQuery } from './utils/debugOutputBuffer'; +import { isSourceUri } from './utils/sourceUri'; +import { toSourceText, toSourceUri } from './utils/vscodeSourceUri'; /** * Outcome of dispatching `testing.debugAtCursor`. @@ -54,6 +57,8 @@ export interface IDebuggingExecutor { getActiveFrameId?(): number | undefined; getDebugOutput?(query: IDebugOutputQuery): ReturnType; waitForDebugSessionReady(timeoutMs: number, signal?: AbortSignal): Promise<'stopped' | 'terminated' | 'timeout' | 'no-session' | 'attached'>; + getFileLineCount?(fileFullPath: string): Promise; + normalizeSourceLocation?(fileFullPath: string): string; dispose?(): Promise | void; } @@ -94,6 +99,29 @@ export class DebuggingExecutor implements IDebuggingExecutor { ); } + /** + * Count the lines of a source file. Virtual documents are read through + * VS Code so their content provider is used; files on disk are read directly. + */ + public async getFileLineCount(fileFullPath: string): Promise { + if (isSourceUri(fileFullPath)) { + const document = await vscode.workspace.openTextDocument(toSourceUri(fileFullPath)); + return document.lineCount; + } + const content = await fs.promises.readFile(fileFullPath, 'utf8'); + return content.length === 0 ? 0 : content.split(/\r?\n/).length; + } + + /** + * The form in which `getBreakpoints` and the debug state report a source + * location, so a caller-supplied path or URI can be compared with them. + * Different spellings of one virtual-document URI (a literal space versus + * `%20`, authority casing) map to the same text. + */ + public normalizeSourceLocation(fileFullPath: string): string { + return toSourceText(toSourceUri(fileFullPath)); + } + /** * Start a debugging session */ @@ -362,7 +390,7 @@ export class DebuggingExecutor implements IDebuggingExecutor { */ public async addBreakpoint(fileFullPath: string, line: number, condition?: string, logMessage?: string): Promise { try { - const uri = vscode.Uri.file(fileFullPath); + const uri = toSourceUri(fileFullPath); const breakpoint = new vscode.SourceBreakpoint( new vscode.Location(uri, new vscode.Position(line - 1, 0)), true, @@ -381,7 +409,7 @@ export class DebuggingExecutor implements IDebuggingExecutor { */ public async removeBreakpoint(fileFullPath: string, line: number): Promise { try { - const uri = vscode.Uri.file(fileFullPath); + const uri = toSourceUri(fileFullPath); const breakpoints = vscode.debug.breakpoints.filter(bp => { if (bp instanceof vscode.SourceBreakpoint) { return bp.location.uri.toString() === uri.toString() && @@ -539,9 +567,16 @@ export class DebuggingExecutor implements IDebuggingExecutor { numNextLines: number ): Promise { try { - const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(filePath)); + // Adapters for virtual documents report a URI in `source.path` (for + // example Business Central's `al-preview:` sources). Treating that + // as a filesystem path would point at a file that does not exist. + const virtualSource = isSourceUri(filePath); + const uri = toSourceUri(filePath); + const doc = await vscode.workspace.openTextDocument(uri); const zeroBasedLine = Math.max(0, Math.min(line - 1, doc.lineCount - 1)); - const fileName = filePath.split(/[/\\]/).pop() || ''; + // Report a virtual source in the form the breakpoint tools accept. + const fileFullPath = virtualSource ? toSourceText(uri) : filePath; + const fileName = (virtualSource ? uri.path.split('/') : filePath.split(/[/\\]/)).pop() || ''; const currentLineContent = doc.lineAt(zeroBasedLine).text.trim(); // Collect the next non-empty lines for lookahead context. @@ -555,7 +590,7 @@ export class DebuggingExecutor implements IDebuggingExecutor { lineOffset++; } - state.updateLocation(filePath, fileName, line, currentLineContent, nextLines); + state.updateLocation(fileFullPath, fileName, line, currentLineContent, nextLines); } catch (error) { // Native/library frames or paths VS Code can't open won't resolve to // a document; degrade gracefully and leave location unset. @@ -786,7 +821,7 @@ export class DebuggingExecutor implements IDebuggingExecutor { .filter((breakpoint): breakpoint is vscode.SourceBreakpoint => breakpoint instanceof vscode.SourceBreakpoint) .map(breakpoint => ({ - fileFullPath: breakpoint.location.uri.fsPath, + fileFullPath: toSourceText(breakpoint.location.uri), line: breakpoint.location.range.start.line + 1, condition: breakpoint.condition, logMessage: breakpoint.logMessage diff --git a/src/debuggingHandler.ts b/src/debuggingHandler.ts index 3e056ad..818561d 100644 --- a/src/debuggingHandler.ts +++ b/src/debuggingHandler.ts @@ -5,6 +5,7 @@ import { DebugConfigurationManager, IDebugConfigurationManager } from './utils/d import { DebugState } from './debugState'; import { IDebuggingExecutor } from './debuggingExecutor'; import { logger } from './utils/logger'; +import { isSourceUri, sourceFileName } from './utils/sourceUri'; import { withTimeout } from './utils/withTimeout'; import { IDebugOutputQuery } from './utils/debugOutputBuffer'; import { @@ -28,9 +29,9 @@ export interface IDebuggingHandler { handleContinue(): Promise; handlePause(): Promise; handleRestart(): Promise; - handleAddBreakpoint(args: { fileFullPath: string; line: number; condition?: string }): Promise; - handleAddLogpoint(args: { fileFullPath: string; line: number; logMessage: string; condition?: string }): Promise; - handleRemoveBreakpoint(args: { fileFullPath: string; line: number }): Promise; + handleAddBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }): Promise; + handleAddLogpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }): Promise; + handleRemoveBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number }): Promise; handleClearAllBreakpoints(): Promise; handleListBreakpoints(): Promise; handleGetVariables(args: { variableNames: string[]; scope?: 'local' | 'global' | 'all' }): Promise; @@ -464,7 +465,7 @@ export class DebuggingHandler implements IDebuggingHandler { * Add a breakpoint at specified location. An optional condition makes it a * conditional breakpoint that only pauses when the expression is true. */ - public async handleAddBreakpoint(args: { fileFullPath: string; line: number; condition?: string }): Promise { + public async handleAddBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }): Promise { const { fileFullPath, line, condition } = args; try { @@ -474,20 +475,51 @@ export class DebuggingHandler implements IDebuggingHandler { // Validate the line exists so we fail clearly instead of setting an // unbound breakpoint past the end of the file. - const lineCount = await this.getFileLineCount(fileFullPath); - if (line > lineCount) { - throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${lineCount} lines.`); - } + const lineCaveat = await this.checkLineInSource(fileFullPath, line); await this.executor.addBreakpoint(fileFullPath, line, condition); const conditionInfo = condition ? ` (condition: ${condition})` : ''; - return `Breakpoint added at ${fileFullPath}:${line}${conditionInfo}${await this.sessionCaveat()}`; + return `Breakpoint added at ${fileFullPath}:${line}${conditionInfo}${lineCaveat}${await this.sessionCaveat()}`; } catch (error) { throw new Error(`Error adding breakpoint: ${error}`); } } + /** + * Reject a line past the end of the source, returning a note for the caller + * when the line could not be checked. + * + * A virtual document is not always readable when a breakpoint is set: + * Business Central serves a `.dal` source only once its debug session has + * stopped. Refusing the breakpoint then would make it impossible to arm one + * before the first stop, so an unreadable virtual source is left unchecked + * and reported as such. A missing file on disk is still an error. + */ + private async checkLineInSource(fileFullPath: string, line: number): Promise { + let lineCount: number; + try { + lineCount = await this.getFileLineCount(fileFullPath); + } catch (error) { + if (!isSourceUri(fileFullPath)) { + throw error; + } + logger.warn( + `Could not open ${fileFullPath} to validate line ${line}: ` + + `${error instanceof Error ? error.message : String(error)}` + ); + return ( + `\n\nNOTE: the virtual document could not be opened, so line ${line} was not checked against it. ` + + 'Some debuggers only serve such sources once the session has stopped. ' + + 'If the URI or line is wrong, this breakpoint will never be hit.' + ); + } + if (line > lineCount) { + throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${lineCount} lines.`); + } + return ''; + } + /** * Warn when a breakpoint is registered with no debug session attached. * @@ -516,7 +548,7 @@ export class DebuggingHandler implements IDebuggingHandler { * interpolated by the debug adapter) instead of pausing execution. An * optional condition only logs when the expression is true. */ - public async handleAddLogpoint(args: { fileFullPath: string; line: number; logMessage: string; condition?: string }): Promise { + public async handleAddLogpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }): Promise { const { fileFullPath, line, logMessage, condition } = args; try { @@ -529,15 +561,12 @@ export class DebuggingHandler implements IDebuggingHandler { // Validate the line exists so we fail clearly instead of setting an // unbound logpoint past the end of the file. - const lineCount = await this.getFileLineCount(fileFullPath); - if (line > lineCount) { - throw new Error(`Line ${line} is out of range: ${fileFullPath} has ${lineCount} lines.`); - } + const lineCaveat = await this.checkLineInSource(fileFullPath, line); await this.executor.addBreakpoint(fileFullPath, line, condition, logMessage); const conditionInfo = condition ? ` (condition: ${condition})` : ''; - return `Logpoint added at ${fileFullPath}:${line}${conditionInfo}${await this.sessionCaveat()}`; + return `Logpoint added at ${fileFullPath}:${line}${conditionInfo}${lineCaveat}${await this.sessionCaveat()}`; } catch (error) { throw new Error(`Error adding logpoint: ${error}`); } @@ -546,14 +575,17 @@ export class DebuggingHandler implements IDebuggingHandler { /** * Remove a breakpoint from specified location */ - public async handleRemoveBreakpoint(args: { fileFullPath: string; line: number }): Promise { + public async handleRemoveBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number }): Promise { const { fileFullPath, line } = args; try { - // Check if breakpoint exists at this location + // Check if breakpoint exists at this location. Compare in the + // executor's own form: a virtual-document URI can be written with a + // literal space or `%20` and still name the same source. + const location = this.executor.normalizeSourceLocation?.(fileFullPath) ?? fileFullPath; const breakpoints = this.executor.getBreakpoints(); const existingBreakpoint = breakpoints.find(bp => - bp.fileFullPath === fileFullPath && bp.line === line); + bp.fileFullPath === location && bp.line === line); if (!existingBreakpoint) { return `No breakpoint found at ${fileFullPath}:${line}`; @@ -579,7 +611,7 @@ export class DebuggingHandler implements IDebuggingHandler { let breakpointList = 'Active Breakpoints:\n'; breakpoints.forEach((bp, index) => { - const fileName = bp.fileFullPath.split(/[/\\]/).pop(); + const fileName = sourceFileName(bp.fileFullPath); const conditionInfo = bp.condition ? ` (condition: ${bp.condition})` : ''; const kind = bp.logMessage ? 'Logpoint' : 'Breakpoint'; const logInfo = bp.logMessage ? ` (log: ${bp.logMessage})` : ''; @@ -1086,6 +1118,9 @@ export class DebuggingHandler implements IDebuggingHandler { } private async getFileLineCount(fileFullPath: string): Promise { + if (this.executor.getFileLineCount) { + return await this.executor.getFileLineCount(fileFullPath); + } const content = await fs.promises.readFile(fileFullPath, 'utf8'); return content.length === 0 ? 0 : content.split(/\r?\n/).length; } diff --git a/src/routingDebuggingHandler.ts b/src/routingDebuggingHandler.ts index 6d1bd06..d8ed36e 100644 --- a/src/routingDebuggingHandler.ts +++ b/src/routingDebuggingHandler.ts @@ -5,6 +5,7 @@ import { IDebuggingHandler } from './debuggingHandler'; import { WorkspaceRegistry, WindowRegistration } from './utils/workspaceRegistry'; import { logger } from './utils/logger'; import { IDebugOutputQuery } from './utils/debugOutputBuffer'; +import { isSourceUri } from './utils/sourceUri'; /** * Router-window handler (one instance per MCP session) that forwards every @@ -41,9 +42,9 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { * has no cached target we recover rather than fail - but only when a single * registered window makes the answer unambiguous. */ - private resolveTarget(pathHint?: string): WindowRegistration { + private resolveTarget(pathHint?: string, virtualSource = false): WindowRegistration { if (pathHint) { - const found = this.registry.findByPath(pathHint); + const found = virtualSource ? undefined : this.registry.findByPath(pathHint); const candidates = this.registry .list() .map((w) => `pid=${w.pid} port=${w.controlPort} folders=[${w.workspaceFolders.join(', ') || 'none'}]`) @@ -63,7 +64,7 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { } } if (!this.target) { - throw new Error(this.noTargetMessage(pathHint)); + throw new Error(this.noTargetMessage(pathHint, virtualSource)); } return this.target; } @@ -92,12 +93,21 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { return undefined; } - private noTargetMessage(pathHint?: string): string { + private noTargetMessage(pathHint?: string, virtualSource = false): string { const windows = this.registry.list(); const openList = windows .map((w) => (w.workspaceFolders.length ? w.workspaceFolders.join(', ') : '(no folder)')) .join('; '); if (pathHint) { + if (virtualSource) { + return ( + `DebugMCP could not select a VS Code window for virtual source URI "${pathHint}". ` + + 'Pass workingDirectory to identify the workspace that owns the debug session. ' + + (openList + ? `Currently registered workspaces: ${openList}.` + : 'No DebugMCP-enabled VS Code windows are currently registered.') + ); + } return ( `DebugMCP could not find an open VS Code window whose workspace contains "${pathHint}". ` + (openList @@ -114,8 +124,8 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { ); } - private async forward(op: string, args: unknown, pathHint?: string): Promise { - const target = this.resolveTarget(pathHint); + private async forward(op: string, args: unknown, pathHint?: string, virtualSource = false): Promise { + const target = this.resolveTarget(pathHint, virtualSource); logger.info(`Forwarding ${op} to pid=${target.pid} port=${target.controlPort}${pathHint ? '' : ' (cached target, no path hint)'}`); try { return await this.post(target, op, args); @@ -241,16 +251,19 @@ export class RoutingDebuggingHandler implements IDebuggingHandler { return this.forward('handleRestart', {}); } - public handleAddBreakpoint(args: { fileFullPath: string; line: number; condition?: string }): Promise { - return this.forward('handleAddBreakpoint', args, args.fileFullPath); + public handleAddBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; condition?: string }): Promise { + const virtualSource = !args.workingDirectory && isSourceUri(args.fileFullPath); + return this.forward('handleAddBreakpoint', args, args.workingDirectory || args.fileFullPath, virtualSource); } - public handleAddLogpoint(args: { fileFullPath: string; line: number; logMessage: string; condition?: string }): Promise { - return this.forward('handleAddLogpoint', args, args.fileFullPath); + public handleAddLogpoint(args: { fileFullPath: string; workingDirectory?: string; line: number; logMessage: string; condition?: string }): Promise { + const virtualSource = !args.workingDirectory && isSourceUri(args.fileFullPath); + return this.forward('handleAddLogpoint', args, args.workingDirectory || args.fileFullPath, virtualSource); } - public handleRemoveBreakpoint(args: { fileFullPath: string; line: number }): Promise { - return this.forward('handleRemoveBreakpoint', args, args.fileFullPath); + public handleRemoveBreakpoint(args: { fileFullPath: string; workingDirectory?: string; line: number }): Promise { + const virtualSource = !args.workingDirectory && isSourceUri(args.fileFullPath); + return this.forward('handleRemoveBreakpoint', args, args.workingDirectory || args.fileFullPath, virtualSource); } public handleClearAllBreakpoints(): Promise { diff --git a/src/test/cliAdapterConfig.test.ts b/src/test/cliAdapterConfig.test.ts index 4c4c287..642e8ef 100644 --- a/src/test/cliAdapterConfig.test.ts +++ b/src/test/cliAdapterConfig.test.ts @@ -16,13 +16,16 @@ import { suite('CLI adapter configuration', () => { let workspace: string; let originalAppData: string | undefined; + let originalXdgConfigHome: string | undefined; let appData: string; setup(async () => { workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'debugmcp-cli-project-')); appData = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'debugmcp-cli-user-')); originalAppData = process.env.APPDATA; + originalXdgConfigHome = process.env.XDG_CONFIG_HOME; process.env.APPDATA = appData; + process.env.XDG_CONFIG_HOME = appData; }); teardown(async () => { @@ -31,6 +34,11 @@ suite('CLI adapter configuration', () => { } else { process.env.APPDATA = originalAppData; } + if (originalXdgConfigHome === undefined) { + delete process.env.XDG_CONFIG_HOME; + } else { + process.env.XDG_CONFIG_HOME = originalXdgConfigHome; + } await fs.promises.rm(workspace, { recursive: true, force: true }); await fs.promises.rm(appData, { recursive: true, force: true }); }); @@ -104,7 +112,7 @@ suite('CLI adapter configuration', () => { type: 'coreclr', extensions: ['.cs'], launch: { - program: '${workspaceFolder}\\bin\\Calculator.exe', + program: path.join('${workspaceFolder}', 'bin', 'Calculator.exe'), args: ['${file}', '${fileBasenameNoExtension}'], sourceFileMap: { '/source': '${fileDirname}' diff --git a/src/test/routing.test.ts b/src/test/routing.test.ts index 62705c5..d65693a 100644 --- a/src/test/routing.test.ts +++ b/src/test/routing.test.ts @@ -160,6 +160,55 @@ suite('Multi-window routing', () => { assert.strictEqual(handlerB.calls.length, 0); }); + test('virtual source breakpoint uses workingDirectory to select its window', async () => { + const repoA = path.join(dir, 'repoA'); + const repoB = path.join(dir, 'repoB'); + const handlerA = new RecordingHandler('A'); + const handlerB = new RecordingHandler('B'); + await startWindow('a.json', [repoA], handlerA); + await startWindow('b.json', [repoB], handlerB); + + const routing = new RoutingDebuggingHandler(new WorkspaceRegistry(process.pid, dir)); + const result = await routing.handleAddBreakpoint({ + fileFullPath: 'al-preview://AlLang/app/Table/18/Customer.dal', + workingDirectory: repoB, + line: 1 + }); + + assert.strictEqual(result, 'B:addBp'); + assert.strictEqual(handlerA.calls.length, 0); + }); + + test('virtual source breakpoint falls back to the sole registered window', async () => { + const repoA = path.join(dir, 'repoA'); + const handlerA = new RecordingHandler('A'); + await startWindow('a.json', [repoA], handlerA); + + const routing = new RoutingDebuggingHandler(new WorkspaceRegistry(process.pid, dir)); + const result = await routing.handleAddBreakpoint({ + fileFullPath: 'al-preview://AlLang/app/Table/18/Customer.dal', + line: 1 + }); + + assert.strictEqual(result, 'A:addBp'); + }); + + test('virtual source breakpoint requires workingDirectory when multiple windows are open', async () => { + const repoA = path.join(dir, 'repoA'); + const repoB = path.join(dir, 'repoB'); + await startWindow('a.json', [repoA], new RecordingHandler('A')); + await startWindow('b.json', [repoB], new RecordingHandler('B')); + + const routing = new RoutingDebuggingHandler(new WorkspaceRegistry(process.pid, dir)); + await assert.rejects( + () => routing.handleAddBreakpoint({ + fileFullPath: 'al-preview://AlLang/app/Table/18/Customer.dal', + line: 1 + }), + /Pass workingDirectory/ + ); + }); + test('throws a helpful error when no window owns the path', async () => { const repoA = path.join(dir, 'repoA'); const repoB = path.join(dir, 'repoB'); diff --git a/src/test/sourceUri.test.ts b/src/test/sourceUri.test.ts new file mode 100644 index 0000000..175abd3 --- /dev/null +++ b/src/test/sourceUri.test.ts @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. + +import * as assert from 'assert'; +import { isSourceUri, sourceFileName } from '../utils/sourceUri'; + +suite('Source URI handling', () => { + test('does not mistake a Windows drive letter for a URI scheme', () => { + assert.strictEqual(isSourceUri('C:\\workspace\\src\\main.ts'), false); + assert.strictEqual(isSourceUri('al-preview://allang/app/Table/18/Customer.dal'), true); + }); + + test('shows a readable file name for paths and URIs', () => { + assert.strictEqual(sourceFileName('/workspace/src/main.ts'), 'main.ts'); + assert.strictEqual(sourceFileName('C:\\workspace\\src\\main.ts'), 'main.ts'); + assert.strictEqual( + sourceFileName('al-preview://allang/app/Codeunit/51000/EXW%20Warehouse%20Service.dal'), + 'EXW Warehouse Service.dal' + ); + assert.strictEqual(sourceFileName('debug:/generated/eval%20code.js?session=1&ref=7'), 'eval code.js'); + assert.strictEqual(sourceFileName('al-preview://allang/app/Table/18/100%.dal'), '100%.dal'); + }); +}); diff --git a/src/test/virtualSourceLocation.test.ts b/src/test/virtualSourceLocation.test.ts new file mode 100644 index 0000000..c85c337 --- /dev/null +++ b/src/test/virtualSourceLocation.test.ts @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. + +import * as vscode from 'vscode'; +import * as assert from 'node:assert/strict'; +import { DebuggingExecutor } from '../debuggingExecutor'; +import { DebuggingHandler } from '../debuggingHandler'; +import { DebugConfigurationManager } from '../utils/debugConfigurationManager'; + +/** + * Language extensions can serve sources that exist only as virtual documents. + * Business Central is the motivating case: the objects of an installed app are + * shown as `al-preview://allang////.dal`, and object + * names routinely contain spaces. The stack frame below is what its debug + * adapter reports for a stop in such a document. + */ +const documentLines = [ + 'codeunit 51000 "EXW Warehouse Service"', + '{', + ' procedure GetPackageInformation(packageID: Text)', + ' begin', + ' if not Package.Get(packageID) then', + '', + ' Error(PackageNotFoundErr, packageID);', + ' exit(Package.Description);', + ' end;', + '}' +]; + +suite('Virtual source documents (AL .dal)', () => { + let schemeCounter = 0; + let scheme: string; + let spacedSource: string; + let canonicalSource: string; + let provider: vscode.Disposable; + let sessionDescriptor: PropertyDescriptor; + let stackDescriptor: PropertyDescriptor; + + const executor = () => new DebuggingExecutor(); + const handler = (target: DebuggingExecutor = executor()) => + new DebuggingHandler(target, new DebugConfigurationManager(), 5); + // VS Code echoes breakpoint changes back to the extension host, so a + // breakpoint removed by an earlier test can briefly reappear. Every test + // therefore uses its own scheme and only looks at its own breakpoints. + const sourceBreakpoints = () => vscode.debug.breakpoints + .filter((breakpoint): breakpoint is vscode.SourceBreakpoint => breakpoint instanceof vscode.SourceBreakpoint) + .filter(breakpoint => breakpoint.location.uri.scheme === scheme); + const reportedLocations = (target: DebuggingExecutor, own: (location: string) => boolean) => + target.getBreakpoints().map(breakpoint => breakpoint.fileFullPath).filter(own); + + setup(() => { + scheme = `al-preview-test-${Date.now()}-${++schemeCounter}`; + spacedSource = `${scheme}://allang/debug-app/Codeunit/51000/EXW Warehouse Service.dal`; + canonicalSource = `${scheme}://allang/debug-app/Codeunit/51000/EXW%20Warehouse%20Service.dal`; + provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { + provideTextDocumentContent: () => documentLines.join('\n') + }); + + const session: vscode.DebugSession = { + id: 'al-virtual-source', + name: 'AL attach', + type: 'al', + configuration: { type: 'al', request: 'attach', name: 'AL attach' }, + workspaceFolder: undefined, + customRequest: async (command: string) => { + assert.equal(command, 'stackTrace'); + return { + stackFrames: [{ + id: 0, + name: 'GetPackageInformation', + source: { name: 'EXW Warehouse Service', path: spacedSource, sourceReference: 0 }, + line: 5, + column: 9 + }] + }; + }, + getDebugProtocolBreakpoint: async () => undefined + }; + sessionDescriptor = Object.getOwnPropertyDescriptor(vscode.debug, 'activeDebugSession')!; + stackDescriptor = Object.getOwnPropertyDescriptor(vscode.debug, 'activeStackItem')!; + Object.defineProperty(vscode.debug, 'activeDebugSession', { configurable: true, get: () => session }); + Object.defineProperty(vscode.debug, 'activeStackItem', { + configurable: true, + get: () => ({ frameId: 0, threadId: 1, session }) + }); + }); + + teardown(() => { + Object.defineProperty(vscode.debug, 'activeDebugSession', sessionDescriptor); + Object.defineProperty(vscode.debug, 'activeStackItem', stackDescriptor); + vscode.debug.removeBreakpoints(vscode.debug.breakpoints); + provider.dispose(); + }); + + test('a stop in a virtual document reports its location', async () => { + const state = await executor().getCurrentDebugState(2); + + assert.equal(state.fileFullPath, canonicalSource); + assert.equal(state.fileName, 'EXW Warehouse Service.dal'); + assert.equal(state.currentLine, 5); + assert.equal(state.currentLineContent, 'if not Package.Get(packageID) then'); + assert.deepEqual(state.nextLines, [ + 'Error(PackageNotFoundErr, packageID);', + 'exit(Package.Description);' + ]); + }); + + test('add_breakpoint accepts the reported location unchanged', async () => { + const state = JSON.parse(await handler().handleGetDebugStatus()).state; + + const result = await handler().handleAddBreakpoint({ fileFullPath: state.fileFullPath, line: state.currentLine }); + + assert.match(result, /Breakpoint added/); + const [breakpoint] = sourceBreakpoints(); + assert.equal(breakpoint.location.uri.toString(), state.fileFullPath); + assert.equal(breakpoint.location.range.start.line, state.currentLine - 1); + }); + + test('add_breakpoint rejects a line past the end of a readable virtual document', async () => { + await assert.rejects( + handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: documentLines.length + 1 }), + /out of range.*has 10 lines/ + ); + assert.equal(sourceBreakpoints().length, 0); + }); + + test('a virtual document that cannot be opened yet still takes a breakpoint, with a note', async () => { + // Business Central serves a .dal source only once the session has stopped. + provider.dispose(); + provider = vscode.workspace.registerTextDocumentContentProvider(scheme, { + provideTextDocumentContent: () => { throw new Error('GetSourceContent failed on the server'); } + }); + + const breakpoint = await handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: 81 }); + const logpoint = await handler().handleAddLogpoint({ fileFullPath: spacedSource, line: 82, logMessage: 'reached' }); + + assert.match(breakpoint, /Breakpoint added at .*:81/); + assert.match(breakpoint, /could not be opened, so line 81 was not checked/); + assert.match(logpoint, /could not be opened, so line 82 was not checked/); + assert.deepEqual(sourceBreakpoints().map(item => item.location.range.start.line + 1).sort(), [81, 82]); + }); + + test('a missing file on disk is still rejected', async () => { + await assert.rejects( + handler().handleAddBreakpoint({ fileFullPath: `${__filename}.missing`, line: 1 }), + /Error adding breakpoint/ + ); + }); + + test('remove_breakpoint finds a breakpoint by the URI text it was added with', async () => { + await handler().handleAddBreakpoint({ fileFullPath: spacedSource, line: 7 }); + assert.equal(sourceBreakpoints().length, 1); + + const result = await handler().handleRemoveBreakpoint({ fileFullPath: spacedSource, line: 7 }); + + assert.match(result, /Breakpoint removed/); + assert.equal(sourceBreakpoints().length, 0); + }); + + test('breakpoints are listed with the decoded file name and the canonical URI', async () => { + const target = executor(); + await handler(target).handleAddBreakpoint({ fileFullPath: spacedSource, line: 7 }); + + const listing = await handler(target).handleListBreakpoints(); + + assert.match(listing, /Breakpoint EXW Warehouse Service\.dal:7/); + assert.deepEqual(reportedLocations(target, location => location.startsWith(`${scheme}:`)), [canonicalSource]); + }); + + test('a breakpoint in a file on disk is reported and removed by its native path', async () => { + const target = executor(); + const onDisk = (location: string) => !location.startsWith('al-preview-test-'); + await handler(target).handleAddBreakpoint({ fileFullPath: __filename, line: 1 }); + assert.deepEqual(reportedLocations(target, onDisk), [__filename]); + + const result = await handler(target).handleRemoveBreakpoint({ fileFullPath: __filename, line: 1 }); + + assert.match(result, /Breakpoint removed/); + assert.deepEqual(reportedLocations(target, onDisk), []); + }); +}); diff --git a/src/utils/sourceUri.ts b/src/utils/sourceUri.ts new file mode 100644 index 0000000..e3ec2ee --- /dev/null +++ b/src/utils/sourceUri.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. + +// Host-neutral helpers for source locations given as text. This module is also +// bundled into the standalone CLI, so it must not depend on the `vscode` module; +// conversions to and from `vscode.Uri` live in `vscodeSourceUri.ts`. + +/** + * True when a source location is a URI rather than a native filesystem path. + * + * The drive letter in a Windows path looks like a URI scheme, so explicitly + * exclude drive-letter paths before applying the generic scheme check. + */ +export function isSourceUri(source: string): boolean { + if (/^[a-zA-Z]:[\\/]/.test(source)) { + return false; + } + return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(source); +} + +/** + * File name to display for a source location given as a native path or a URI + * string. Percent-escapes in a URI are decoded, so `My%20Object.dal` reads as + * `My Object.dal`. + */ +export function sourceFileName(source: string): string { + if (!isSourceUri(source)) { + return source.split(/[/\\]/).pop() ?? ''; + } + const name = source.replace(/[?#].*$/, '').split('/').pop() ?? ''; + try { + return decodeURIComponent(name); + } catch { + return name; + } +} diff --git a/src/utils/vscodeSourceUri.ts b/src/utils/vscodeSourceUri.ts new file mode 100644 index 0000000..d39d3a7 --- /dev/null +++ b/src/utils/vscodeSourceUri.ts @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. + +import * as vscode from 'vscode'; +import { isSourceUri } from './sourceUri'; + +/** Preserve virtual-document schemes while retaining native path behavior. */ +export function toSourceUri(source: string): vscode.Uri { + return isSourceUri(source) ? vscode.Uri.parse(source, true) : vscode.Uri.file(source); +} + +/** + * The text DebugMCP reports for a source location and accepts back unchanged: + * the native path for a file on disk, the canonical URI string for anything else. + */ +export function toSourceText(uri: vscode.Uri): string { + return uri.scheme === 'file' ? uri.fsPath : uri.toString(); +}