Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(mcp-market): isolate registry header variables from URLs
ct-jaryn0aadc674b4a2
diff --git a/docs/adr/README.md b/docs/adr/README.mdindex e995670e8..9d8340339 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -329,3 +329,4 @@ Each ADR includes:| 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) || turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted || provider-display-order | [Provider display order](provider-display-order.md) | Accepted |+| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |diff --git a/docs/adr/registry-header-variable-spelling.md b/docs/adr/registry-header-variable-spelling.mdnew file mode 100644index 000000000..32d98d83a--- /dev/null+++ b/docs/adr/registry-header-variable-spelling.md@@ -0,0 +1,60 @@+# ADR: Remote header variables accept the registry's `{name}` spelling++- Status: Proposed+- Date: 2026-09-20+- Deciders: Pending maintainer review+- Related: ADR 0245, E2E-MCP-MARKET-SEMANTICS++## Context++The official MCP registry spells a remote header variable `{name}` and declares+the name in the header's `variables` map. Its schema describes `variables` as+the values that replace "keys in the input `value` that are wrapped in+`{curly_braces}`". Declared names may use lower case, such as `api_key`.+The regression fixtures cover both cases; this ADR does not assert the+frequency of either spelling in the live registry.++The builtin catalog and stdio templates spell a template variable `${NAME}` in+upper case. The registry adapter and the catalog template matcher knew only+that spelling. In the reproduced mapping and resolution path, a registry+record using the official spelling retained `Authorization: Bearer {api_key}`+and had no `requiredEnv` entry. This establishes an unresolved template at+the parser boundary. The tests do not establish rendered install-sheet+behavior, actual HTTP transmission, or a user's observed response status.++## Decision++1. The registry adapter resolves `{name}` only when that same header declares+ it in `variables`; undeclared braces remain literal. Legacy `${NAME}` tokens+ keep working without a variables map. Names need not be upper case when+ declared by the registry. Each header owns its variable definitions.+2. Add optional `headerBindings` to the shared catalog template. Each header+ maps exact tokens to an editable `requiredEnv` input or a fixed literal.+ Same-named inputs in separate headers get distinct collision-safe names.+ Variable `default` prefills the editable input; omitted `isRequired` means+ optional. A fixed `value` is not editable and its content is never parsed+ again as a template. Bindings do not enter the host `McpServerInput` or+ persisted server config, so the runtime protocol remains unchanged.+3. Header templates accept both spellings and consume the `$`, so a `${NAME}`+ header resolves without a stray dollar. URL templates keep the legacy+ `${NAME}` spelling with upper-case names. A header declaration never makes+ bare `{name}` text in a URL editable or substitutable, including when the+ header has a default. `collectCatalogPlaceholders` and `resolveCatalogEntry`+ select the same pattern for each field, so discovery and resolution agree.+4. stdio templates keep the `${NAME}` spelling and the upper-case name rule.+ A brace pair inside a command or an argument is never rewritten, and the+ existing stdio contract is unchanged.+5. `requiredEnv` names are validated against the transport: variable names for+ `http`, environment-variable names for `stdio`.++## Consequences++- Declared editable header variables yield prompts and resolve according to+ their own defaults and requiredness. Fixed variables and unbound brace text+ do not create prompts. Header-local bindings prevent cross-header leakage+ of defaults, optional flags, and literal values. Bare URL tokens remain+ literal through mapping, resolution and host persistence; explicit legacy+ `${NAME}` URL templates retain their existing behavior.+- Builtin catalog entries and stdio packages behave exactly as before.+- The catalog can express a header variable that is not an environment variable+ name, which is what the registry publishes.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 29d07c29e..7915e7391 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13227,8 +13227,9 @@ plugin-form fixtures in an isolated temporary directory at runtime.| ID | Scenario | Verification ||---|---|---|| E2E-MCP-MARKET-NET-BOUNDARY | URL guard rejects credentials, loopback, private, special-use IPv4, v4-mapped, ULA, site-local and link-local bypass forms (trailing dot included); Main pins the checked public address and rechecks HTTPS redirects | deterministic guard assertions; source-contract coverage for DNS pin and bounded responses |-| E2E-MCP-MARKET-SEMANTICS | Registry records map to install templates preserving package versions, named/positional runtime/package arguments and required/optional env variables | deterministic mapping assertions |+| E2E-MCP-MARKET-SEMANTICS | Registry records map to install templates preserving package versions, named/positional runtime/package arguments and required/optional env variables; a remote header variable is recognized in both the registry's `{name}` and the catalog's `${NAME}` spelling, prompts for declared editable values, preserves unbound brace literals, and resolves header-local defaults, fixed values, and optional flags without merging same-named inputs across headers (ADR registry-header-variable-spelling) | deterministic mapping assertions || E2E-MCP-MARKET-INSTALL | Builtin catalog entry resolves through `resolveCatalogEntry` and installs via the host `mcp.upsert` RPC; record lands in `~/.agents/servers/` | real host binary, isolated temp HOME |+| E2E-MCP-MARKET-HEADER-SCOPE | Registry header-local `{token}` resolves only in its header; same-named URL path/query tokens remain literal through mapping, resolution, host upsert/list and persistence. URL templates retain only legacy `${NAME}` substitution | shared regressions plus real host binary with isolated temporary storage; remote entry disabled, no network call |#### E2E-SKILL-MARKET-NET-BOUNDARY: Public-HTTPS skill sources reject private and loopback URLsdiff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex c600c7b1f..056d2307b 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -7773,8 +7773,9 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture| ID | 场景 | 验证 ||---|---|---|| E2E-MCP-MARKET-NET-BOUNDARY | URL guard 拒绝凭据、回环、私网、special-use IPv4、v4-mapped、ULA、site-local 和 link-local 及尾点绕过形态;Main 固定已检查的公网地址并逐跳复核 HTTPS 重定向 | 确定性 guard 断言;DNS pin 与响应上限 source-contract 覆盖 |-| E2E-MCP-MARKET-SEMANTICS | Registry 记录映射为安装模板时保留包版本、named/positional runtime/package 参数与 required/optional 环境变量语义 | 确定性映射断言 |+| E2E-MCP-MARKET-SEMANTICS | Registry 记录映射为安装模板时保留包版本、named/positional runtime/package 参数与 required/optional 环境变量语义;远端 header 变量同时识别注册表的 `{name}` 与目录的 `${NAME}` 两种写法,仅为已声明的可编辑值显示输入,保留未声明花括号字面量,并按各 header 的作用域处理默认值、固定值与可选标记,不合并不同 header 的同名输入(ADR registry-header-variable-spelling) | 确定性映射断言 || E2E-MCP-MARKET-INSTALL | 内置目录条目经 `resolveCatalogEntry` 解析并通过宿主 `mcp.upsert` RPC 安装;记录落盘 `~/.agents/servers/` | 真实宿主二进制,隔离临时 HOME |+| E2E-MCP-MARKET-HEADER-SCOPE | Registry header-local `{token}` resolves only in its header; same-named URL path/query tokens remain literal through mapping, resolution, host upsert/list and persistence. URL templates retain only legacy `${NAME}` substitution | shared regressions plus real host binary with isolated temporary storage; remote entry disabled, no network call |#### E2E-SKILL-MARKET-NET-BOUNDARY:技能源公网 HTTPS 策略拒绝私网与回环diff --git a/packages/shared/src/mcp-catalog.test.ts b/packages/shared/src/mcp-catalog.test.tsindex 2a44c14bb..161a8caf4 100644--- a/packages/shared/src/mcp-catalog.test.ts+++ b/packages/shared/src/mcp-catalog.test.ts@@ -142,6 +142,21 @@ describe("resolveCatalogEntry", () => {expect(input.headers).toEqual({ Authorization: "Bearer tok" });});+ it("resolves only legacy URL tokens alongside header-local variables", () => {+ const entry: McpCatalogEntry = {+ ...httpTemplate,+ url: "https://api.example.com/${REGION}/{token}?literal=${token}",+ headers: { Authorization: "Bearer {token}" },+ headerBindings: { Authorization: { "{token}": { input: "token" } } },+ requiredEnv: [{ name: "REGION" }, { name: "token" }],+ };+ expect(collectCatalogPlaceholders({ ...entry, headers: {}, headerBindings: undefined })).toEqual(["REGION"]);+ const input = resolveCatalogEntry(entry, { REGION: "eu", token: "synthetic-secret" });+ expect(input.url).toBe("https://api.example.com/eu/{token}?literal=${token}");+ expect(input.headers).toEqual({ Authorization: "Bearer synthetic-secret" });+ expect(() => resolveCatalogEntry(entry, { token: "synthetic-secret" })).toThrow("missing value for REGION");+ });+it("substitutes values into stdio args and env", () => {const input = resolveCatalogEntry(stdioTemplate, {GITHUB_PAT: "pat-value",@@ -246,3 +261,31 @@ describe("validateMcpCatalogFile", () => {expect(warnings.join("\n")).toContain("public https");});});+++describe("header-local token bindings", () => {+ const entry: McpCatalogEntry = {+ id: "scoped", name: "Scoped", transport: "http", url: "https://example.com/mcp",+ headers: { "X-Test": "{literal} {input} {fixed}" },+ headerBindings: { "X-Test": { "{input}": { input: "key" }, "{fixed}": { value: "{input}" } } },+ requiredEnv: [{ name: "key" }],+ };++ it("collects editable references only and preserves literal replacements", () => {+ expect(collectCatalogPlaceholders(entry)).toEqual(["key"]);+ expect(resolveCatalogEntry(entry, { key: "synthetic" }).headers).toEqual({+ "X-Test": "{literal} synthetic {input}",+ });+ });++ it("validates input references and binding shapes", () => {+ expect(catalogEntryError({ ...entry, requiredEnv: [] })).toContain("placeholder key is not declared");+ for (const headerBindings of [+ { "X-Unknown": {} },+ { "X-Test": { "{input}": { input: "key", value: "both" } } },+ { "X-Test": { "{input}": { input: 3 } } },+ { "X-Test": { invalid: { value: "literal" } } },+ ]) expect(catalogEntryError({ ...entry, headerBindings })).not.toBeNull();+ expect(catalogEntryError({ ...entry, transport: "stdio", command: "node" })).toContain("requires http");+ });+});diff --git a/packages/shared/src/mcp-catalog.ts b/packages/shared/src/mcp-catalog.tsindex 9109a6dde..62138b269 100644--- a/packages/shared/src/mcp-catalog.ts+++ b/packages/shared/src/mcp-catalog.ts@@ -20,6 +20,9 @@ export type McpCatalogRequiredEnv = {defaultValue?: string;};+/** A registry header token resolves to a form input or a non-editable literal. */+export type McpCatalogHeaderBinding = { input: string } | { value: string };+export type McpCatalogEntry = {id: string;name: string;@@ -33,9 +36,11 @@ export type McpCatalogEntry = {command?: string;args?: string[];env?: Record<string, string>;- /** http template. Market endpoints must use credentials-free public HTTPS. */+ /** Public HTTPS template; only legacy `${NAME}` URL tokens are expanded. */url?: string;headers?: Record<string, string>;+ /** Header-local token bindings. Unbound text stays literal, including braces. */+ headerBindings?: Record<string, Record<string, McpCatalogHeaderBinding>>;requiredEnv?: McpCatalogRequiredEnv[];prerequisites?: string[];notes?: string;@@ -48,9 +53,18 @@ export type McpCatalogFile = {servers: McpCatalogEntry[];};-const PLACEHOLDER = /\$\{([A-Z_][A-Z0-9_]*)\}/g;-const CATALOG_CATEGORIES = new Set<McpCatalogCategory>(["devtools", "web", "docs", "data", "productivity"]);+/*+ * The builtin catalog and stdio templates spell a variable `${NAME}` in upper+ * case. The official registry spells a header variable `{name}` and does not+ * require upper case, so the header pattern accepts both spellings and consumes+ * the `$`, leaving no stray dollar behind. URLs and stdio keep their legacy+ * spelling; header-local brace tokens never authorize URL substitution.+ */+const ENV_PLACEHOLDER = /\$\{([A-Z_][A-Z0-9_]*)\}/g;+const HEADER_PLACEHOLDER = /\$?\{([A-Za-z_][A-Za-z0-9_]*)\}/g;const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;+const VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;+const CATALOG_CATEGORIES = new Set<McpCatalogCategory>(["devtools", "web", "docs", "data", "productivity"]);function isRecord(value: unknown): value is Record<string, unknown> {return !!value && typeof value === "object" && !Array.isArray(value);@@ -64,13 +78,14 @@ function isStringRecord(value: unknown): value is Record<string, string> {return isRecord(value) && Object.values(value).every((item) => typeof item === "string");}-function requiredEnvError(value: unknown, id: string): string | null {+function requiredEnvError(value: unknown, id: string, transport: unknown): string | null {if (!Array.isArray(value)) return `${id}: requiredEnv must be an array`;const names = new Set<string>();+ const namePattern = transport === "http" ? VARIABLE_NAME : ENV_NAME;for (const item of value) {if (!isRecord(item)) return `${id}: requiredEnv items must be objects`;- if (typeof item.name !== "string" || !ENV_NAME.test(item.name)) {- return `${id}: requiredEnv names must be environment variable names`;+ if (typeof item.name !== "string" || !namePattern.test(item.name)) {+ return `${id}: requiredEnv names must be variable names`;}if (names.has(item.name)) return `${id}: duplicate requiredEnv name ${item.name}`;names.add(item.name);@@ -87,6 +102,22 @@ function requiredEnvError(value: unknown, id: string): string | null {return null;}+function headerBindingsError(value: unknown, headers: unknown, id: string): string | null {+ if (!isRecord(value) || !isStringRecord(headers)) return `${id}: headerBindings requires headers`;+ for (const [header, bindings] of Object.entries(value)) {+ if (!Object.hasOwn(headers, header) || !isRecord(bindings)) return `${id}: invalid header bindings`;+ for (const [token, binding] of Object.entries(bindings)) {+ if (!/^\$?\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(token) || !isRecord(binding) || Object.keys(binding).length !== 1) {+ return `${id}: invalid header token binding`;+ }+ if (typeof binding.value !== "string" && (typeof binding.input !== "string" || !VARIABLE_NAME.test(binding.input))) {+ return `${id}: header token binding requires an input or literal value`;+ }+ }+ }+ return null;+}+function entryShapeError(value: unknown): string | null {if (!isRecord(value)) return "entry is not an object";const id = typeof value.id === "string" ? value.id : "unknown";@@ -102,9 +133,14 @@ function entryShapeError(value: unknown): string | null {if (value.args !== undefined && !isStringArray(value.args)) return `${id}: args must be an array of strings`;if (value.env !== undefined && !isStringRecord(value.env)) return `${id}: env must be an object of strings`;if (value.headers !== undefined && !isStringRecord(value.headers)) return `${id}: headers must be an object of strings`;+ if (value.headerBindings !== undefined) {+ if (value.transport !== "http") return `${id}: headerBindings requires http transport`;+ const error = headerBindingsError(value.headerBindings, value.headers, id);+ if (error) return error;+ }if (value.prerequisites !== undefined && !isStringArray(value.prerequisites)) return `${id}: prerequisites must be an array of strings`;if (value.requiredEnv !== undefined) {- const error = requiredEnvError(value.requiredEnv, id);+ const error = requiredEnvError(value.requiredEnv, id, value.transport);if (error) return error;}for (const field of ["description", "author", "homepage", "command", "url", "notes"]) {@@ -129,15 +165,35 @@ function templateStrings(entry: McpCatalogEntry): string[] {];}-/** Every `${NAME}` the entry's install template needs, deduped and sorted. */+/** Every editable input referenced by an install template, deduped and sorted. */export function collectCatalogPlaceholders(entry: McpCatalogEntry): string[] {const names = new Set<string>();- for (const text of templateStrings(entry)) {- for (const match of text.matchAll(PLACEHOLDER)) names.add(match[1]);+ const declared = declaredNames(entry);+ const collect = (text: string, pattern: RegExp, bindings?: Record<string, McpCatalogHeaderBinding>) => {+ for (const match of text.matchAll(pattern)) {+ if (bindings) {+ const binding = Object.hasOwn(bindings, match[0]) ? bindings[match[0]] : undefined;+ if (binding && "input" in binding) names.add(binding.input);+ } else if (match[0].startsWith("$") || declared.has(match[1])) {+ names.add(match[1]);+ }+ }+ };+ if (entry.transport === "http") {+ collect(entry.url ?? "", ENV_PLACEHOLDER);+ for (const [header, template] of Object.entries(entry.headers ?? {})) {+ collect(template, HEADER_PLACEHOLDER, bindingsForHeader(entry, header));+ }+ } else {+ for (const text of templateStrings(entry)) collect(text, ENV_PLACEHOLDER);}return [...names].sort();}+function bindingsForHeader(entry: McpCatalogEntry, header: string): Record<string, McpCatalogHeaderBinding> | undefined {+ return entry.headerBindings && Object.hasOwn(entry.headerBindings, header) ? entry.headerBindings[header] : undefined;+}+function declaredNames(entry: McpCatalogEntry): Map<string, McpCatalogRequiredEnv> {return new Map((entry.requiredEnv ?? []).map((item) => [item.name, item]));}@@ -182,10 +238,18 @@ export function resolveCatalogEntry(const error = catalogEntryError(entry);if (error) throw new Error(error);const declared = declaredNames(entry);- const fill = (text: string): string =>- text.replace(PLACEHOLDER, (whole, name: string) => {+ const fill = (text: string, pattern: RegExp, bindings?: Record<string, McpCatalogHeaderBinding>): string =>+ text.replace(pattern, (whole, name: string) => {+ if (bindings) {+ const binding = Object.hasOwn(bindings, whole) ? bindings[whole] : undefined;+ if (!binding) return whole;+ if ("value" in binding) return binding.value;+ name = binding.input;+ } else if (!whole.startsWith("$") && !declared.has(name)) {+ return whole;+ }const spec = declared.get(name);- const value = values[name] ?? spec?.defaultValue ?? "";+ const value = (Object.hasOwn(values, name) ? values[name] : undefined) ?? spec?.defaultValue ?? "";if (!value && !spec?.optional) {throw new Error(`${entry.name}: missing value for ${name}`);}@@ -200,21 +264,21 @@ export function resolveCatalogEntry(if (entry.transport === "http") {const headers: Record<string, string> = {};for (const [key, template] of Object.entries(entry.headers ?? {})) {- const value = fill(template);+ const value = fill(template, HEADER_PLACEHOLDER, bindingsForHeader(entry, key));if (value) headers[key] = value;}- return { ...base, transport: "http", url: fill(entry.url!), headers };+ return { ...base, transport: "http", url: fill(entry.url!, ENV_PLACEHOLDER), headers };}const env: Record<string, string> = {};for (const [key, template] of Object.entries(entry.env ?? {})) {- const value = fill(template);+ const value = fill(template, ENV_PLACEHOLDER);if (value) env[key] = value;}return {...base,transport: "stdio",- command: fill(entry.command!),- args: (entry.args ?? []).map((arg) => fill(arg)),+ command: fill(entry.command!, ENV_PLACEHOLDER),+ args: (entry.args ?? []).map((arg) => fill(arg, ENV_PLACEHOLDER)),env,};}diff --git a/packages/shared/src/mcp-registry.test.ts b/packages/shared/src/mcp-registry.test.tsindex f2ef666c3..800697ec5 100644--- a/packages/shared/src/mcp-registry.test.ts+++ b/packages/shared/src/mcp-registry.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { catalogEntryError } from "./mcp-catalog.js";+import { catalogEntryError, collectCatalogPlaceholders, resolveCatalogEntry } from "./mcp-catalog.js";import {guessCategory,isPublicIpLiteral,@@ -67,6 +67,57 @@ const remoteRecord: RegistryRecord = {},};+/*+ * The official registry spells a header variable as `{name}` and declares it in+ * `variables` (see the `variables` description in the registry server schema,+ * which replaces the `{curly_braces}` keys of `value`). Records in the wild use+ * both that form and the `${NAME}` form the builtin catalog uses.+ */+const officialPlaceholderRecord: RegistryRecord = {+ server: {+ name: "io.github.example/cloud-toolkit",+ title: "Cloud Toolkit",+ description: "web search and page extraction",+ remotes: [+ {+ type: "streamable-http",+ url: "https://toolkit.example.com/mcp",+ headers: [+ {+ name: "Authorization",+ value: "Bearer {CLOUD_API_KEY}",+ isRequired: true,+ isSecret: true,+ variables: {+ CLOUD_API_KEY: {+ description: "Create a scoped key in the dashboard.",+ format: "string",+ isRequired: true,+ isSecret: true,+ },+ },+ },+ ],+ },+ ],+ },+};++const lowercasePlaceholderRecord: RegistryRecord = {+ server: {+ name: "ai.example/lowercase",+ title: "Lowercase",+ description: "a server whose variable name is not upper case",+ remotes: [+ {+ type: "streamable-http",+ url: "https://lowercase.example.com/mcp",+ headers: [{ name: "Authorization", value: "Bearer {api_key}", variables: { api_key: { isRequired: true } } }],+ },+ ],+ },+};+describe("registryIdFromName", () => {it("slugifies reverse-dns names", () => {expect(registryIdFromName("com.pulsemcp/playwright-stealth")).toBe("com-pulsemcp-playwright-stealth");@@ -118,6 +169,154 @@ describe("mapRegistryServer", () => {expect(catalogEntryError(entry!)).toBeNull();});+ it("maps a remote record's official {curly_braces} header variables", () => {+ const entry = mapRegistryServer(officialPlaceholderRecord);+ expect(entry).not.toBeNull();+ expect(entry!.headers).toEqual({ Authorization: "Bearer {CLOUD_API_KEY}" });+ expect(entry!.requiredEnv).toEqual([+ { name: "CLOUD_API_KEY", description: "Create a scoped key in the dashboard." },+ ]);+ expect(catalogEntryError(entry!)).toBeNull();+ });++ it("accepts a lowercase variable name", () => {+ const entry = mapRegistryServer(lowercasePlaceholderRecord);+ expect(entry!.requiredEnv).toEqual([{ name: "api_key" }]);+ expect(catalogEntryError(entry!)).toBeNull();+ const input = resolveCatalogEntry(entry!, { api_key: "k-lower-1" });+ expect(input.headers).toEqual({ Authorization: "Bearer k-lower-1" });+ });++ it.each(["token", "TOKEN"])("keeps header-local %s out of URL paths and queries", (name) => {+ const url = `https://example.com/{${name}}?token={${name}}`;+ const entry = mapRegistryServer({ server: { name: "io.example/header-scope", remotes: [{+ type: "streamable-http", url,+ headers: [{ name: "Authorization", value: `Bearer {${name}}`, variables: {+ [name]: { isRequired: true, default: "synthetic-default" },+ } }],+ }] } })!;++ expect(entry).not.toBeNull();+ for (const values of [{}, { [name]: "synthetic-secret" }]) {+ const input = resolveCatalogEntry(entry, values);+ expect(input.url).toBe(url);+ expect(input.headers).toEqual({ Authorization: `Bearer ${values[name] ?? "synthetic-default"}` });+ }+ expect(collectCatalogPlaceholders({ ...entry, headers: {}, headerBindings: undefined })).toEqual([]);+ });++ it("marks a declared header variable optional when it is not required", () => {+ const record: RegistryRecord = JSON.parse(JSON.stringify(officialPlaceholderRecord));+ record.server!.remotes![0].headers![0].variables!.CLOUD_API_KEY = {+ description: "Optional project selector.",+ isRequired: false,+ };+ const entry = mapRegistryServer(record);+ expect(entry!.requiredEnv).toEqual([+ { name: "CLOUD_API_KEY", description: "Optional project selector.", optional: true },+ ]);+ });++ it("resolves an official {curly_braces} header into the sent value, not the placeholder", () => {+ const entry = mapRegistryServer(officialPlaceholderRecord)!;+ const input = resolveCatalogEntry(entry, { CLOUD_API_KEY: "sk-live-123" });+ expect(input.headers).toEqual({ Authorization: "Bearer sk-live-123" });+ });++ it("resolves a builtin ${NAME} header without leaving a stray dollar", () => {+ const entry = mapRegistryServer(remoteRecord)!;+ const input = resolveCatalogEntry(entry, { TOKEN: "t-1", PROJECT: "p-9" });+ expect(input.headers).toEqual({+ Authorization: "Bearer t-1",+ "X-Project": "p-9",+ });+ });++ it("refuses to resolve an official header whose value is missing", () => {+ const entry = mapRegistryServer(officialPlaceholderRecord)!;+ expect(() => resolveCatalogEntry(entry, {})).toThrow(/missing value for CLOUD_API_KEY/);+ });++ it("preserves undeclared brace tokens, including a name declared in another header", () => {+ const record: RegistryRecord = { server: { name: "io.example/literals", remotes: [{+ type: "streamable-http", url: "https://example.com/mcp", headers: [+ { name: "X-Literal", value: "{opaque} {token}" },+ { name: "Authorization", value: "Bearer {token}", variables: { token: { isRequired: true } } },+ ],+ }] } };+ const entry = mapRegistryServer(record)!;+ expect(entry.requiredEnv).toEqual([{ name: "token" }]);+ expect(resolveCatalogEntry(entry, { token: "synthetic" }).headers).toEqual({+ "X-Literal": "{opaque} {token}", Authorization: "Bearer synthetic",+ });+ });++ it("preserves undeclared braces beside a legacy dollar token with the same name", () => {+ const record: RegistryRecord = { server: { name: "io.example/mixed", remotes: [{+ type: "streamable-http", url: "https://example.com/mcp",+ headers: [{ name: "X-Mixed", value: "{TOKEN} ${TOKEN}" }],+ }] } };+ expect(resolveCatalogEntry(mapRegistryServer(record)!, { TOKEN: "synthetic" }).headers).toEqual({+ "X-Mixed": "{TOKEN} synthetic",+ });+ });++ it("uses header variable defaults, allows overrides and defaults isRequired to false", () => {+ const record: RegistryRecord = { server: { name: "io.example/defaults", remotes: [{+ type: "streamable-http", url: "https://example.com/mcp", headers: [+ { name: "X-Project", value: "{project}", variables: { project: { isRequired: true, default: "public" } } },+ { name: "X-Optional", value: "{scope}", variables: { scope: { description: "Optional scope" } } },+ ],+ }] } };+ const entry = mapRegistryServer(record)!;+ expect(entry.requiredEnv).toContainEqual({ name: "scope", description: "Optional scope", optional: true });+ expect(resolveCatalogEntry(entry).headers).toEqual({ "X-Project": "public" });+ expect(resolveCatalogEntry(entry, { project: "custom" }).headers).toEqual({ "X-Project": "custom" });+ });++ it("keeps fixed variable values out of the form and does not interpret their contents", () => {+ const record: RegistryRecord = { server: { name: "io.example/fixed", remotes: [{+ type: "streamable-http", url: "https://example.com/mcp", headers: [{+ name: "X-Fixed", value: "{fixed} {editable}", variables: {+ fixed: { value: "${editable} {editable}", default: "ignored", isRequired: true },+ editable: { isRequired: true },+ },+ }],+ }] } };+ const entry = mapRegistryServer(record)!;+ expect(entry.requiredEnv).toEqual([{ name: "editable" }]);+ expect(resolveCatalogEntry(entry, { fixed: "override", editable: "chosen" }).headers).toEqual({+ "X-Fixed": "${editable} {editable} chosen",+ });+ });++ it("keeps same-named header inputs independent and avoids generated-name collisions", () => {+ const record: RegistryRecord = { server: { name: "io.example/scopes", remotes: [{+ type: "streamable-http", url: "https://example.com/mcp", headers: [+ { name: "X-Optional", value: "{token}", variables: { token: {} } },+ { name: "Authorization", value: "Bearer {token}", variables: { token: { isRequired: true } } },+ { name: "X-Collision", value: "{token_1}", variables: { token_1: { default: "one" } } },+ ],+ }] } };+ const entry = mapRegistryServer(record)!;+ expect(entry.requiredEnv).toHaveLength(3);+ expect(new Set(entry.requiredEnv!.map(({ name }) => name)).size).toBe(3);+ const required = entry.requiredEnv!.find(({ optional }) => !optional)!;+ expect(() => resolveCatalogEntry(entry)).toThrow(`missing value for ${required.name}`);+ expect(resolveCatalogEntry(entry, { [required.name]: "synthetic" }).headers).toEqual({+ Authorization: "Bearer synthetic", "X-Collision": "one",+ });+ });++ it("does not use inherited object properties as supplied input values", () => {+ const record: RegistryRecord = { server: { name: "io.example/property", remotes: [{+ type: "streamable-http", url: "https://example.com/mcp", headers: [{+ name: "X-Input", value: "{constructor}", variables: { constructor: { isRequired: true } },+ }],+ }] } };+ expect(() => resolveCatalogEntry(mapRegistryServer(record)!, {})).toThrow("missing value for constructor");+ });+it("drops records without a runnable form", () => {const ociOnly: RegistryRecord = {server: {diff --git a/packages/shared/src/mcp-registry.ts b/packages/shared/src/mcp-registry.tsindex fc569adf8..ae579a7d2 100644--- a/packages/shared/src/mcp-registry.ts+++ b/packages/shared/src/mcp-registry.ts@@ -11,6 +11,7 @@ import {catalogEntryError,type McpCatalogCategory,type McpCatalogEntry,+ type McpCatalogHeaderBinding,type McpCatalogRequiredEnv,} from "./mcp-catalog.js";import { isPublicHttpsUrl } from "./public-network.js";@@ -41,10 +42,24 @@ export type RegistryPackage = {environmentVariables?: RegistryEnvVar[];};+/**+ * A registry input: the shape shared by a remote header, a package environment+ * variable and an entry of a header's `variables` map.+ */+export type RegistryInput = {+ description?: string;+ format?: string;+ isRequired?: boolean;+ isSecret?: boolean;+ value?: string;+ default?: string;+ variables?: Record<string, RegistryInput>;+};+export type RegistryRemote = {type?: string;url?: string;- headers?: Array<{ name?: string; value?: string }>;+ headers?: Array<RegistryInput & { name?: string }>;};export type RegistryServer = {@@ -125,23 +140,68 @@ function packageSpecifier(pkg: RegistryPackage, separator: "@" | "=="): string |return version ? `${identifier}${separator}${version}` : identifier;}-const REMOTE_PLACEHOLDER = /\$\{([A-Z_][A-Z0-9_]*)\}/g;+/** Registry variables are scoped to each header; legacy dollar tokens remain supported. */+const REMOTE_PLACEHOLDER = /\$?\{([A-Za-z_][A-Za-z0-9_]*)\}/g;-function remoteHeaderTemplates(remote: RegistryRemote): {- headers: Record<string, string>;- requiredEnv?: McpCatalogRequiredEnv[];-} {- const headers = Object.fromEntries(+function remoteHeaderTemplates(remote: RegistryRemote): Pick<McpCatalogEntry, "headers" | "headerBindings" | "requiredEnv"> {+ // Keep the same last-header-wins behavior as Object.fromEntries, including its metadata.+ const headerInputs = new Map((remote.headers ?? []).filter((header) => typeof header.name === "string" && !!header.name && typeof header.value === "string")- .map((header) => [header.name!, header.value!]),+ .map((header) => [header.name!, header]),);- const names = new Set<string>();- for (const value of Object.values(headers)) {- for (const match of value.matchAll(REMOTE_PLACEHOLDER)) names.add(match[1]);+ const inputs = [...headerInputs].map(([header, input]) => {+ const tokens = new Map<string, { name: string; variable?: RegistryInput }>();+ for (const match of input.value!.matchAll(REMOTE_PLACEHOLDER)) {+ const variable = input.variables && Object.hasOwn(input.variables, match[1]) ? input.variables[match[1]] : undefined;+ // The official contract preserves unbound {name}; only legacy ${NAME} is inferred.+ if (variable || /^\$\{[A-Z_][A-Z0-9_]*\}$/.test(match[0])) {+ tokens.set(match[0], { name: match[1], variable });+ }+ }+ return { header, input, tokens };+ });+ const nameCounts = new Map<string, number>();+ for (const { tokens } of inputs) {+ const names = new Set([...tokens.values()].filter(({ variable }) => typeof variable?.value !== "string").map(({ name }) => name));+ for (const name of names) nameCounts.set(name, (nameCounts.get(name) ?? 0) + 1);}- const requiredEnv = [...names].sort().map((name) => ({ name }));- return { headers, ...(requiredEnv.length ? { requiredEnv } : {}) };+ const usedNames = new Set(nameCounts.keys());+ const requiredEnv: McpCatalogRequiredEnv[] = [];+ const headerBindings: Array<[string, Record<string, McpCatalogHeaderBinding>]> = [];+ for (const [index, { header, tokens }] of inputs.entries()) {+ const localNames = new Map<string, string>();+ const bindings: Array<[string, McpCatalogHeaderBinding]> = [];+ for (const [token, { name, variable }] of tokens) {+ if (typeof variable?.value === "string") {+ bindings.push([token, { value: variable.value }]);+ continue;+ }+ let inputName = localNames.get(name);+ if (!inputName) {+ inputName = name;+ if ((nameCounts.get(name) ?? 0) > 1) {+ inputName = `${name}_${index + 1}`;+ while (usedNames.has(inputName)) inputName += "_";+ }+ usedNames.add(inputName);+ localNames.set(name, inputName);+ requiredEnv.push({+ name: inputName,+ ...(variable?.description ? { description: variable.description } : {}),+ ...(variable && variable.isRequired !== true ? { optional: true } : {}),+ ...(typeof variable?.default === "string" ? { defaultValue: variable.default } : {}),+ });+ }+ bindings.push([token, { input: inputName }]);+ }+ headerBindings.push([header, Object.fromEntries(bindings)]);+ }+ return {+ headers: Object.fromEntries(inputs.map(({ header, input }) => [header, input.value!])),+ headerBindings: Object.fromEntries(headerBindings),+ ...(requiredEnv.length ? { requiredEnv: requiredEnv.sort((left, right) => left.name.localeCompare(right.name)) } : {}),+ };}/*@@ -246,8 +306,7 @@ export function mapRegistryServer(record: RegistryRecord): McpCatalogEntry | nul...base,transport: "http",url: remote.url!,- ...(Object.keys(template.headers).length ? { headers: template.headers } : {}),- ...(template.requiredEnv ? { requiredEnv: template.requiredEnv } : {}),+ ...template,};return catalogEntryError(entry) ? null : entry;}diff --git a/scripts/e2e-mcp-market.mjs b/scripts/e2e-mcp-market.mjsindex 2eb174911..ca139b3ee 100644--- a/scripts/e2e-mcp-market.mjs+++ b/scripts/e2e-mcp-market.mjs@@ -6,6 +6,8 @@* E2E-MCP-MARKET-INSTALL builtin entry → mcp.upsert → record on disk* E2E-MCP-MARKET-SEMANTICS registry record → template keeps named* arguments and required/optional envs+ * E2E-MCP-MARKET-HEADER-SCOPE header credential stays out of the URL+ * through mapping, resolution and persistence* E2E-MCP-MARKET-NET-BOUNDARY the URL guard rejects loopback/private/* mapped/ULA/link-local bypass forms*@@ -209,6 +211,29 @@ try {!!row && row.enabled === true && diskOk,row ? JSON.stringify({ command: row.command, args: row.args, enabled: row.enabled }) : "not listed",);++ const scopedUrl = "https://example.com/{token}?token={token}";+ const scopedEntry = mapRegistryServer({ server: {+ name: "io.example/header-scope",+ remotes: [{ type: "streamable-http", url: scopedUrl, headers: [{+ name: "Authorization", value: "Bearer {token}",+ variables: { token: { isRequired: true } },+ }] }],+ } });+ const scopedInput = resolveCatalogEntry(scopedEntry, { token: "synthetic-header-secret" });+ await host.call("mcp.upsert", { server: {+ ...scopedInput, enabled: false, level: "global", scope: GLOBAL_SCOPE,+ } });+ const scopedList = await host.call("mcp.list", { level: "global" });+ const scopedRow = scopedList.servers.find((server) => server.id === scopedEntry.id);+ const scopedDisk = JSON.parse(readFileSync(join(home, ".agents", "servers", `${scopedEntry.id}.json`), "utf8"));+ record(+ "E2E-MCP-MARKET-HEADER-SCOPE",+ scopedInput.url === scopedUrl && scopedRow?.url === scopedUrl && scopedDisk.url === scopedUrl+ && scopedDisk.headers?.Authorization === "Bearer synthetic-header-secret"+ && scopedRow.enabled === false,+ "header resolves while the same-named URL token remains literal in host configuration",+ );}} catch (error) {record("E2E-MCP-MARKET-INSTALL", false, error.message);