Skip to content

Improve ql-mcp VS Code extension UX#230

Merged
data-douser merged 13 commits intomainfrom
copilot/improve-vscode-extension-ux
Apr 8, 2026
Merged

Improve ql-mcp VS Code extension UX#230
data-douser merged 13 commits intomainfrom
copilot/improve-vscode-extension-ux

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 7, 2026

📝 Update Information

Primitive Details

  • Type: Prompts, Extension
  • Name: All 14 workflow prompts, VS Code extension infrastructure
  • Update Category: Feature Enhancement, Robustness, UX

⚠️ CRITICAL: PR SCOPE VALIDATION

ALLOWED FILES:

  • Server implementation files (server/src/**/*.ts)
  • Updated primitive implementations
  • Updated or new test files (server/test/**/*.ts)
  • Extension source files (extensions/vscode/src/**/*.ts)
  • Extension test files (extensions/vscode/test/**/*.ts)
  • Build configuration (extensions/vscode/esbuild.config.js)
  • Shared constants (server/src/prompts/constants.ts)

🚫 FORBIDDEN FILES:

  • No unrelated files included

🛑 MANDATORY PR VALIDATION CHECKLIST

  • ONLY server and extension implementation files are included
  • NO temporary or output files are included
  • NO unrelated configuration files are included
  • ALL existing tests continue to pass
  • NEW functionality is properly tested

  • Impact Scope: Moderate — touches all prompt registrations, extension CLI resolver, pack installer, watchers, and MCP provider

Update Metadata

  • Breaking Changes: No
  • API Compatibility: Enhanced (additive only — completion/complete responses are new, language parameter now optional on several prompts)
  • Performance Impact: Neutral (completions are lazy with 5s TTL cache; debounced MCP definition-change events reduce noise)

🎯 Changes Description

Current Behavior

Workflow prompts used as VS Code Copilot Chat slash commands show raw text input fields for all parameters. Users must manually type full file paths for CodeQL queries, databases, SARIF files, etc. The language parameter is required on every prompt, even when it could be inferred. Extension-side CLI resolution can race, pack installer logging is inconsistent, and file watchers fire noisy MCP definition-change events.

Updated Behavior

MCP Server Prompt Completions:

  • Prompt parameters now provide auto-complete suggestions via the MCP SDK's completable() function. VS Code shows a filtered dropdown as the user types:
    • language — filters SUPPORTED_LANGUAGES by prefix
    • queryPath — discovers .ql/.qlref files in workspace
    • sarifPath/sarifPathA/sarifPathB — discovers .sarif/.sarif.json files
    • database/databasePath — lists CodeQL database directories from CODEQL_DATABASES_BASE_DIRS, $HOME/codeql/databases/, and workspace
    • workspaceUri/packRoot — finds directories containing codeql-pack.yml
  • Completion results are cached with a 5-second TTL to avoid repeated workspace scans.
  • A centralized SKIP_DIRS set ensures all completion providers consistently skip node_modules, .git, .github, .tmp, build, coverage, and dist directories.

Optional Language with Auto-Derivation:

  • Several workflow prompts (workshop_creation_workflow, explain_codeql_query, document_codeql_query, ql_lsp_iterative_development) now accept language as optional.
  • When omitted, language is auto-derived from the nearest codeql-pack.yml with a codeql/<lang>-all or codeql/<lang>-queries dependency via resolveLanguageFromPack().
  • A shared getEffectiveLanguage() helper centralizes the derivation logic, debug logging, and warning generation across all prompt handlers.
  • queryPath is ordered before language in schema shapes so the user fills in the query first, enabling better auto-derivation.

Extension Robustness:

  • CliResolver ensures only one resolution runs at a time, validates PATH-discovered binaries, and uses generation tokens to prevent stale cache writes after invalidation.
  • PackInstaller uses consistent "download" terminology for codeql pack download operations and provides detailed per-language logging.
  • McpProvider.fireDidChange debounces rapid-fire notifications and clears pending timers on dispose/restart.
  • File watchers use relative paths in log messages and no longer trigger MCP definition changes for content-only file events.

Circular Dependency Fix:

  • SUPPORTED_LANGUAGES moved to server/src/prompts/constants.ts to break the circular import between workflow-prompts.ts and prompt-completions.ts.

Motivation

The VS Code MCP integration supports completion/complete for prompt arguments. The MCP SDK already ships completable() — we just weren't using it. Additionally, requiring language when it could be inferred from pack metadata created unnecessary friction, and extension-side race conditions in CLI resolution and noisy watcher events degraded the user experience.

🔄 Before vs. After Comparison

Functionality Changes

// BEFORE: raw shape, no completions, language always required
server.prompt('explain_codeql_query', description,
  toPermissiveShape(explainCodeqlQuerySchema.shape),
  handler);

