Repository navigation
mcp: expand ${VAR} in workspace .mcp.json servers in the local harness - #340369
Merged
Vritant Bhardwaj (vritant24) merged 1 commit intoOct 7, 2026
Merged
Vritant Bhardwaj (vritant24) merged 1 commit into
Vritant Bhardwaj (vritant24) merged 1 commit into
Conversation
#340161 plans for the migration from `.vscode/mcp.json` to `.mcp.json` to rewrite VS Code inputs and `${env:X}` as `${NAME}` / `${NAME:-default}` environment variable references. The local harness passes those through literally, so a migrated server would break if the user switched back from the agent host, and a literal `"API_KEY": "${API_KEY}"` would override the inherited variable. Workspace `.mcp.json` servers now expand `${VAR}` and `${VAR:-default}` with the Copilot runtime's rules (ported resolver and tests in platform/mcp/common/envVarResolution.ts), in `command`, `args`, `env` values, the URL and header values. Env keys and header names are never expanded. Bare `$VAR` stays literal: the migration copies it unchanged and it was always literal in VS Code. `cwd`, the Copilot user config, `.vscode/mcp.json`, user `mcp.json`, plugins, extensions and other discovery sources are unchanged. The extension host that runs or connects to the server expands with its own `process.env` (case-insensitive on Windows, like `${env:}`), before policy checks. The URL is expanded from the raw string, and the trust nonce stays based on the unexpanded configuration. The web worker host leaves references literal. Refs #340161 Co-authored-by: Copilot <[email protected]>
Contributor
📬 CODENOTIFYThe following users are being notified based on files changed in this PR: TylerLeonhardtMatched files:
|
roblourens
approved these changes
Oct 7, 2026
3 of 42 tasks
Vritant Bhardwaj (vritant24)
enabled auto-merge
October 7, 2026 21:18
Contributor
There was a problem hiding this comment.
🟢 Approval recommended
Expansion scope, host routing, serialization, and edge-case semantics are consistently implemented and tested.
0 open findings
What changed in this PR
Adds Copilot-compatible environment-variable expansion for workspace .mcp.json servers in the local MCP harness.
Changes:
- Implements
${VAR}and${VAR:-default}resolution. - Expands supported launch fields in the responsible extension host.
- Adds discovery, RPC, registry, and edge-case coverage.
| File | Description |
|---|---|
src/vs/platform/mcp/common/envVarResolution.ts |
Implements portable environment-variable resolution. |
src/vs/platform/mcp/test/common/envVarResolution.test.ts |
Tests parser and resolution semantics. |
src/vs/workbench/contrib/mcp/common/mcpEnvironmentVariableExpansion.ts |
Applies expansion to supported launch fields. |
src/vs/workbench/contrib/mcp/test/common/mcpEnvironmentVariableExpansion.test.ts |
Tests launch-field expansion boundaries. |
src/vs/workbench/contrib/mcp/common/mcpTypes.ts |
Adds expansion metadata to server definitions. |
src/vs/workbench/contrib/mcp/common/mcpRegistryTypes.ts |
Extends the host delegate contract. |
src/vs/workbench/contrib/mcp/common/mcpRegistry.ts |
Invokes host-side expansion during resolution. |
src/vs/workbench/contrib/mcp/common/discovery/workspaceDotMcpDiscovery.ts |
Flags workspace .mcp.json servers. |
src/vs/workbench/contrib/mcp/test/common/workspaceDotMcpDiscovery.test.ts |
Verifies flags and unchanged trust data. |
src/vs/workbench/contrib/mcp/test/common/nativeMcpDiscoveryAdapters.test.ts |
Verifies native sources remain unflagged. |
src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts |
Tests registry expansion behavior. |
src/vs/workbench/contrib/mcp/test/common/mcpRegistryTypes.ts |
Updates the test registry delegate. |
src/vs/workbench/contrib/mcp/test/common/mcpServerConnection.test.ts |
Updates the connection test delegate. |
src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts |
Updates the request-handler test delegate. |
src/vs/workbench/api/common/extHost.protocol.ts |
Adds the expansion RPC contract. |
src/vs/workbench/api/browser/mainThreadMcp.ts |
Forwards expansion requests to the host. |
src/vs/workbench/api/common/extHostMcp.ts |
Defines web-host no-op behavior. |
src/vs/workbench/api/node/extHostMcpNode.ts |
Expands against Node’s process environment. |
src/vs/workbench/api/test/browser/mainThreadMcp.test.ts |
Tests expansion RPC forwarding. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Vritant Bhardwaj (vritant24)
deleted the
agents/expand-env-vars-in-mcp-config-files
branch
October 7, 2026 21:38
Vritant Bhardwaj (vritant24)
added a commit
that referenced
this pull request
Oct 7, 2026
<!-- Thank you for submitting a Pull Request. Please: * Read our Pull Request guidelines: https://github.com/microsoft/vscode/wiki/How-to-Contribute#pull-requests * Associate an issue with the Pull Request. * Ensure that the code is up-to-date with the `main` branch. * Include a description of the proposed changes and how to test them. --> Refs #340161 (task **B1**). Builds on #340369 (merged) and matches #340379. ## Problem The MCP customization migrator refused every server that used `${env:NAME}`, so those servers stayed in `.vscode/mcp.json` and the user `mcp.json`. ## Changes **Rewrite.** `${env:NAME}` becomes `${NAME}`, never the variable's current value, in the fields that both the Copilot runtime and the local harness expand: - stdio `command`, `args` and `env` values; - the remote URL and header values. Other portable variables (`${workspaceFolder}`, `${/}`, …) are still resolved to literals exactly as before. **Implementation** (`mcpServerCustomizationMigration.ts`): - `analyzeSourceConfiguration` replaces `resolveSourceConfiguration`. Planning, the check before writing, and rollback all use this one function, so they always agree. - Portable variables are resolved one at a time and `${env:}` is skipped. Resolving `${env:FOO}` to `${FOO}` inside a `ConfigurationResolverExpression` would make it re-parse `${FOO}` as a new, unknown variable. - Candidates get an optional `migratedConfiguration`: the content written to the destination. It's separate from `projectedConfiguration`, which still holds the current env values and is used to detect stale candidates. **Exclusions.** These servers stay behind, each with a localized reason: | Case | Reason | |---|---| | `${env:}` in an env or header **name**; neither the runtime nor the harness expands names (C4, C9) | `environmentVariableInName` | | Name isn't `[A-Za-z_][A-Za-z0-9_]*`, e.g. `${env:ProgramFiles(x86)}`, `${env:my-var}`, `${env:HOST:-x}` | `invalidEnvironmentVariableName` | | Rewritten value is over 1000 UTF-16 code units; the runtime skips expansion above that | `environmentVariableValueTooLong` | | URL fails `URL.canParse` after the rewrite: a port, the scheme, or the whole URL (C7; same rule as #340379) | `unsupportedEnvironmentVariableInUrl` | | `${env:}` mixed with a non-portable variable (`${input:}`, `${config:}`, `${userHome}`, …), or `${env:}` in `cwd` | `unrepresentableConfiguration` (unchanged) | | A referenced variable's value itself contains a `${...}` variable: VS Code resolves it, but the destination keeps the value as is | `unrepresentableConfiguration` | **User scope** (`mcp.json` → `~/.copilot/mcp-config.json`): - User servers are forwarded with their variables unresolved. Those whose only compatibility problem is `UnresolvedConfiguration` can now be planned. - They're compared against the source with `${env:}` left as written; any other variable still excludes the server. - `CopilotMpcDiscoveryAdapter` now sets `environmentVariableExpansion`, using the raw URL, so a migrated `${NAME}` keeps working in VS Code's own chat. ## Notes for reviewers - **Behaviour change for unset variables (decision a):** VS Code resolves an unset `${env:FOO}` to `""`, but the runtime and the local harness leave an unset `${FOO}` as literal text. We chose `${NAME}` over `${NAME:-}` for readability, for consistency with the issue's Decision, and because a host with a `:-` default is rejected (C7). D5/E3 will add the unset-variable warning. - **Copilot user config expansion (decision b):** existing literal `${FOO}` strings in `~/.copilot/mcp-config.json` are now expanded in VS Code, matching the Copilot runtime. Trust nonces are still computed from the unexpanded launch. - **URLs are still blocked by E11 in practice:** the forwarded projection builds `url` from `launch.uri.toString()`, which percent-encodes `${env:…}`, so it never matches the source. The URL rewrite and C7 exclusion are implemented and tested, but real URL servers with `${env:}` stay excluded (as unrepresentable) until E11 is fixed. Header values are unaffected. - No changes to `parseWorkspaceRootMcpConfiguration` or the `chat.mcp.discovery.enabled` default (#340181). ## How to test I ran each of these on this branch: - `npm run build-fast -- --client-only`: **passed** - `./scripts/test.sh --reporter dot --run src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpServerCustomizationMigration.test.ts --run src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationMigrationServiceImpl.test.ts --run src/vs/workbench/contrib/mcp/test/common/nativeMcpDiscoveryAdapters.test.ts --run src/vs/workbench/contrib/mcp/test/common/workspaceDotMcpDiscovery.test.ts --run src/vs/workbench/contrib/mcp/test/common/mcpEnvironmentVariableExpansion.test.ts --run src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts --run src/vs/platform/mcp/test/common/envVarResolution.test.ts --run src/vs/workbench/api/test/browser/mainThreadMcp.test.ts`: **passed, 226 passing** - The same three migration/discovery files with `--grep 'env:|Copilot user configuration'`: **passed, 7 passing**. These are all the new tests: - rewriting in every supported position, mixed with `${workspaceFolder}`, a shared variable, and a value at exactly 1000 characters; - every exclusion case, checked at both planning and execution; - user-scope servers; - a source that changed between planning and writing; - rollback followed by a successful retry; - provider exclusion details; - Copilot adapter expansion. - `npm run typecheck-client`: **passed** - `npm run eslint -- <8 changed files>`: **passed**; the pre-commit hygiene check also passed. The tests ran before merging #340375 (agent-host structured tool results) from `main`, which doesn't touch these files. Not tested manually end to end against a live Copilot agent-host session. Manual check: in a workspace whose `.vscode/mcp.json` has a stdio server with `"env": { "TOKEN": "${env:TOKEN}" }`, run the customization migration from an agent-host Copilot session. The server should move to `.mcp.json` as `"TOKEN": "${TOKEN}"` with no secret value in the file, and should still start in VS Code chat.
Vritant Bhardwaj (vritant24)
added a commit
that referenced
this pull request
Oct 8, 2026
…40379) <!-- Thank you for submitting a Pull Request. Please: * Read our Pull Request guidelines: https://github.com/microsoft/vscode/wiki/How-to-Contribute#pull-requests * Associate an issue with the Pull Request. * Ensure that the code is up-to-date with the `main` branch. * Include a description of the proposed changes and how to test them. --> Follow-up to #340369. Part of #340161. #340369 expands `${VAR}` anywhere in a workspace `.mcp.json` server's URL. The Copilot runtime is stricter: it parses the URL as written, before expanding it, and rejects the server if it doesn't parse. As a result, some URLs now work in VS Code's own chat while the same server is rejected in Copilot sessions, which goes beyond what migration needs. ## Changes A URL is now expanded only if it parses as a URL (`URL.canParse`). Otherwise it's left unexpanded, as it was before #340369. | URL in `.mcp.json` | Copilot runtime | VS Code after this PR | |---|---|---| | Host, path, query: `https://${HOST}/mcp?key=${KEY}` | ✅ | ✅ expanded | | Default in path or query: `/${R:-eu}/mcp?k=${K:-x}` | ✅ | ✅ expanded | | Default in the host: `https://${HOST:-example.com}/mcp` | ❌ rejected | Left as written (was expanded) | | Port: `http://localhost:${PORT}/mcp` | ❌ rejected | Left as written (was expanded) | | Whole URL: `${BASE}/mcp` | ❌ rejected | Left as written (was expanded) | Header values are still expanded even when the URL isn't. ## Notes for reviewers - **Source for the Copilot behaviour:** `.mcp.json` servers go through `workspace_discovery.rs` → `parse_workspace_config` → `validate_server_config` → `validate_remote_server`, which calls `Url::parse` on the URL as written and drops the server with "url: Invalid url". I checked each URL form by running the runtime's `url` crate (2.5.8, toolchain 1.98.1). `URL.canParse` follows the same WHATWG standard and gave the same result for every form. - **Not changed:** a URL whose scheme is a variable (`${SCHEME}://...`) still makes VS Code drop every server in that `.mcp.json`, because `URI.parse` throws in `claudeConfigToServerDefinition`. That predates #340369. ## Validation - `npm run typecheck-client`: passed - `npm run build-fast -- --client-only`: passed - `./scripts/test.sh --reporter dot --run src/vs/platform/mcp/test/common/envVarResolution.test.ts --run src/vs/workbench/contrib/mcp/test/common/mcpEnvironmentVariableExpansion.test.ts --run src/vs/workbench/contrib/mcp/test/common/nativeMcpDiscoveryAdapters.test.ts --run src/vs/workbench/contrib/mcp/test/common/workspaceDotMcpDiscovery.test.ts --run src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts --run src/vs/workbench/api/test/browser/mainThreadMcp.test.ts --run src/vs/workbench/contrib/mcp/test/common/mcpServerConnection.test.ts --run src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts`: 169 passing, 14 pending (from an existing `.skip`) - `npm run eslint -- <changed files>`: clean
Wing K.Y (wingwkyuen)
pushed a commit
to tcgoidc/vscode
that referenced
this pull request
Oct 8, 2026
The Copilot runtime parses a remote server's URL as written, before expanding variables, and rejects the server if it doesn't parse (a variable in the port or scheme, a whole-URL variable, or a host with a `:-` default). Leave such URLs unexpanded, as before microsoft#340369, so a `.mcp.json` server never works in VS Code's chat while being rejected in Copilot sessions. Header values are still expanded. Refs microsoft#340161 Co-authored-by: Copilot <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #340161 (task E2).
#340161 plans for the migration from
.vscode/mcp.jsonto.mcp.jsonto rewrite VS Code inputs and${env:X}as${NAME}/${NAME:-default}. Copilot agent sessions expand those references, but VS Code's own (local) MCP harness passes them to the server as literal text. A migrated server would therefore break if the user switched back from the agent host.It's also worse than a no-op. The server starts with the host environment and the configured
envis applied on top, so a literal"API_KEY": "${API_KEY}"replaces the realAPI_KEYthe server would otherwise inherit.Changes
Workspace
.mcp.jsonservers now expand${VAR}and${VAR:-default}with the Copilot runtime's rules.command, each ofargs,envvaluesenvnames,cwdprocess.env. On Windows, names match case-insensitively, as${env:X}does.How it works:
WorkspaceDotMcpDiscoverymarks each server with a newenvironmentVariableExpansionfield on the definition, keeping the URL exactly as written. Parsing it as aURIwould encodehttps://${HOST}/mcpashttps://%24%7Bhost%7D/mcp.McpRegistry.resolveConnectionasks the host delegate to expand any marked launch that contains a reference. This runs after VS Code's own variable resolution and before the dev-mode, sandbox and allowed/denied-servers checks.MainThreadMcpforwards the request over a new$expandEnvironmentVariablesRPC. The Node extension host expands it; the web worker extension host has no environment and returns the launch unchanged.The resolver in
src/vs/platform/mcp/common/envVarResolution.tsis a port of the runtime'senv_var_resolution.rs, and its tests are ported too, so the two stay in sync. The field mapping is insrc/vs/workbench/contrib/mcp/common/mcpEnvironmentVariableExpansion.ts.Unchanged
$VARstays literal. The migrator copies it unchanged from.vscode/mcp.json, where VS Code never expanded it (for example a shell-quotedecho '$HOME'inargs).${env:X},${input:x}and${secret:x}stay literal: they don't match the${NAME}grammar..vscode/mcp.json, usermcp.json,~/.copilot/mcp-config.json, plugins, extensions, Claude Desktop, Cursor and Windsurf are unchanged.Notes for reviewers
${env:}or${input:}, and replaces${workspaceFolder}and similar variables with literal values. This PR is groundwork for B1 and A1–A7 in Support migrating MCP inputs and ${...} variables to portable .mcp.json / Copilot mcp-config.json #340161. Until those land, it only changes hand-written.mcp.jsonfiles that use${VAR}.connection.launchDefinition, so they need the expanded values. As with${env:}today, expanded env and header values travel back to the renderer over RPC.$VARisn't expanded;commandandargsare resolved against the host environment, not the server's ownenvblock, matching how${env:X}behaved before migration;cwdisn't honored or expanded, because the migrator skips servers that set it;GITHUB_TOKENandGIT_CONFIG_*injection, OIDC tokens,${secret:}).IMcpHostDelegate.expandEnvironmentVariables, implemented byMainThreadMcpand the test delegates.workspaceDotMcpDiscovery.test.tsandnativeMcpDiscoveryAdapters.test.ts. This branch merges cleanly withmaintoday, and the hunks are independent.