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GAAI,GAAA,CAAI,MAAA,GAAS,EAAE,GAAA,KAAQ;AAAC,GAC9B;AACF","file":"mcp-imports.mjs","sourcesContent":["/**\n * `~/.agentproto/imported-mcps.json` — the user's curated set of\n * discovered MCPs they want the daemon to know about. v1 is just\n * persistence + read-side; the actual MCP-proxy implementation\n * (where the daemon's /mcp endpoint aggregates the imported\n * servers' tools under namespace prefixes) is v2 work.\n *\n * Purpose: today, \"I see you have chrome-devtools in claude\" is\n * read-only. Once a user imports it, the operator agent can refer\n * to it (\"the user said it's enabled — call it\") and a future\n * proxy layer can actually expose it. We persist the choice now so\n * the data is in place when the proxy lands.\n *\n * File shape:\n *   {\n *     \"version\": 1,\n *     \"imports\": [\n *       {\n *         \"id\":         \"claude-code:project:/path:chrome-devtools\",\n *         \"alias\":      \"chrome-devtools\",\n *         \"addedAt\":    \"2026-05-10T...\",\n *         \"snapshot\":   { ...the DiscoveredMcp at import time }\n *       }\n *     ]\n *   }\n *\n * Snapshotting at import time keeps the daemon resilient to the\n * source config getting deleted (user runs `claude mcp remove ...`).\n * The imported entry stays usable; only the next discovery pass\n * stops listing it as \"available to import.\"\n */\n\nimport { promises as fs } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, resolve as resolvePath } from \"node:path\"\nimport type { DiscoveredMcp } from \"./mcp-discovery.js\"\n\nexport const IMPORTED_MCPS_PATH = (): string =>\n  resolvePath(homedir(), \".agentproto\", \"imported-mcps.json\")\n\nexport const IMPORTED_MCPS_VERSION = 1 as const\n\n/** Where an import came from. `plugin` (written by plugin-local-browser) and\n *  `manual` have no discovery source; `kind` otherwise mirrors\n *  `DiscoveredMcp[\"source\"]`. */\nexport interface ImportedMcpOrigin {\n  kind: DiscoveredMcp[\"source\"] | \"plugin\" | \"manual\"\n  scope: string\n  name: string\n}\n\n/** `live` = re-read the source harness config at connect time (the snapshot is\n *  only a fallback); `snapshot` = the stored copy is authoritative. */\nexport type ImportedMcpResolve = \"live\" | \"snapshot\"\n\n/** Opaque secret refs (resolved via `resolveMcpSecret`), keyed by the header\n *  / env key they fill. Values are refs, NEVER secret material. */\nexport interface ImportedMcpSecretRefs {\n  headers?: Record<string, string>\n  env?: Record<string, string>\n}\n\nexport interface ImportedMcpEntry {\n  id: string\n  alias: string\n  addedAt: string\n  snapshot: DiscoveredMcp\n  /** Additive (no file-version bump): link back to the source config. */\n  origin?: ImportedMcpOrigin\n  resolve?: ImportedMcpResolve\n  secretRefs?: ImportedMcpSecretRefs\n  /** http/sse only: the server authenticates with OAuth. Tokens live in the\n   *  keychain (`mcpOAuthRef`), never in this file. Set by `mcp login`. */\n  auth?: ImportedMcpAuth\n  /** http/sse only: also send the caller session and node headers\n   *  (`x-agentproto-caller-session`, `x-agentproto-caller-node`) to this server\n   *  when it is not on this machine. Loopback servers always receive them. */\n  forwardCaller?: boolean\n  /** http only: mint an AIP-59 section 8 sub-session token per caller session\n   *  and send it as `Agentproto-Subsession` instead of the bare caller header.\n   *  Only meaningful when the server serves `POST /pair/subsessions`. */\n  subsession?: \"aip-59\"\n}\n\nexport interface ImportedMcpAuth {\n  type: \"oauth\"\n  /** Scope to request; omitted = the server's advertised default. */\n  scope?: string\n}\n\n/** Value written into `snapshot.headers[K]` / `snapshot.env[K]` in place of a\n *  literal secret that now lives behind `secretRefs`. */\nexport const SECRET_REF_MARKER = \"<secretRef>\"\n\n/** Discovery sources whose config can be re-read live. */\nconst LIVE_SOURCES: ReadonlySet<string> = new Set([\n  \"claude-code\",\n  \"cursor\",\n  \"codex\",\n  \"workspace\",\n])\n\n/** `live` only when discovery can actually re-find the entry: a discovery\n *  source AND a scope discovery scans (`global` / `project:*` / `workspace:*`).\n *  claude-code `local`-scope and plugin/manual entries stay `snapshot`. */\nexport function deriveResolve(snapshot: DiscoveredMcp): ImportedMcpResolve {\n  if (!LIVE_SOURCES.has(snapshot.source)) return \"snapshot\"\n  const s = snapshot.scope\n  return s === \"global\" || s.startsWith(\"project:\") || s.startsWith(\"workspace:\")\n    ? \"live\"\n    : \"snapshot\"\n}\n\n/** Keychain path + account for one secret slot of an import. Ref format\n *  `agentproto/mcp-import/<importId>#<header|env>:<KEY>` (split on LAST `#`). */\nexport function mcpSecretRef(\n  importId: string,\n  kind: \"header\" | \"env\",\n  key: string\n): string {\n  return `agentproto/mcp-import/${importId}#${kind}:${key}`\n}\n\nconst PLACEHOLDER_RE = /\\$\\{[A-Z_][A-Z0-9_]*(?::-[^}]*)?\\}/i\n\n/** A value worth moving to the keychain: non-empty, not already the marker,\n *  and not a `${VAR}` placeholder (those expand at connect, no secret at rest). */\nexport function isLiteralSecretValue(v: unknown): v is string {\n  return (\n    typeof v === \"string\" &&\n    v.length > 0 &&\n    v !== SECRET_REF_MARKER &&\n    !PLACEHOLDER_RE.test(v)\n  )\n}\n\nexport interface MoveSecretsResult {\n  entry: ImportedMcpEntry\n  /** Header/env KEY names moved this call (never values). */\n  moved: string[]\n  /** Human warnings (key names only). */\n  warnings: string[]\n}\n\n/**\n * Move every literal header/env value of `entry.snapshot` behind a keychain\n * ref. Keychain write happens FIRST per key; only on success is the snapshot\n * value replaced by the marker (a failed write keeps the literal + warns).\n * Read-back verification when `resolve` is supplied.\n */\nexport async function moveEntrySecrets(\n  entry: ImportedMcpEntry,\n  hooks: {\n    storeMcpSecret?: (ref: string, value: string) => Promise<void>\n    resolveMcpSecret?: (ref: string) => Promise<string | undefined>\n  }\n): Promise<MoveSecretsResult> {\n  if (!hooks.storeMcpSecret) {\n    const has =\n      Object.values(entry.snapshot.headers ?? {}).some(isLiteralSecretValue) ||\n      Object.values(entry.snapshot.env ?? {}).some(isLiteralSecretValue)\n    return {\n      entry,\n      moved: [],\n      warnings: has\n        ? [\n            \"no secret store available: header/env values were kept as literals in imported-mcps.json (mode 0600)\",\n          ]\n        : [],\n    }\n  }\n  const moved: string[] = []\n  const warnings: string[] = []\n  const secretRefs: ImportedMcpSecretRefs = {\n    ...(entry.secretRefs?.headers ? { headers: { ...entry.secretRefs.headers } } : {}),\n    ...(entry.secretRefs?.env ? { env: { ...entry.secretRefs.env } } : {}),\n  }\n  const headers = entry.snapshot.headers ? { ...entry.snapshot.headers } : undefined\n  const env = entry.snapshot.env ? { ...entry.snapshot.env } : undefined\n  const passes: Array<[\"header\" | \"env\", Record<string, string> | undefined]> = [\n    [\"header\", headers],\n    [\"env\", env],\n  ]\n  for (const [kind, map] of passes) {\n    if (!map) continue\n    for (const [key, value] of Object.entries(map)) {\n      if (!isLiteralSecretValue(value)) continue\n      const ref = mcpSecretRef(entry.id, kind, key)\n      try {\n        await hooks.storeMcpSecret(ref, value)\n        if (hooks.resolveMcpSecret) {\n          const back = await hooks.resolveMcpSecret(ref)\n          if (back !== value) throw new Error(\"read-back mismatch\")\n        }\n      } catch (err) {\n        warnings.push(\n          `could not store ${kind} \"${key}\" in the secret store (${\n            err instanceof Error ? err.message : \"error\"\n          }); kept as a literal`\n        )\n        continue\n      }\n      map[key] = SECRET_REF_MARKER\n      const bucket = kind === \"header\" ? \"headers\" : \"env\"\n      secretRefs[bucket] = { ...(secretRefs[bucket] ?? {}), [key]: ref }\n      moved.push(`${kind}:${key}`)\n    }\n  }\n  if (moved.length === 0) return { entry, moved, warnings }\n  return {\n    entry: {\n      ...entry,\n      snapshot: {\n        ...entry.snapshot,\n        ...(headers ? { headers } : {}),\n        ...(env ? { env } : {}),\n      },\n      secretRefs,\n    },\n    moved,\n    warnings,\n  }\n}\n\nexport interface ImportedMcpsConfig {\n  version: typeof IMPORTED_MCPS_VERSION\n  imports: ImportedMcpEntry[]\n}\n\nconst EMPTY: ImportedMcpsConfig = {\n  version: IMPORTED_MCPS_VERSION,\n  imports: [],\n}\n\nexport async function loadImportedMcps(\n  path: string = IMPORTED_MCPS_PATH()\n): Promise<ImportedMcpsConfig> {\n  let raw: string\n  try {\n    raw = await fs.readFile(path, \"utf8\")\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return EMPTY\n    throw err\n  }\n  let parsed: unknown\n  try {\n    parsed = JSON.parse(raw)\n  } catch (err) {\n    throw new Error(\n      `agentproto: ${path} is not valid JSON (${\n        err instanceof Error ? err.message : String(err)\n      }). Delete or fix manually.`\n    )\n  }\n  return normalize(parsed)\n}\n\nexport async function saveImportedMcps(\n  config: ImportedMcpsConfig,\n  path: string = IMPORTED_MCPS_PATH()\n): Promise<void> {\n  await fs.mkdir(dirname(path), { recursive: true })\n  const tmp = `${path}.tmp.${process.pid}`\n  // 0600: entries may hold literal upstream credentials (parity with bundles.ts).\n  await fs.writeFile(tmp, JSON.stringify(config, null, 2) + \"\\n\", {\n    encoding: \"utf8\",\n    mode: 0o600,\n  })\n  await fs.rename(tmp, path)\n}\n\n/**\n * Add (or replace) an import. Snapshots the discovered MCP at\n * import time so the entry stays usable when the source config\n * disappears.\n */\nexport function addImport(\n  config: ImportedMcpsConfig,\n  input: { snapshot: DiscoveredMcp; alias?: string }\n): ImportedMcpsConfig {\n  const alias = (input.alias ?? input.snapshot.name).trim()\n  if (!alias) {\n    throw new Error(\"addImport: alias resolves to empty string\")\n  }\n  const addedAt = new Date().toISOString()\n  const next: ImportedMcpEntry = {\n    id: input.snapshot.id,\n    alias,\n    addedAt,\n    snapshot: input.snapshot,\n    origin: {\n      kind: input.snapshot.source,\n      scope: input.snapshot.scope,\n      name: input.snapshot.name,\n    },\n    resolve: deriveResolve(input.snapshot),\n  }\n  const others = config.imports.filter(e => e.id !== input.snapshot.id)\n  return { ...config, imports: [...others, next] }\n}\n\n/**\n * `addImport` + move literal header/env values behind keychain refs (via the\n * `storeMcpSecret` hook). Hook absent → literals kept and a warning returned.\n * Callers persist `config` and surface `warnings` in their reply.\n */\nexport async function addImportWithSecrets(\n  config: ImportedMcpsConfig,\n  input: { snapshot: DiscoveredMcp; alias?: string },\n  hooks: {\n    storeMcpSecret?: (ref: string, value: string) => Promise<void>\n    resolveMcpSecret?: (ref: string) => Promise<string | undefined>\n  }\n): Promise<{ config: ImportedMcpsConfig; entry: ImportedMcpEntry; warnings: string[] }> {\n  const added = addImport(config, input)\n  const entry = added.imports.find(e => e.id === input.snapshot.id)!\n  const moved = await moveEntrySecrets(entry, hooks)\n  return {\n    config: {\n      ...added,\n      imports: added.imports.map(e => (e.id === entry.id ? moved.entry : e)),\n    },\n    entry: moved.entry,\n    warnings: moved.warnings,\n  }\n}\n\nexport function removeImport(\n  config: ImportedMcpsConfig,\n  id: string\n): ImportedMcpsConfig {\n  return { ...config, imports: config.imports.filter(e => e.id !== id) }\n}\n\nexport function findImport(\n  config: ImportedMcpsConfig,\n  id: string\n): ImportedMcpEntry | undefined {\n  return config.imports.find(e => e.id === id)\n}\n\nfunction normalize(parsed: unknown): ImportedMcpsConfig {\n  if (!parsed || typeof parsed !== \"object\") return EMPTY\n  const obj = parsed as Record<string, unknown>\n  const imports: ImportedMcpEntry[] = []\n  if (Array.isArray(obj.imports)) {\n    for (const entry of obj.imports) {\n      if (!entry || typeof entry !== \"object\") continue\n      const e = entry as Record<string, unknown>\n      const id = typeof e.id === \"string\" ? e.id : \"\"\n      const alias = typeof e.alias === \"string\" ? e.alias : id\n      const addedAt =\n        typeof e.addedAt === \"string\" ? e.addedAt : new Date().toISOString()\n      const snapshot = e.snapshot as DiscoveredMcp | undefined\n      if (!id || !snapshot) continue\n      const extra: Partial<ImportedMcpEntry> = {}\n      const origin = parseOrigin(e.origin)\n      if (origin) extra.origin = origin\n      if (e.resolve === \"live\" || e.resolve === \"snapshot\") extra.resolve = e.resolve\n      const secretRefs = parseSecretRefs(e.secretRefs)\n      if (secretRefs) extra.secretRefs = secretRefs\n      const auth = parseAuth(e.auth)\n      if (auth) extra.auth = auth\n      if (e.forwardCaller === true) extra.forwardCaller = true\n      if (e.subsession !== undefined) {\n        if (e.subsession === \"aip-59\" && snapshot.type === \"http\") {\n          extra.subsession = \"aip-59\"\n        } else {\n          console.warn(\n            `agentproto: import \"${alias}\" declares subsession but is not an http \"aip-59\" entry; ignoring`,\n          )\n        }\n      }\n      imports.push({ id, alias, addedAt, snapshot, ...extra })\n    }\n  }\n  return { version: IMPORTED_MCPS_VERSION, imports }\n}\n\nfunction parseAuth(v: unknown): ImportedMcpAuth | undefined {\n  if (!v || typeof v !== \"object\") return undefined\n  const o = v as Record<string, unknown>\n  if (o.type !== \"oauth\") return undefined\n  return { type: \"oauth\", ...(typeof o.scope === \"string\" && o.scope ? { scope: o.scope } : {}) }\n}\n\nfunction parseOrigin(v: unknown): ImportedMcpOrigin | undefined {\n  if (!v || typeof v !== \"object\") return undefined\n  const o = v as Record<string, unknown>\n  if (\n    typeof o.kind !== \"string\" ||\n    typeof o.scope !== \"string\" ||\n    typeof o.name !== \"string\"\n  )\n    return undefined\n  return { kind: o.kind as ImportedMcpOrigin[\"kind\"], scope: o.scope, name: o.name }\n}\n\nfunction parseStringMap(v: unknown): Record<string, string> | undefined {\n  if (!v || typeof v !== \"object\" || Array.isArray(v)) return undefined\n  const out: Record<string, string> = {}\n  for (const [k, val] of Object.entries(v as Record<string, unknown>)) {\n    if (typeof val === \"string\") out[k] = val\n  }\n  return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction parseSecretRefs(v: unknown): ImportedMcpSecretRefs | undefined {\n  if (!v || typeof v !== \"object\") return undefined\n  const o = v as Record<string, unknown>\n  const headers = parseStringMap(o.headers)\n  const env = parseStringMap(o.env)\n  if (!headers && !env) return undefined\n  return { ...(headers ? { headers } : {}), ...(env ? { env } : {}) }\n}\n\n/** KEY names only (never refs' targets or values) — for status surfaces. */\nexport function secretRefKeys(\n  entry: Pick<ImportedMcpEntry, \"secretRefs\">\n): { headers?: string[]; env?: string[] } | undefined {\n  const r = entry.secretRefs\n  if (!r) return undefined\n  const headers = r.headers ? Object.keys(r.headers) : []\n  const env = r.env ? Object.keys(r.env) : []\n  if (headers.length === 0 && env.length === 0) return undefined\n  return {\n    ...(headers.length ? { headers } : {}),\n    ...(env.length ? { env } : {}),\n  }\n}\n"]}