// AFTER: completable-wrapped shape, language optional + auto-derived
server.prompt('explain_codeql_query', description,
  addCompletions(toPermissiveShape(explainCodeqlQuerySchema.shape)),
  createSafePromptHandler('explain_codeql_query', explainCodeqlQuerySchema,
    async ({ queryPath, language }) => {
      // ...
      const langResult = await getEffectiveLanguage('explain_codeql_query', language, resolvedQueryPath);
      const effectiveLanguage = langResult.language;
      if (langResult.warning) warnings.push(langResult.warning);
      // ...
    }));

API Changes

// Input Schema Changes — language now optional on select prompts
// BEFORE:
const explainCodeqlQuerySchema = z.object({
  queryPath: z.string(),
  language: z.enum(SUPPORTED_LANGUAGES),
  databasePath: z.string().optional(),
});

// AFTER:
const explainCodeqlQuerySchema = z.object({
  queryPath: z.string(),
  language: z.enum(SUPPORTED_LANGUAGES).optional(),
  databasePath: z.string().optional(),
});

Output Format Changes

New completion/complete responses:

{
  "completion": {
    "values": ["java", "javascript"],
    "hasMore": false,
    "total": 2
  }
}

🧪 Testing & Validation

Test Coverage Updates

  • Existing Tests: All existing tests continue to pass (1377 server, 182 extension unit)
  • New Test Cases: 65 unit tests for completion providers, addCompletions, resolveLanguageFromPack, getEffectiveLanguage, and schema field ordering
  • Regression Tests: Existing workflow-prompts.test.ts (309 tests) validates schema consistency
  • Edge Case Tests: ZodEnum handling, mutation safety, empty workspace, skipped directories, Windows env var stubs, cross-platform homedir() behavior

Validation Scenarios

  1. Backward Compatibility: All 309 existing workflow prompt tests pass unchanged
  2. New Functionality: 65 new completion/auto-derivation tests; 12 new E2E integration tests
  3. Error Handling: getEffectiveLanguage returns user-friendly warnings when language can't be derived
  4. Performance: Completion results cached with 5s TTL; SKIP_DIRS set avoids scanning large output directories

Test Results

  • Unit Tests: 1377/1377 pass (server), 182/182 pass (extension)
  • Integration Tests: 12 new E2E tests in mcp-completion-e2e.integration.test.ts
  • Manual Testing: N/A (sandbox environment cannot download VS Code)
  • Performance Testing: No regressions detected

📋 Implementation Details

Files Modified

  • Core Implementation: server/src/prompts/prompt-completions.ts — completion providers, addCompletions(), resolveLanguageFromPack(), getEffectiveLanguage()
  • Core Implementation: server/src/prompts/workflow-prompts.ts — apply addCompletions() to all 14 prompts, use getEffectiveLanguage() helper, make language optional on select prompts
  • Shared Constants: server/src/prompts/constants.tsSUPPORTED_LANGUAGES extracted to break circular dependency
  • Extension: extensions/vscode/src/codeql/cli-resolver.ts — concurrency control, PATH validation, generation tokens
  • Extension: extensions/vscode/src/server/pack-installer.ts — consistent download terminology, detailed logging
  • Extension: extensions/vscode/src/server/mcp-provider.ts — debounced fireDidChange, timer cleanup on dispose
  • Extension: extensions/vscode/src/bridge/database-watcher.ts, query-results-watcher.ts — relative path logging, no MCP definition changes on content events
  • Tests: server/test/src/prompts/prompt-completions.test.ts — 65 tests for completions, language resolution, getEffectiveLanguage, schema ordering
  • Tests: extensions/vscode/test/suite/mcp-completion-e2e.integration.test.ts — 12 E2E completion tests
  • Build Config: extensions/vscode/esbuild.config.js — add new test entry point

Code Changes Summary

  • Algorithm Improvements: Centralized SKIP_DIRS set for workspace scanning; cached completion results with TTL
  • Error Handling: getEffectiveLanguage() returns structured {language, warning} result
  • Performance Optimization: 5-second scan cache, consistent directory skip list
  • Type Safety: cloneStringType preserves ZodEnum types; runtime checks for unexpected Zod types
  • Input Validation: Enum preservation for prompts using raw shapes (e.g., findOverlappingQueriesSchema)

Dependencies

  • No New Dependencies: Uses existing @modelcontextprotocol/sdk v1.29 (completable export)

🔍 Quality Improvements

Code Quality Enhancements

  • Readability: Centralized SKIP_DIRS, extracted getEffectiveLanguage() helper to eliminate 4× duplicated language auto-derivation blocks
  • Maintainability: SUPPORTED_LANGUAGES in shared constants.ts breaks circular dependency
  • Testability: 65 new unit tests + 12 E2E tests; Windows env var stubs for cross-platform test compatibility
  • Reusability: addCompletions() automatically enhances any prompt shape with matching parameter names

