Skip to content

mcp: expand ${VAR} in workspace .mcp.json servers in the local harness - #340369

Merged
Vritant Bhardwaj (vritant24) merged 1 commit into
mainfrom
agents/expand-env-vars-in-mcp-config-files
Oct 7, 2026
Merged

Vritant Bhardwaj (vritant24) merged 1 commit into
mainfrom
agents/expand-env-vars-in-mcp-config-files

Conversation

@vritant24

@vritant24 Vritant Bhardwaj (vritant24) commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Part of #340161 (task E2).

#340161 plans for the migration from .vscode/mcp.json to .mcp.json to 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 env is applied on top, so a literal "API_KEY": "${API_KEY}" replaces the real API_KEY the server would otherwise inherit.

Changes

Workspace .mcp.json servers now expand ${VAR} and ${VAR:-default} with the Copilot runtime's rules.

Expanded Never expanded
Local (stdio) command, each of args, env values env names, cwd
Remote (HTTP) URL (host, path, query), header values header names
  • Unset with no default: left as written. Set but empty: the empty value is used, not the default.
  • Defaults: inserted literally and never expanded again.
  • Long strings: anything over 1000 characters is left unchanged.
  • Where values come from: the extension host that runs or connects to the server (local or remote), using its own process.env. On Windows, names match case-insensitively, as ${env:X} does.

How it works:

  1. WorkspaceDotMcpDiscovery marks each server with a new environmentVariableExpansion field on the definition, keeping the URL exactly as written. Parsing it as a URI would encode https://${HOST}/mcp as https://%24%7Bhost%7D/mcp.
  2. McpRegistry.resolveConnection asks 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.
  3. MainThreadMcp forwards the request over a new $expandEnvironmentVariables RPC. 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.ts is a port of the runtime's env_var_resolution.rs, and its tests are ported too, so the two stay in sync. The field mapping is in src/vs/workbench/contrib/mcp/common/mcpEnvironmentVariableExpansion.ts.

Unchanged

  • Bare $VAR stays literal. The migrator copies it unchanged from .vscode/mcp.json, where VS Code never expanded it (for example a shell-quoted echo '$HOME' in args).
  • ${env:X}, ${input:x} and ${secret:x} stay literal: they don't match the ${NAME} grammar.
  • Trust: the cache/trust nonce is still computed from the unexpanded config, so changing an env var never re-prompts for trust.
  • Other sources: .vscode/mcp.json, user mcp.json, ~/.copilot/mcp-config.json, plugins, extensions, Claude Desktop, Cursor and Windsurf are unchanged.

Notes for reviewers

  • Doesn't affect migrated servers yet. Today the migrator skips any server that uses ${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.json files that use ${VAR}.
  • Why expand through the delegate rather than only at spawn time: the allowed/denied-servers check and other renderer consumers read connection.launchDefinition, so they need the expanded values. As with ${env:} today, expanded env and header values travel back to the renderer over RPC.
  • Where this differs from the Copilot runtime:
    • bare $VAR isn't expanded;
    • command and args are resolved against the host environment, not the server's own env block, matching how ${env:X} behaved before migration;
    • cwd isn't honored or expanded, because the migrator skips servers that set it;
    • the runtime-only environment handling isn't ported (blocked-variable filter, GITHUB_TOKEN and GIT_CONFIG_* injection, OIDC tokens, ${secret:}).
  • New delegate method: IMcpHostDelegate.expandEnvironmentVariables, implemented by MainThreadMcp and the test delegates.
  • Overlap with mcp: discover Copilot CLI user MCP config by default without forwarding it #340181: both touch workspaceDotMcpDiscovery.test.ts and nativeMcpDiscoveryAdapters.test.ts. This branch merges cleanly with main today, and the hunks are independent.

#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]>
Copilot AI balanced review requested due to automatic review settings October 7, 2026 21:07
@vs-code-engineering

Copy link
Copy Markdown
Contributor

📬 CODENOTIFY

The following users are being notified based on files changed in this PR:

TylerLeonhardt

Matched files:

  • src/vs/workbench/api/browser/mainThreadMcp.ts
  • src/vs/workbench/api/common/extHostMcp.ts

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 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.

@vritant24
Vritant Bhardwaj (vritant24) merged commit 20f57d8 into main Oct 7, 2026
36 checks passed
@vritant24
Vritant Bhardwaj (vritant24) deleted the agents/expand-env-vars-in-mcp-config-files branch October 7, 2026 21:38
@vs-code-engineering vs-code-engineering Bot added this to the 1.142.0 milestone Oct 7, 2026
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]>
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.

3 participants