🔗 References

External References

🚀 Compatibility & Migration

Backward Compatibility

  • Fully Compatible: No breaking changes. Clients that don't support completion/complete simply never call it. Prompts that previously required language now accept it as optional with auto-derivation fallback.

API Evolution

  • Enhanced Parameters: language now optional on select prompts; all prompt arguments gain auto-complete
  • Improved Responses: Warnings when language can't be auto-derived
  • Maintained Contracts: All prompt schemas, handlers, and validation unchanged for non-affected prompts

👥 Review Guidelines

For Reviewers

  • ⚠️ SCOPE COMPLIANCE: Server + extension files, all directly related
  • ⚠️ BACKWARD COMPATIBILITY: Zero changes to prompt handler logic or schemas for non-affected prompts
  • Functionality: addCompletions() is a pure wrapper — prompt behavior unchanged
  • Test Coverage: 65 new unit tests + 12 E2E tests + all existing tests pass
  • Code Quality: Centralized SKIP_DIRS, extracted getEffectiveLanguage(), broke circular dependency

Testing Instructions

# Full server test suite (1377 tests)
npm test -w server

# Extension unit tests (182 tests)
npm run test:coverage -w extensions/vscode

# Specific prompt completion tests
cd server && npx vitest run test/src/prompts/prompt-completions.test.ts

# Full build and lint
npm run build-and-test

📊 Impact Assessment

Server Impact

  • Startup Time: Negligible — addCompletions runs once during registration
  • Runtime Stability: Completion callbacks are async, error-resilient (catch + empty array)
  • Resource Usage: File scans capped at 50 results, 8 levels deep, cached with 5s TTL
  • Concurrent Usage: Safe for concurrent access

AI Assistant Impact

  • Enhanced User Experience: Users pick from dropdowns instead of typing raw paths
  • Enhanced Accuracy: Language auto-derivation reduces user error
  • Improved Reliability: Debounced MCP events, concurrent CLI resolution guard

Copilot AI and others added 4 commits April 7, 2026 04:19
Add completable() wrappers to workflow prompt parameters so VS Code
Copilot Chat shows auto-complete dropdowns for language, query paths,
SARIF files, database paths, and pack roots.

- Create prompt-completions.ts with completion providers for each
  parameter type (language enum, .ql/.qlref files, .sarif files,
  CodeQL databases, codeql-pack.yml directories)
- Update all 14 workflow prompt registrations to use addCompletions()
- Add comprehensive unit tests (35 tests covering all completers
  and the addCompletions utility)

Agent-Logs-Url: https://github.com/advanced-security/codeql-development-mcp-server/sessions/e316ece4-06c5-45d7-8020-062e6ec67e39

Co-authored-by: data-douser <70299490+data-douser@users.noreply.github.com>
Co-authored-by: data-douser <70299490+data-douser@users.noreply.github.com>
- cloneStringType now accepts both ZodString and ZodEnum (for prompts
  that use raw schema.shape without toPermissiveShape)
- Add runtime type checks that throw clear errors for unexpected types
- Add 2 unit tests for ZodEnum handling in addCompletions

Agent-Logs-Url: https://github.com/advanced-security/codeql-development-mcp-server/sessions/e316ece4-06c5-45d7-8020-062e6ec67e39

Co-authored-by: data-douser <70299490+data-douser@users.noreply.github.com>
Copilot AI changed the title [WIP] Improve UX for ql-mcp workflow prompts in VS Code [UPDATE PRIMITIVE] Add MCP prompt argument completions for VS Code slash command UX Apr 7, 2026
Copilot AI requested a review from data-douser April 7, 2026 04:35
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 7, 2026

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Snapshot Warnings

⚠️: No snapshots were found for the head SHA 15928f5.
Ensure that dependencies are being submitted on PR branches and consider enabling retry-on-snapshot-warnings. See the documentation for more information and troubleshooting advice.

Scanned Files

None

Addresses three UX issues with MCP prompt argument completions:

1. Database discovery: completeDatabasePath now scans $HOME/codeql/databases/
   as a default search location, and recursively discovers directories
   containing codeql-database.yml (including .testproj dirs) in the workspace.

2. Language auto-derivation: For prompts where queryPath is provided,
   language is now optional and auto-derived from the nearest
   codeql-pack.yml's codeql/<lang>-all or codeql/<lang>-queries dependency.
   Schema field ordering now puts queryPath before language so VS Code
   prompts for the query first. Affected schemas: explainCodeqlQuerySchema,
   documentCodeqlQuerySchema, workshopCreationWorkflowSchema,
   qlLspIterativeDevelopmentSchema.

3. Query path completion filtering: completeQueryPath now skips .github,
   dist, coverage, and build directories in addition to node_modules, .git,
   and .tmp — preventing workshop examples and build artifacts from
   cluttering the VS Code dropdown.

New tests: 19 unit tests covering all three fixes.
Updated tests: 9 existing tests updated to reflect language being optional.
Copilot AI review requested due to automatic review settings April 7, 2026 15:35
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds MCP prompt-argument completions so VS Code Copilot Chat slash commands can provide dropdown suggestions (languages, query paths, SARIF paths, databases, pack roots), and updates several prompt schemas/handlers to allow omitting language with best-effort auto-derivation from codeql-pack.yml. The PR also includes a set of VS Code extension-side changes around CodeQL CLI discovery and pack installation logging, plus new extension E2E coverage for completion/complete.

Changes:

  • Introduce server/src/prompts/prompt-completions.ts with completion providers and addCompletions() to wrap prompt shapes with MCP SDK completable().
  • Update workflow prompt registrations to apply addCompletions() and (for some prompts) make language optional + attempt auto-derivation from pack metadata.
  • Add unit tests (server) and E2E integration tests (VS Code extension) for completion behavior, alongside additional extension improvements/tests for CLI resolution and pack installer logging.
Show a summary per file
File Description
server/src/prompts/prompt-completions.ts New completion providers + addCompletions() wrapper; also adds language auto-derivation helper.
server/src/prompts/workflow-prompts.ts Wrap prompt registration shapes with addCompletions(); make language optional for several schemas; add handler-side language auto-derivation + warnings.
server/test/src/prompts/prompt-completions.test.ts New unit tests for completion providers, schema wrapping behavior, and language auto-derivation from pack metadata.
server/test/src/prompts/workflow-prompts.test.ts Update schema expectation tests to reflect language becoming optional in select prompts and updated handler messaging.
server/dist/codeql-development-mcp-server.js Updated bundled build output reflecting server-side changes.
extensions/vscode/test/suite/mcp-completion-e2e.integration.test.ts New Extension Development Host E2E tests calling completion/complete against the running MCP server.
extensions/vscode/test/suite/mcp-server.integration.test.ts Adds an environment validation test for CODEQL_PATH (currently substring-based).
extensions/vscode/esbuild.config.js Registers the new extension integration test entry point for compilation.
extensions/vscode/src/codeql/cli-resolver.ts Adds in-flight resolve de-duplication and validates PATH-resolved binaries before accepting them.
extensions/vscode/test/codeql/cli-resolver.test.ts Adds tests for PATH-based version detection and concurrent resolution behavior.
extensions/vscode/src/server/pack-installer.ts Enhances logging (CLI vs target version), adds success counts, and changes terminology to “install” for pack download.
extensions/vscode/test/server/pack-installer.test.ts Adds tests asserting updated pack installer logging and summary behavior.
extensions/vscode/src/server/server-manager.ts Tweaks “bundled server” log message text.
extensions/vscode/test/server/server-manager.test.ts Updates expectations to match new server-manager logging and asserts no “npm install” mention.

Copilot's findings

Comments suppressed due to low confidence (3)

server/src/prompts/workflow-prompts.ts:348

  • The explainCodeqlQuerySchema parameter comment still says queryPath and language are required, but language is now .optional(). Please update the comment so it matches the schema/handler behavior (language may be omitted and auto-derived).
 * - `databasePath` is optional – a database may also be derived from tests.
 */
export const explainCodeqlQuerySchema = z.object({
  queryPath: z
    .string()
    .describe('Path to the CodeQL query file (.ql or .qlref)'),
  language: z
    .enum(SUPPORTED_LANGUAGES)
    .optional()
    .describe('Programming language of the query (auto-derived from pack metadata when omitted)'),

server/src/prompts/workflow-prompts.ts:367

  • The documentCodeqlQuerySchema comment says queryPath and language are required, but language is now optional. Please update the comment to reflect the new validation contract (and the handler’s auto-derivation/warning behavior).
/**
 * Schema for document_codeql_query prompt parameters.
 *
 * - `queryPath` and `language` are **required**.
 */
export const documentCodeqlQuerySchema = z.object({
  queryPath: z
    .string()
    .describe('Path to the CodeQL query file (.ql or .qlref)'),
  language: z
    .enum(SUPPORTED_LANGUAGES)
    .optional()
    .describe('Programming language of the query (auto-derived from pack metadata when omitted)'),

server/src/prompts/workflow-prompts.ts:454

  • qlLspIterativeDevelopmentSchema now has language optional, but the schema comment still states language and queryPath are required. Please update the comment to match the schema (language omitted -> auto-derive + warning).
/**
 * Schema for ql_lsp_iterative_development prompt parameters.
 *
 * - `language` and `queryPath` are **required** – LSP tools need both.
 * - `workspaceUri` is optional – defaults to the pack root.
 */
export const qlLspIterativeDevelopmentSchema = z.object({
  queryPath: z
    .string()
    .describe('Path to the query file being developed'),
  language: z
    .enum(SUPPORTED_LANGUAGES)
    .optional()
    .describe('Programming language for the query (auto-derived from pack metadata when omitted)'),
  • Files reviewed: 13/15 changed files
  • Comments generated: 9

File watcher events (database discovery, query result creation) were
triggering envBuilder.invalidate() + mcpProvider.fireDidChange(), causing
VS Code to re-query provideMcpServerDefinitions() on every workspace
file change. The debounce only coalesced rapid events but did not prevent
the unnecessary re-provision cycle.

The MCP server definition only needs to change when:
- The extension itself changes (update/reinstall)
- Workspace folder registration changes (folders added/removed)
- Configuration changes that affect the server

The running server discovers databases and query results on its own
through filesystem scanning at tool invocation time, so notifying
VS Code of file content changes is unnecessary.

Also includes:
- Prompt completion caching with 5s TTL to avoid repeated filesystem
  scans during rapid completion requests
- Debounce timer cancellation when McpProvider is disposed
- Unit tests verifying watchers do not trigger fireDidChange
- Integration tests verifying file creation does not fire
  onDidChangeMcpServerDefinitions
@data-douser data-douser changed the title [UPDATE PRIMITIVE] Add MCP prompt argument completions for VS Code slash command UX Improve ql-mcp VS Code extension UX Apr 7, 2026
@data-douser data-douser requested a review from Copilot April 7, 2026 20:33
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves the ql-mcp VS Code extension and server prompt UX by adding MCP prompt argument completions, refining watcher/restart behavior, strengthening CLI resolution robustness, and expanding automated test coverage.

Changes:

  • Add prompt argument completion providers (language + file/path discovery) and wire them into workflow prompt registrations.
  • Make several workflow prompt language parameters optional with auto-derivation from CodeQL pack metadata and updated handler messaging/tests.
  • Improve extension-side robustness/UX via CLI resolution concurrency control, debounced MCP definition change notifications, clearer logging, and new unit/integration tests.
Show a summary per file
File Description
server/src/prompts/prompt-completions.ts Adds completion callbacks + schema enhancement via completable() and language auto-derivation from pack metadata.
server/src/prompts/workflow-prompts.ts Makes language optional for several prompts, derives language from pack metadata, and applies addCompletions() to prompt shapes.
server/test/src/prompts/prompt-completions.test.ts Adds unit tests covering completion behavior, caching, schema enhancement, and pack-language derivation.
server/test/src/prompts/workflow-prompts.test.ts Updates schema/handler tests for optional language and updated warning behavior.
server/dist/codeql-development-mcp-server.js Updates bundled build artifact to include the new prompt completion functionality and schema changes.
extensions/vscode/src/codeql/cli-resolver.ts Adds in-flight resolution deduplication and validation for PATH-discovered CLI binaries.
extensions/vscode/test/codeql/cli-resolver.test.ts Adds tests for PATH version detection, validation failure fallback, and concurrent resolution behavior.
extensions/vscode/src/server/mcp-provider.ts Debounces fireDidChange() notifications and cancels pending debounce on restart.
extensions/vscode/test/server/mcp-provider.test.ts Adds unit tests validating debounce/coalescing behavior and restart cancellation semantics.
extensions/vscode/src/extension.ts Stops invalidating/re-providing MCP definitions on file-content watcher events; keeps watchers for logging/state only.
extensions/vscode/test/extension.test.ts Adds tests ensuring watcher events do not trigger MCP definition updates or env invalidation.
extensions/vscode/src/server/server-manager.ts Clarifies bundled server log message (“Bundled server ready”).
extensions/vscode/test/server/server-manager.test.ts Updates assertions to match the new bundled server log wording and ensures no “npm install” mention.
extensions/vscode/src/server/pack-installer.ts Improves logging around CLI/target versions, download/install flow, and per-language success summaries.
extensions/vscode/test/server/pack-installer.test.ts Adds tests for new logging behaviors and summary counts.
extensions/vscode/src/bridge/database-watcher.ts Logs discovered/removed databases using relative paths for readability.
extensions/vscode/src/bridge/query-results-watcher.ts Logs created BQRS/SARIF results using relative paths for readability.
extensions/vscode/__mocks__/vscode.ts Extends workspace mock with asRelativePath and updateWorkspaceFolders for tests.
extensions/vscode/test/suite/mcp-server.integration.test.ts Adds an integration test asserting CODEQL_PATH shape when available.
extensions/vscode/test/suite/mcp-completion-e2e.integration.test.ts Adds end-to-end tests that exercise MCP completion/complete against the real server in the extension host.
extensions/vscode/test/suite/file-watcher-stability.integration.test.ts Adds integration tests ensuring file changes do not trigger redundant MCP definition change events.
extensions/vscode/esbuild.config.js Registers the new VS Code integration test entry points for esbuild compilation.

Copilot's findings

Comments suppressed due to low confidence (3)

server/src/prompts/workflow-prompts.ts:1034

  • The warning advises ensuring a codeql/<lang>-all dependency, but resolveLanguageFromPack() also resolves languages from codeql/<lang>-queries. To avoid misleading guidance, update the message to mention both -all and -queries (or align the resolver + message to the same rule).
        if (!effectiveLanguage) {
          warnings.push('⚠ **Language could not be auto-derived.** Please provide the `language` parameter or ensure the query is inside a CodeQL pack with a `codeql/<lang>-all` dependency.');
        }

server/src/prompts/workflow-prompts.ts:1098

  • The warning advises ensuring a codeql/<lang>-all dependency, but resolveLanguageFromPack() also resolves languages from codeql/<lang>-queries. To avoid misleading guidance, update the message to mention both -all and -queries (or align the resolver + message to the same rule).
        if (!effectiveLanguage) {
          warnings.push('⚠ **Language could not be auto-derived.** Please provide the `language` parameter or ensure the query is inside a CodeQL pack with a `codeql/<lang>-all` dependency.');
        }

server/src/prompts/workflow-prompts.ts:1215

  • The warning advises ensuring a codeql/<lang>-all dependency, but resolveLanguageFromPack() also resolves languages from codeql/<lang>-queries. To avoid misleading guidance, update the message to mention both -all and -queries (or align the resolver + message to the same rule).
        if (!effectiveLanguage) {
          warnings.push('⚠ **Language could not be auto-derived.** Please provide the `language` parameter or ensure the query is inside a CodeQL pack with a `codeql/<lang>-all` dependency.');
        }
  • Files reviewed: 21/23 changed files
  • Comments generated: 5

@data-douser data-douser marked this pull request as ready for review April 7, 2026 21:43
@data-douser data-douser requested review from a team and enyil as code owners April 7, 2026 21:43
Copilot AI review requested due to automatic review settings April 7, 2026 21:43
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves the ql-mcp VS Code extension and MCP server prompt UX by adding prompt-argument completions (for better slash-command input), making several workflow prompt parameters more robust (e.g., optional language with auto-derivation), and reducing noisy/redundant extension definition-change events via watcher behavior changes and debouncing.

Changes:

  • Add MCP prompt argument completion providers (language + workspace file/path discovery) and wire them into workflow prompt registration.
  • Make language optional for several workflow prompts and auto-derive it from codeql-pack.yml when possible, emitting warnings when it can’t be derived.
  • Improve VS Code extension robustness: CLI resolution concurrency/validation, pack install/download logging, watcher behavior, and debounced MCP definition-change notifications; expand unit/integration test coverage accordingly.
Show a summary per file
File Description
server/test/src/prompts/workflow-prompts.test.ts Updates prompt schema/handler tests to reflect optional language and new warning behavior.
server/test/src/prompts/prompt-completions.test.ts Adds unit tests for completion providers, caching, directory filtering, and pack-language derivation.
server/test/src/prompts/constants.test.ts Adds tests ensuring shared SUPPORTED_LANGUAGES constant is exported and sorted.
server/src/prompts/workflow-prompts.ts Makes language optional for select prompts, auto-derives language from pack metadata, and attaches completion metadata to prompt schemas.
server/src/prompts/prompt-completions.ts Introduces completion providers (language/query/db/sarif/packRoot) plus schema enhancement via completable().
server/src/prompts/constants.ts Moves shared prompt constants (supported languages) to a dedicated module to avoid circular deps.
server/dist/codeql-development-mcp-server.js Updates bundled server output to include new prompt completion and prompt behavior changes.
extensions/vscode/test/suite/mcp-server.integration.test.ts Adds an integration assertion around CODEQL_PATH shape when present.
extensions/vscode/test/suite/mcp-completion-e2e.integration.test.ts Adds end-to-end tests that invoke MCP completion/complete for prompt arguments.
extensions/vscode/test/suite/file-watcher-stability.integration.test.ts Adds integration coverage ensuring file changes don’t spuriously trigger definition updates.
extensions/vscode/test/server/server-manager.test.ts Updates expectations for revised “bundled server ready” logging.
extensions/vscode/test/server/pack-installer.test.ts Adds tests for new pack install/download logging and success-count summaries.
extensions/vscode/test/server/mcp-provider.test.ts Adds unit tests for debounced fireDidChange, restart behavior, and disposal.
extensions/vscode/test/extension.test.ts Adds tests ensuring watcher events don’t trigger environment invalidation or definition change events.
extensions/vscode/test/codeql/cli-resolver.test.ts Adds tests for PATH validation/version detection, concurrent resolution, and invalidation of in-flight resolve.
extensions/vscode/src/server/server-manager.ts Refines bundled-server readiness log message for clarity.
extensions/vscode/src/server/pack-installer.ts Enhances logging (CLI/target versions, download vs bundled install, per-language success counts).
extensions/vscode/src/server/mcp-provider.ts Debounces fireDidChange, cancels pending debounce on restart/dispose.
extensions/vscode/src/extension.ts Stops treating watcher file events as a trigger for MCP server definition changes (logging/state only).
extensions/vscode/src/codeql/cli-resolver.ts Prevents duplicate concurrent CLI resolutions, validates PATH results, and discards stale in-flight results after invalidation.
extensions/vscode/src/bridge/query-results-watcher.ts Logs watcher events using relative paths for readability.
extensions/vscode/src/bridge/database-watcher.ts Logs discovered/removed databases using relative paths for readability.
extensions/vscode/esbuild.config.js Adds new integration test entry points to the extension test build config.
extensions/vscode/mocks/vscode.ts Extends VS Code workspace mock with asRelativePath and updateWorkspaceFolders.

Copilot's findings

  • Files reviewed: 23/25 changed files
  • Comments generated: 3

@data-douser
Copy link
Copy Markdown
Collaborator

@copilot apply changes based on the comments in this thread

…EffectiveLanguage helper, add Windows env stubs

- Centralize directory skip list into SKIP_DIRS set used by
  findFilesByExtension, findDatabaseDirs, and completePackRoot
  (adds dist/, coverage/, build/, .github/ to completePackRoot)
- Extract getEffectiveLanguage() helper to eliminate duplicated
  language auto-derivation logic across 4 prompt handlers
- Add Windows env var stubs (HOMEDRIVE, HOMEPATH, USERPROFILE)
  to database completion tests for cross-platform compatibility
- Add 5 unit tests for getEffectiveLanguage()

Agent-Logs-Url: https://github.com/advanced-security/codeql-development-mcp-server/sessions/e315dcb4-ed12-428b-8294-14b398746c4c

Co-authored-by: data-douser <70299490+data-douser@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Apr 7, 2026

@copilot apply changes based on the comments in this thread

All three review comments addressed in 63247cc:

  1. completePackRoot() skip list — Centralized all directory skip lists into a shared SKIP_DIRS set, so completePackRoot() now skips dist/, coverage/, build/, .github/ (matching findFilesByExtension() and findDatabaseDirs()).

  2. Windows env var stubs — Added HOMEDRIVE, HOMEPATH, and USERPROFILE stubs to the completeDatabasePath default search path tests for cross-platform compatibility.

  3. Duplicated language auto-derivation — Extracted getEffectiveLanguage() helper in prompt-completions.ts and replaced all 4 duplicated instances in workflow-prompts.ts. Added 5 unit tests for the new helper.

Extract SKIP_DIRS from prompt-completions.ts and
search-ql-code.ts into a shared scan-exclude module
with a comprehensive default list of 20 directories.

The exclusion set is configurable via the env var
CODEQL_MCP_SCAN_EXCLUDE_DIRS (comma-separated).
Entries prefixed with ! remove a default (negation).

Add codeql-mcp.scanExcludeDirs VS Code setting that
the extension passes to the server as the env var.

New files:
- server/src/lib/scan-exclude.ts
- server/test/src/lib/scan-exclude.test.ts

Modified:
- server/src/prompts/prompt-completions.ts
- server/src/tools/codeql/search-ql-code.ts
- extensions/vscode/package.json
- extensions/vscode/src/bridge/environment-builder.ts
- extensions/vscode/test/bridge/environment-builder.test.ts
- server/test/src/prompts/prompt-completions.test.ts
Copilot AI review requested due to automatic review settings April 7, 2026 23:20
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds MCP prompt argument auto-completions and optional language auto-derivation to improve the ql-mcp VS Code extension UX, while also hardening extension-side server lifecycle behavior (CLI resolution, pack install logging, and reduced noisy definition-change events).

Changes:

  • Introduce server-side prompt argument completions (completion/complete) with caching and shared scan-exclude configuration.
  • Make language optional for select workflow prompts and auto-derive it from nearest codeql-pack.yml dependencies.
  • Improve extension robustness: serialized CLI resolution, clearer pack installer logging, debounced MCP definition change notifications, and quieter file watchers.
Show a summary per file
File Description
server/test/src/prompts/workflow-prompts.test.ts Updates schema/handler expectations for optional language and auto-derivation warnings.
server/test/src/prompts/prompt-completions.test.ts Adds unit tests for completion providers, caching, schema wrapping, and language derivation.
server/test/src/prompts/constants.test.ts Verifies SUPPORTED_LANGUAGES export and ordering from the new constants module.
server/test/src/lib/scan-exclude.test.ts Tests shared scan-exclude defaults, env var merging/negation, and membership checks.
server/src/tools/codeql/search-ql-code.ts Uses shared configurable scan-exclude set during traversal.
server/src/prompts/workflow-prompts.ts Wraps all prompt shapes with addCompletions() and uses getEffectiveLanguage() for select prompts.
server/src/prompts/prompt-completions.ts Implements completion providers, caching, schema enhancement via completable(), and pack-based language derivation.
server/src/prompts/constants.ts Extracts SUPPORTED_LANGUAGES to break circular imports.
server/src/lib/scan-exclude.ts Adds shared configurable directory exclusion list for workspace scanning.
server/dist/codeql-development-mcp-server.js Updates bundled build output to include new server functionality.
extensions/vscode/test/suite/mcp-server.integration.test.ts Adds an integration assertion around CODEQL_PATH shape when available.
extensions/vscode/test/suite/mcp-completion-e2e.integration.test.ts Adds e2e coverage for MCP prompt argument completions.
extensions/vscode/test/suite/file-watcher-stability.integration.test.ts Ensures file content events don’t trigger MCP definition change events.
extensions/vscode/test/server/server-manager.test.ts Updates expected log messaging for bundled server readiness.
extensions/vscode/test/server/pack-installer.test.ts Adds tests for updated pack install/download logging and summaries.
extensions/vscode/test/server/mcp-provider.test.ts Adds tests for debounced fireDidChange() and dispose behavior.
extensions/vscode/test/extension.test.ts Ensures database/query watcher events don’t invalidate env or fire definition changes.
extensions/vscode/test/codeql/cli-resolver.test.ts Adds tests for in-flight invalidation handling, PATH validation, and concurrency.
extensions/vscode/test/bridge/environment-builder.test.ts Tests propagation of scanExcludeDirs setting into CODEQL_MCP_SCAN_EXCLUDE_DIRS.
extensions/vscode/src/server/server-manager.ts Adjusts bundled-server log wording.
extensions/vscode/src/server/pack-installer.ts Adds clearer per-language logging plus success/failure summaries; uses “download” terminology for pack downloads.
extensions/vscode/src/server/mcp-provider.ts Debounces definition-change notifications and clears timers on dispose/restart.
extensions/vscode/src/extension.ts Stops invalidating env / firing definition changes on database/query-results watcher events.
extensions/vscode/src/codeql/cli-resolver.ts Serializes resolution, validates PATH-discovered binaries, and discards stale in-flight results after invalidation.
extensions/vscode/src/bridge/query-results-watcher.ts Uses workspace-relative paths in logs.
extensions/vscode/src/bridge/environment-builder.ts Exposes scanExcludeDirs setting to server via env var.
extensions/vscode/src/bridge/database-watcher.ts Switches to workspace-relative logging for discovered/removed databases.
extensions/vscode/package.json Adds codeql-mcp.scanExcludeDirs setting documentation.
extensions/vscode/esbuild.config.js Adds new integration test entry points for compilation.
extensions/vscode/mocks/vscode.ts Adds workspace.asRelativePath to support updated logging in tests.

Copilot's findings

Comments suppressed due to low confidence (1)

extensions/vscode/src/bridge/database-watcher.ts:72

  • Same issue as handleDatabaseDiscovered(): dbRoot uses a Windows-only path separator regex, so on POSIX the watcher will fail to remove codeql-database.yml from the path and knownDatabases.delete() will likely never match the stored root. Use path.dirname() (or otherwise normalize separators) to compute the database root reliably across platforms.
  private handleDatabaseRemoved(ymlPath: string): void {
    const dbRoot = ymlPath.replace(/\/codeql-database\.yml$/, '');
    if (this.knownDatabases.delete(dbRoot)) {
      this.logger.info(`Database removed: ${vscode.workspace.asRelativePath(dbRoot)}`);
  • Files reviewed: 29/31 changed files
  • Comments generated: 1

Adds "on.pull_request" and "on.push" triggers for the "next" branch
for actions workflows with equivalent triggers for the "main" branch.
@data-douser data-douser linked an issue Apr 7, 2026 that may be closed by this pull request
@data-douser data-douser merged commit 36631d9 into main Apr 8, 2026
29 checks passed
@data-douser data-douser deleted the copilot/improve-vscode-extension-ux branch April 8, 2026 00:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support next branch as long-lived prerelease branch alongside main Improve vscode extension UX for ql-mcp workflow prompts

3 participants