@agent-native/core 0.72.3 → 0.72.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +10 -0
  3. package/corpus/core/package.json +6 -6
  4. package/corpus/core/src/a2a/client.ts +7 -3
  5. package/corpus/core/src/client/api-path.ts +28 -0
  6. package/corpus/core/src/client/embed-auth.ts +26 -0
  7. package/corpus/core/src/client/mcp-app-host.ts +6 -0
  8. package/corpus/core/src/client/mcp-apps/McpAppRenderer.tsx +227 -33
  9. package/corpus/core/src/client/resources/use-mcp-servers.ts +1 -0
  10. package/corpus/core/src/client/settings/DemoModeSection.tsx +3 -1
  11. package/corpus/core/src/demo/fetch-interceptor.ts +1 -1
  12. package/corpus/core/src/embedding/agent.ts +6 -1
  13. package/corpus/core/src/embedding/bridge.ts +34 -1
  14. package/corpus/core/src/mcp/build-server.ts +38 -10
  15. package/corpus/core/src/mcp/embed-app.ts +120 -45
  16. package/corpus/core/src/mcp/index.ts +5 -0
  17. package/corpus/core/src/mcp/org-directory.ts +70 -11
  18. package/corpus/core/src/mcp/server.ts +14 -0
  19. package/corpus/core/src/mcp-client/config.ts +12 -0
  20. package/corpus/core/src/mcp-client/index.ts +2 -0
  21. package/corpus/core/src/mcp-client/manager.ts +268 -9
  22. package/corpus/core/src/mcp-client/remote-store.ts +154 -0
  23. package/corpus/core/src/mcp-client/routes.ts +2 -0
  24. package/corpus/core/src/server/agent-chat-plugin.ts +8 -0
  25. package/corpus/core/src/server/index.ts +1 -0
  26. package/corpus/core/src/shared/mcp-embed-headers.ts +44 -3
  27. package/corpus/core/src/vite/client.ts +53 -0
  28. package/corpus/templates/assets/.agents/skills/a2a-assets/SKILL.md +17 -10
  29. package/corpus/templates/assets/.agents/skills/asset-generation/SKILL.md +15 -6
  30. package/corpus/templates/assets/AGENTS.md +7 -5
  31. package/corpus/templates/assets/actions/generate-asset.ts +161 -0
  32. package/corpus/templates/assets/actions/list-assets.ts +4 -2
  33. package/corpus/templates/assets/actions/open-asset-picker.ts +84 -3
  34. package/corpus/templates/assets/app/routes/library.tsx +243 -40
  35. package/corpus/templates/clips/desktop/src-tauri/src/native_speech.rs +9 -0
  36. package/corpus/templates/design/AGENTS.md +10 -5
  37. package/corpus/templates/design/actions/connect-assets-mcp.ts +131 -0
  38. package/corpus/templates/design/actions/insert-asset.ts +219 -0
  39. package/corpus/templates/design/actions/view-screen.ts +3 -1
  40. package/corpus/templates/design/app/components/editor/PromptDialog.tsx +1 -1
  41. package/corpus/templates/design/app/pages/DesignEditor.tsx +53 -0
  42. package/corpus/templates/design/server/plugins/agent-chat.ts +5 -1
  43. package/corpus/templates/design/server/plugins/assets-mcp.ts +60 -0
  44. package/dist/a2a/client.d.ts +1 -0
  45. package/dist/a2a/client.d.ts.map +1 -1
  46. package/dist/a2a/client.js +5 -3
  47. package/dist/a2a/client.js.map +1 -1
  48. package/dist/client/api-path.d.ts.map +1 -1
  49. package/dist/client/api-path.js +27 -0
  50. package/dist/client/api-path.js.map +1 -1
  51. package/dist/client/embed-auth.d.ts.map +1 -1
  52. package/dist/client/embed-auth.js +27 -0
  53. package/dist/client/embed-auth.js.map +1 -1
  54. package/dist/client/mcp-app-host.d.ts.map +1 -1
  55. package/dist/client/mcp-app-host.js +5 -0
  56. package/dist/client/mcp-app-host.js.map +1 -1
  57. package/dist/client/mcp-apps/McpAppRenderer.d.ts +1 -0
  58. package/dist/client/mcp-apps/McpAppRenderer.d.ts.map +1 -1
  59. package/dist/client/mcp-apps/McpAppRenderer.js +179 -33
  60. package/dist/client/mcp-apps/McpAppRenderer.js.map +1 -1
  61. package/dist/client/resources/use-mcp-servers.d.ts +1 -0
  62. package/dist/client/resources/use-mcp-servers.d.ts.map +1 -1
  63. package/dist/client/resources/use-mcp-servers.js.map +1 -1
  64. package/dist/client/settings/DemoModeSection.d.ts.map +1 -1
  65. package/dist/client/settings/DemoModeSection.js +3 -1
  66. package/dist/client/settings/DemoModeSection.js.map +1 -1
  67. package/dist/demo/fetch-interceptor.js +1 -1
  68. package/dist/demo/fetch-interceptor.js.map +1 -1
  69. package/dist/embedding/agent.d.ts +1 -1
  70. package/dist/embedding/agent.d.ts.map +1 -1
  71. package/dist/embedding/agent.js +1 -1
  72. package/dist/embedding/agent.js.map +1 -1
  73. package/dist/embedding/bridge.d.ts.map +1 -1
  74. package/dist/embedding/bridge.js +27 -1
  75. package/dist/embedding/bridge.js.map +1 -1
  76. package/dist/extensions/schema.d.ts +2 -2
  77. package/dist/mcp/build-server.d.ts +2 -0
  78. package/dist/mcp/build-server.d.ts.map +1 -1
  79. package/dist/mcp/build-server.js +32 -9
  80. package/dist/mcp/build-server.js.map +1 -1
  81. package/dist/mcp/embed-app.d.ts.map +1 -1
  82. package/dist/mcp/embed-app.js +120 -45
  83. package/dist/mcp/embed-app.js.map +1 -1
  84. package/dist/mcp/index.d.ts +1 -0
  85. package/dist/mcp/index.d.ts.map +1 -1
  86. package/dist/mcp/index.js +1 -0
  87. package/dist/mcp/index.js.map +1 -1
  88. package/dist/mcp/org-directory.d.ts +1 -0
  89. package/dist/mcp/org-directory.d.ts.map +1 -1
  90. package/dist/mcp/org-directory.js +59 -11
  91. package/dist/mcp/org-directory.js.map +1 -1
  92. package/dist/mcp/server.d.ts.map +1 -1
  93. package/dist/mcp/server.js +9 -0
  94. package/dist/mcp/server.js.map +1 -1
  95. package/dist/mcp-client/config.d.ts +12 -0
  96. package/dist/mcp-client/config.d.ts.map +1 -1
  97. package/dist/mcp-client/config.js.map +1 -1
  98. package/dist/mcp-client/index.d.ts +1 -1
  99. package/dist/mcp-client/index.d.ts.map +1 -1
  100. package/dist/mcp-client/index.js +1 -1
  101. package/dist/mcp-client/index.js.map +1 -1
  102. package/dist/mcp-client/manager.d.ts +2 -0
  103. package/dist/mcp-client/manager.d.ts.map +1 -1
  104. package/dist/mcp-client/manager.js +201 -9
  105. package/dist/mcp-client/manager.js.map +1 -1
  106. package/dist/mcp-client/remote-store.d.ts +27 -0
  107. package/dist/mcp-client/remote-store.d.ts.map +1 -1
  108. package/dist/mcp-client/remote-store.js +105 -0
  109. package/dist/mcp-client/remote-store.js.map +1 -1
  110. package/dist/mcp-client/routes.d.ts +1 -0
  111. package/dist/mcp-client/routes.d.ts.map +1 -1
  112. package/dist/mcp-client/routes.js +1 -0
  113. package/dist/mcp-client/routes.js.map +1 -1
  114. package/dist/provider-api/actions/github-repo-files.d.ts +2 -2
  115. package/dist/provider-api/actions/query-staged-dataset.d.ts +3 -3
  116. package/dist/provider-api/corpus-jobs.d.ts +8 -8
  117. package/dist/server/agent-chat-plugin.d.ts +2 -0
  118. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  119. package/dist/server/agent-chat-plugin.js +8 -0
  120. package/dist/server/agent-chat-plugin.js.map +1 -1
  121. package/dist/server/index.d.ts +1 -1
  122. package/dist/server/index.d.ts.map +1 -1
  123. package/dist/server/index.js +1 -1
  124. package/dist/server/index.js.map +1 -1
  125. package/dist/shared/mcp-embed-headers.d.ts +3 -1
  126. package/dist/shared/mcp-embed-headers.d.ts.map +1 -1
  127. package/dist/shared/mcp-embed-headers.js +40 -3
  128. package/dist/shared/mcp-embed-headers.js.map +1 -1
  129. package/dist/sharing/actions/list-resource-shares.d.ts +1 -1
  130. package/dist/sharing/actions/set-resource-visibility.d.ts +2 -2
  131. package/dist/sharing/actions/share-resource.d.ts +1 -1
  132. package/dist/sharing/schema.d.ts +1 -1
  133. package/dist/vite/client.d.ts.map +1 -1
  134. package/dist/vite/client.js +44 -0
  135. package/dist/vite/client.js.map +1 -1
  136. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"org-directory.js","sourceRoot":"","sources":["../../src/mcp/org-directory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAkBH,0DAA0D;AAC1D,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B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AE,WAAW,CAAC,OAAO,CAAC,IAAI,CAAC;SAClC,CAAC,CAAC;QACH,IAAI,GAAG,CAAC,EAAE,EAAE,CAAC;YACX,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAuB,CAAC;YACtD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YACxD,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;YACrE,GAAG,GAAG,cAAc,CAAC;QACvB,CAAC;QACD,qEAAqE;IACvE,CAAC;IAAC,MAAM,CAAC;QACP,oEAAoE;QACpE,IAAI,GAAG,EAAE,CAAC;QACV,GAAG,GAAG,YAAY,CAAC;IACrB,CAAC;IAED,IAAI,QAAQ,EAAE,CAAC;QACb,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE;YAClB,IAAI;YACJ,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG;SAC5B,CAAC,CAAC;IACL,CAAC;IACD,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC;AAED,0DAA0D;AAC1D,MAAM,UAAU,uBAAuB;IACrC,KAAK,CAAC,KAAK,EAAE,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Org-directory discovery for the generic cross-app MCP verbs\n * (`list_apps` / `ask_app` in `builtin-tools.ts`).\n *\n * Phase 3b of cross-app auto-wiring. Today the cross-app verbs resolve sibling\n * apps from *local workspace* info only (`workspace-resolve.ts`), so the mail\n * agent can only reach the calendar agent in a local dev workspace. When the\n * deployment runs against an org directory (Dispatch is also the identity hub\n * for the org), this module discovers the org's *deployed* sibling apps so the\n * same verbs work cross-app in production with ZERO manual setup.\n *\n * ## The directory request\n *\n * GET <directoryOrigin>/_agent-native/org/apps\n * Auth Authorization: Bearer <org A2A token> (same signed token A2A peers\n * already mint — reuses `resolveA2ACallerAuth()`; the org A2A secret /\n * global `A2A_SECRET` is loaded exactly how outgoing A2A calls load it)\n * ⇒ { org, apps: [ { id, name, url, a2aUrl, capabilities? } ] }\n * (allow-listed first-party apps only, prod URLs — enforced by the\n * authority side, Phase 3a, on Dispatch)\n *\n * ## Resolution + safety model\n *\n * - The directory origin is read from env: `AGENT_NATIVE_ORG_DIRECTORY_URL`\n * (dedicated) or `AGENT_NATIVE_IDENTITY_HUB_URL` (Dispatch is also the\n * identity hub). When *neither* is set the feature is simply inactive —\n * `fetchOrgApps()` returns `[]` and nothing changes anywhere (asserted by\n * a test). This makes the whole feature opt-in and back-compat.\n * - On ANY error (no env, unreachable, 401, non-2xx, bad JSON, no signed\n * token) `fetchOrgApps()` returns `[]` and NEVER throws — the cross-app\n * verbs degrade silently to their exact current local-only behavior.\n * - A short in-memory TTL cache (default 60s) keyed by directory origin and\n * caller identity/org scope so sibling app lists never cross tenants.\n * Empty authenticated results are cached too (with a shorter TTL) so a\n * transient failure doesn't hammer the directory on every call.\n * - No secrets are ever logged.\n *\n * Bundled alongside `mountMCP` (no Node-only top-level imports). The A2A\n * caller-auth + a2a client are dynamically imported inside `fetchOrgApps()`.\n */\n\nexport interface OrgApp {\n /** Canonical app id, e.g. `calendar`. */\n id: string;\n /** Human-readable name, e.g. `Calendar`. */\n name: string;\n /** Deployed app origin/URL, e.g. `https://calendar.acme.com`. */\n url: string;\n /**\n * A2A endpoint to route `ask_app` to. The authority side returns this; we\n * fall back to the app `url` (the A2A client appends `/_agent-native/a2a`).\n */\n a2aUrl: string;\n /** Optional capability hints the authority side may include. */\n capabilities?: string[];\n}\n\n/** Default cache TTL for a successful directory fetch. */\nconst SUCCESS_TTL_MS = 60_000;\n/** Shorter TTL for an empty/failed fetch so transient errors recover fast. */\nconst EMPTY_TTL_MS = 10_000;\n\ninterface CacheEntry {\n apps: OrgApp[];\n expiresAt: number;\n}\n\n/** In-memory cache keyed by resolved directory origin (+ identity scope). */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * Resolve the org-directory origin from env. Returns `null` when neither env\n * var is set — the caller treats `null` as \"feature inactive\".\n *\n * `env` is injectable for tests; defaults to `process.env`.\n */\nexport function resolveOrgDirectoryOrigin(\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const raw =\n env.AGENT_NATIVE_ORG_DIRECTORY_URL || env.AGENT_NATIVE_IDENTITY_HUB_URL;\n if (!raw || typeof raw !== \"string\") return null;\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (!trimmed) return null;\n try {\n // Validate it's an absolute http(s) URL; reject anything else.\n const u = new URL(trimmed);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n return trimmed;\n } catch {\n return null;\n }\n}\n\nfunction normalizeApp(raw: unknown): OrgApp | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const id = typeof r.id === \"string\" ? r.id.trim().toLowerCase() : \"\";\n const url = typeof r.url === \"string\" ? r.url.trim() : \"\";\n if (!id || !url) return null;\n // Only accept absolute http(s) URLs from the directory.\n try {\n const u = new URL(url);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n } catch {\n return null;\n }\n const name = typeof r.name === \"string\" && r.name.trim() ? r.name.trim() : id;\n const a2aUrl =\n typeof r.a2aUrl === \"string\" && r.a2aUrl.trim() ? r.a2aUrl.trim() : url;\n const capabilities = Array.isArray(r.capabilities)\n ? r.capabilities.filter((c): c is string => typeof c === \"string\")\n : undefined;\n return {\n id,\n name,\n url: url.replace(/\\/+$/, \"\"),\n a2aUrl: a2aUrl.replace(/\\/+$/, \"\"),\n ...(capabilities && capabilities.length ? { capabilities } : {}),\n };\n}\n\n/** Compare two origins by host (ignores trailing slash / protocol noise). */\nfunction sameOrigin(a: string, b: string): boolean {\n try {\n const ua = new URL(a);\n const ub = new URL(b);\n return ua.host === ub.host && ua.protocol === ub.protocol;\n } catch {\n return a.replace(/\\/+$/, \"\") === b.replace(/\\/+$/, \"\");\n }\n}\n\nfunction scopedCacheKey(\n origin: string,\n auth: {\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n },\n): string {\n return [\n origin,\n `user:${auth.userEmail ?? \"\"}`,\n `org:${auth.orgId ?? auth.orgDomain ?? \"\"}`,\n ].join(\"|\");\n}\n\n/**\n * Fetch the org's first-party sibling apps from the org directory.\n *\n * - Returns `[]` (never throws) on ANY failure or when the directory env is\n * unset — the cross-app verbs then keep their exact local-only behavior.\n * - Short in-memory TTL cache so it isn't fetched on every tool call.\n * - Strips the current app from the result (compared by id and by origin) so\n * `list_apps` / `ask_app` never offer to route to themselves.\n *\n * @param opts.selfId Current app id (so it's stripped from the result).\n * @param opts.selfOrigin Current app origin (so it's stripped by origin too).\n * @param opts.env Injectable env (tests). Defaults to `process.env`.\n */\nexport async function fetchOrgApps(opts?: {\n selfId?: string;\n selfOrigin?: string;\n env?: NodeJS.ProcessEnv;\n}): Promise<OrgApp[]> {\n const env = opts?.env ?? process.env;\n const origin = resolveOrgDirectoryOrigin(env);\n // Feature inactive: no directory configured ⇒ behave exactly as before.\n if (!origin) return [];\n\n const selfId = (opts?.selfId ?? \"\").trim().toLowerCase();\n const selfOrigin = (opts?.selfOrigin ?? \"\").trim();\n\n const stripSelf = (apps: OrgApp[]): OrgApp[] =>\n apps.filter((a) => {\n if (selfId && a.id === selfId) return false;\n if (selfOrigin && sameOrigin(a.url, selfOrigin)) return false;\n return true;\n });\n\n let cacheKey: string | null = null;\n let apps: OrgApp[] = [];\n let ttl = EMPTY_TTL_MS;\n try {\n // Reuse the existing A2A caller-auth: it reads userEmail + orgId from the\n // request context, loads the org A2A secret via getOrgA2ASecret (falling\n // back to the global A2A_SECRET env), and signs the same bearer JWT A2A\n // peers already use. No new secret loading is invented here.\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n const auth = await resolveA2ACallerAuth();\n if (!auth.apiKey) {\n // No signed token available (no A2A secret / no caller identity) — the\n // directory requires the org bearer, so degrade silently to local-only.\n return [];\n }\n\n const now = Date.now();\n cacheKey = scopedCacheKey(origin, auth);\n const cached = cache.get(cacheKey);\n if (cached && cached.expiresAt > now) {\n return stripSelf(cached.apps);\n }\n\n const res = await fetch(`${origin}/_agent-native/org/apps`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(4000),\n });\n if (res.ok) {\n const json = (await res.json()) as { apps?: unknown };\n const list = Array.isArray(json?.apps) ? json.apps : [];\n apps = list.map(normalizeApp).filter((a): a is OrgApp => a !== null);\n ttl = SUCCESS_TTL_MS;\n }\n // Non-2xx ⇒ leave apps=[] with the short EMPTY_TTL (silent degrade).\n } catch {\n // Unreachable / parse error / abort ⇒ silent degrade to local-only.\n apps = [];\n ttl = EMPTY_TTL_MS;\n }\n\n if (cacheKey) {\n cache.set(cacheKey, {\n apps,\n expiresAt: Date.now() + ttl,\n });\n }\n return stripSelf(apps);\n}\n\n/** Test-only: clear the in-memory cache between cases. */\nexport function _resetOrgDirectoryCache(): void {\n cache.clear();\n}\n"]}
1
+ {"version":3,"file":"org-directory.js","sourceRoot":"","sources":["../../src/mcp/org-directory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAkBH,0DAA0D;AAC1D,MAAM,cAAc,GAAG,MAAM,CAAC;AAC9B,8EAA8E;AAC9E,MAAM,YAAY,GAAG,MAAM,CAAC;AAO5B,6EAA6E;AAC7E,MAAM,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAAyB,OAAO,CAAC,GAAG;IAEpC,MAAM,GAAG,GACP,GAAG,CAAC,8BAA8B,IAAI,GAAG,CAAC,6BAA6B,CAAC;IAC1E,IAAI,CAAC,G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CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IAC5C,CAAC;AACH,CAAC","sourcesContent":["/**\n * Org-directory discovery for the generic cross-app MCP verbs\n * (`list_apps` / `ask_app` in `builtin-tools.ts`).\n *\n * Phase 3b of cross-app auto-wiring. Today the cross-app verbs resolve sibling\n * apps from *local workspace* info only (`workspace-resolve.ts`), so the mail\n * agent can only reach the calendar agent in a local dev workspace. When the\n * deployment runs against an org directory (Dispatch is also the identity hub\n * for the org), this module discovers the org's *deployed* sibling apps so the\n * same verbs work cross-app in production with ZERO manual setup.\n *\n * ## The directory request\n *\n * GET <directoryOrigin>/_agent-native/org/apps\n * Auth Authorization: Bearer <org A2A token> (same signed token A2A peers\n * already mint — reuses `resolveA2ACallerAuth()`; the org A2A secret /\n * global `A2A_SECRET` is loaded exactly how outgoing A2A calls load it)\n * ⇒ { org, apps: [ { id, name, url, a2aUrl, capabilities? } ] }\n * (allow-listed first-party apps only, prod URLs — enforced by the\n * authority side, Phase 3a, on Dispatch)\n *\n * ## Resolution + safety model\n *\n * - The directory origin is read from env: `AGENT_NATIVE_ORG_DIRECTORY_URL`\n * (dedicated) or `AGENT_NATIVE_IDENTITY_HUB_URL` (Dispatch is also the\n * identity hub). When *neither* is set the feature is simply inactive —\n * `fetchOrgApps()` returns `[]` and nothing changes anywhere (asserted by\n * a test). This makes the whole feature opt-in and back-compat.\n * - On ANY error (no env, unreachable, 401, non-2xx, bad JSON, no signed\n * token) `fetchOrgApps()` returns `[]` and NEVER throws — the cross-app\n * verbs degrade silently to their exact current local-only behavior.\n * - A short in-memory TTL cache (default 60s) keyed by directory origin and\n * caller identity/org scope so sibling app lists never cross tenants.\n * Empty authenticated results are cached too (with a shorter TTL) so a\n * transient failure doesn't hammer the directory on every call.\n * - No secrets are ever logged.\n *\n * Bundled alongside `mountMCP` (no Node-only top-level imports). The A2A\n * caller-auth + a2a client are dynamically imported inside `fetchOrgApps()`.\n */\n\nexport interface OrgApp {\n /** Canonical app id, e.g. `calendar`. */\n id: string;\n /** Human-readable name, e.g. `Calendar`. */\n name: string;\n /** Deployed app origin/URL, e.g. `https://calendar.acme.com`. */\n url: string;\n /**\n * A2A endpoint to route `ask_app` to. The authority side returns this; we\n * fall back to the app `url` (the A2A client appends `/_agent-native/a2a`).\n */\n a2aUrl: string;\n /** Optional capability hints the authority side may include. */\n capabilities?: string[];\n}\n\n/** Default cache TTL for a successful directory fetch. */\nconst SUCCESS_TTL_MS = 60_000;\n/** Shorter TTL for an empty/failed fetch so transient errors recover fast. */\nconst EMPTY_TTL_MS = 10_000;\n\ninterface CacheEntry {\n apps: OrgApp[];\n expiresAt: number;\n}\n\n/** In-memory cache keyed by resolved directory origin (+ identity scope). */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * Resolve the org-directory origin from env. Returns `null` when neither env\n * var is set — the caller treats `null` as \"feature inactive\".\n *\n * `env` is injectable for tests; defaults to `process.env`.\n */\nexport function resolveOrgDirectoryOrigin(\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const raw =\n env.AGENT_NATIVE_ORG_DIRECTORY_URL || env.AGENT_NATIVE_IDENTITY_HUB_URL;\n if (!raw || typeof raw !== \"string\") return null;\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (!trimmed) return null;\n try {\n // Validate it's an absolute http(s) URL; reject anything else.\n const u = new URL(trimmed);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n return trimmed;\n } catch {\n return null;\n }\n}\n\nfunction normalizeApp(raw: unknown): OrgApp | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const id = typeof r.id === \"string\" ? r.id.trim().toLowerCase() : \"\";\n const url = typeof r.url === \"string\" ? r.url.trim() : \"\";\n if (!id || !url) return null;\n // Only accept absolute http(s) URLs from the directory.\n try {\n const u = new URL(url);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") return null;\n } catch {\n return null;\n }\n const name = typeof r.name === \"string\" && r.name.trim() ? r.name.trim() : id;\n const a2aUrl =\n typeof r.a2aUrl === \"string\" && r.a2aUrl.trim() ? r.a2aUrl.trim() : url;\n const capabilities = Array.isArray(r.capabilities)\n ? r.capabilities.filter((c): c is string => typeof c === \"string\")\n : undefined;\n return {\n id,\n name,\n url: url.replace(/\\/+$/, \"\"),\n a2aUrl: a2aUrl.replace(/\\/+$/, \"\"),\n ...(capabilities && capabilities.length ? { capabilities } : {}),\n };\n}\n\n/** Compare two origins by host (ignores trailing slash / protocol noise). */\nfunction sameOrigin(a: string, b: string): boolean {\n try {\n const ua = new URL(a);\n const ub = new URL(b);\n return ua.host === ub.host && ua.protocol === ub.protocol;\n } catch {\n return a.replace(/\\/+$/, \"\") === b.replace(/\\/+$/, \"\");\n }\n}\n\nfunction scopedCacheKey(\n origin: string,\n auth: {\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n },\n): string {\n return [\n origin,\n `user:${auth.userEmail ?? \"\"}`,\n `org:${auth.orgId ?? auth.orgDomain ?? \"\"}`,\n ].join(\"|\");\n}\n\nfunction serviceScopedCacheKey(origin: string, orgId: string): string {\n return [origin, `service-org:${orgId}`].join(\"|\");\n}\n\n/**\n * Fetch the org's first-party sibling apps from the org directory.\n *\n * - Returns `[]` (never throws) on ANY failure or when the directory env is\n * unset — the cross-app verbs then keep their exact local-only behavior.\n * - Short in-memory TTL cache so it isn't fetched on every tool call.\n * - Strips the current app from the result (compared by id and by origin) so\n * `list_apps` / `ask_app` never offer to route to themselves.\n *\n * @param opts.selfId Current app id (so it's stripped from the result).\n * @param opts.selfOrigin Current app origin (so it's stripped by origin too).\n * @param opts.env Injectable env (tests). Defaults to `process.env`.\n */\nexport async function fetchOrgApps(opts?: {\n selfId?: string;\n selfOrigin?: string;\n serviceOrgId?: string;\n env?: NodeJS.ProcessEnv;\n}): Promise<OrgApp[]> {\n const env = opts?.env ?? process.env;\n const origin = resolveOrgDirectoryOrigin(env);\n // Feature inactive: no directory configured ⇒ behave exactly as before.\n if (!origin) return [];\n\n const selfId = (opts?.selfId ?? \"\").trim().toLowerCase();\n const selfOrigin = (opts?.selfOrigin ?? \"\").trim();\n\n const stripSelf = (apps: OrgApp[]): OrgApp[] =>\n apps.filter((a) => {\n if (selfId && a.id === selfId) return false;\n if (selfOrigin && sameOrigin(a.url, selfOrigin)) return false;\n return true;\n });\n\n let cacheKey: string | null = null;\n let apps: OrgApp[] = [];\n let ttl = EMPTY_TTL_MS;\n const serviceOrgId = opts?.serviceOrgId?.trim();\n if (serviceOrgId) {\n const serviceCacheKey = serviceScopedCacheKey(origin, serviceOrgId);\n const cached = cache.get(serviceCacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return stripSelf(cached.apps);\n }\n cacheKey = serviceCacheKey;\n }\n try {\n const auth = serviceOrgId\n ? await resolveOrgDirectoryServiceAuth(serviceOrgId)\n : await resolveOrgDirectoryCallerAuth();\n if (!auth.apiKey) {\n // No signed token available (no A2A secret / no caller identity) — the\n // directory requires the org bearer, so degrade silently to local-only.\n return [];\n }\n\n if (!cacheKey) {\n const now = Date.now();\n cacheKey = scopedCacheKey(origin, auth);\n const cached = cache.get(cacheKey);\n if (cached && cached.expiresAt > now) {\n return stripSelf(cached.apps);\n }\n }\n\n const res = await fetch(`${origin}/_agent-native/org/apps`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(4000),\n });\n if (res.ok) {\n const json = (await res.json()) as { apps?: unknown };\n const list = Array.isArray(json?.apps) ? json.apps : [];\n apps = list.map(normalizeApp).filter((a): a is OrgApp => a !== null);\n ttl = SUCCESS_TTL_MS;\n }\n // Non-2xx ⇒ leave apps=[] with the short EMPTY_TTL (silent degrade).\n } catch {\n // Unreachable / parse error / abort ⇒ silent degrade to local-only.\n apps = [];\n ttl = EMPTY_TTL_MS;\n }\n\n if (cacheKey) {\n cache.set(cacheKey, {\n apps,\n expiresAt: Date.now() + ttl,\n });\n }\n return stripSelf(apps);\n}\n\n/** Test-only: clear the in-memory cache between cases. */\nexport function _resetOrgDirectoryCache(): void {\n cache.clear();\n}\n\nasync function resolveOrgDirectoryCallerAuth(): Promise<{\n apiKey?: string;\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n}> {\n // Reuse the existing A2A caller-auth: it reads userEmail + orgId from the\n // request context, loads the org A2A secret via getOrgA2ASecret (falling\n // back to the global A2A_SECRET env), and signs the same bearer JWT A2A\n // peers already use. No new secret loading is invented for normal callers.\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n return resolveA2ACallerAuth();\n}\n\nasync function resolveOrgDirectoryServiceAuth(orgId: string): Promise<{\n apiKey?: string;\n userEmail?: string;\n orgId?: string;\n orgDomain?: string;\n}> {\n const trimmedOrgId = orgId.trim();\n if (!trimmedOrgId) return {};\n let orgDomain: string | undefined;\n let orgSecret: string | undefined;\n try {\n const { getOrgDomain, getOrgA2ASecret } = await import(\"../org/context.js\");\n orgDomain = (await getOrgDomain(trimmedOrgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(trimmedOrgId)) ?? undefined;\n } catch {}\n try {\n const [{ signA2AToken }, { serviceIdentityEmail }] = await Promise.all([\n import(\"../a2a/client.js\"),\n import(\"./connect-store.js\"),\n ]);\n const userEmail = serviceIdentityEmail(\"mcp-client\", trimmedOrgId);\n const apiKey = await signA2AToken(userEmail, orgDomain, orgSecret, {\n expiresIn: \"5m\",\n preferGlobalSecret: !orgSecret,\n extraClaims: { org_id: trimmedOrgId },\n });\n return { apiKey, userEmail, orgId: trimmedOrgId, orgDomain };\n } catch {\n return { orgId: trimmedOrgId, orgDomain };\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAYlC,OAAO,EACL,yBAAyB,EACzB,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,OAAO,CACR,QAAQ,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAC5E,CAuKA;AAMD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,QAAQ,CACtB,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,SAAS,EACjB,WAAW,SAAmB,GAC7B,IAAI,CAYN"}
@@ -56,6 +56,10 @@ function deriveRequestMeta(event) {
56
56
  const fullCatalog = fullCatalogHeader === "1" ||
57
57
  fullCatalogHeader === "true" ||
58
58
  fullCatalogHeader === "yes";
59
+ const inlineAppsHeader = getRequestHeader(event, "x-agent-native-mcp-inline-apps")?.toLowerCase();
60
+ const inlineAppsRequested = inlineAppsHeader === "1" ||
61
+ inlineAppsHeader === "true" ||
62
+ inlineAppsHeader === "yes";
59
63
  const basePath = getConfiguredAppBasePath();
60
64
  return {
61
65
  origin,
@@ -64,6 +68,7 @@ function deriveRequestMeta(event) {
64
68
  clientName,
65
69
  clientHint,
66
70
  ...(fullCatalog ? { fullCatalog } : {}),
71
+ ...(inlineAppsRequested ? { inlineMcpApps: true } : {}),
67
72
  };
68
73
  }
69
74
  function isLoopbackOrigin(origin) {
@@ -265,6 +270,10 @@ export async function handleMcpRequest(event, config) {
265
270
  const server = await createMCPServerForRequest(config, authResult.identity, {
266
271
  ...requestMeta,
267
272
  fullSurface: authResult.fullSurface === true,
273
+ inlineMcpApps: requestMeta.inlineMcpApps === true &&
274
+ authResult.identity?.firstPartyMcp === true
275
+ ? true
276
+ : undefined,
268
277
  // When the caller minted their token with --full-catalog (catalog_scope:
269
278
  // "full" JWT claim), bypass the connector-catalog tier filter.
270
279
  ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,w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BAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CACH,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport {\n buildMcpOAuthChallenge,\n getMcpOAuthAudiences,\n getMcpOAuthIssuer,\n getMcpOAuthProtectedResourceMetadataUrl,\n getMcpOAuthResource,\n} from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}/_agent-native/mcp`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n/**\n * Build an actionable JSON body for the 401 response. OAuth-capable clients\n * follow the `WWW-Authenticate` header automatically, but the JSON body is what\n * a human or a coding agent reads when a tool call comes back unauthorized — so\n * spell out the exact remediation: the `agent-native connect <url>` command and\n * the authorize/metadata URL. Keeping the legacy `error: \"Unauthorized\"` field\n * means existing clients that only check that field still work.\n */\nfunction buildUnauthorizedBody(event: H3Event): {\n error: string;\n message: string;\n authenticate: {\n command?: string;\n firstTimeCommand?: string;\n authorizeUrl?: string;\n resourceMetadataUrl?: string;\n mcpUrl?: string;\n };\n} {\n const issuer = getMcpOAuthIssuer(event);\n const mcpUrl = getMcpOAuthResource(event);\n const resourceMetadataUrl = getMcpOAuthProtectedResourceMetadataUrl(event);\n const command = issuer\n ? `npx -y @agent-native/core@latest reconnect ${issuer}`\n : undefined;\n const firstTimeCommand = issuer\n ? `npx @agent-native/core@latest connect ${issuer}`\n : undefined;\n const authorizeUrl = issuer\n ? `${issuer}/_agent-native/mcp/oauth/authorize`\n : undefined;\n const message = command\n ? `Authentication required. Run \\`${command}\\` to re-authenticate this ` +\n `MCP connector without reinstalling it (or, in a Claude Code host, ` +\n `run /mcp and choose Authenticate), then retry. For first-time ` +\n `setup, run \\`${firstTimeCommand}\\`.`\n : \"Authentication required. Authenticate the MCP connector in your host, \" +\n \"then retry.\";\n return {\n error: \"Unauthorized\",\n message,\n authenticate: {\n ...(command ? { command } : {}),\n ...(firstTimeCommand ? { firstTimeCommand } : {}),\n ...(authorizeUrl ? { authorizeUrl } : {}),\n ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),\n ...(mcpUrl ? { mcpUrl } : {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<\n Response | string | { error: string } | Record<string, unknown> | undefined\n> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthAudiences(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return buildUnauthorizedBody(event);\n }\n\n // Stateless mode: only POST is meaningful. A stateless, per-request transport\n // on serverless cannot keep the standalone GET SSE stream (server->client\n // channel) alive across invocations — once the function returns and freezes,\n // that stream dies and the client reports \"session expired\" / \"not\n // connected\". The spec lets a server that offers no GET stream answer 405, so\n // the client falls back to plain POST request/response. Reject GET here\n // instead of letting the SDK open a doomed stream.\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Optional diagnostics for host capability negotiation. Keep disabled by\n // default because initialize payloads can include client-specific metadata.\n if (process.env.MCP_DEBUG_INIT && body) {\n const msgs = Array.isArray(body) ? body : [body];\n const init = msgs.find(\n (m): m is { params?: { capabilities?: unknown; clientInfo?: unknown } } =>\n typeof m === \"object\" &&\n m !== null &&\n (m as { method?: unknown }).method === \"initialize\",\n );\n if (init) {\n console.error(\n \"[MCP_DEBUG_INIT] clientInfo=\",\n JSON.stringify(init.params?.clientInfo),\n \"capabilities=\",\n JSON.stringify(init.params?.capabilities),\n );\n }\n }\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n // When the caller minted their token with --full-catalog (catalog_scope:\n // \"full\" JWT claim), bypass the connector-catalog tier filter.\n ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n // Return JSON request/response instead of SSE. A stateless serverless\n // instance can freeze right after returning a streaming Response, before\n // the deferred SSE result event is flushed — the client then never gets\n // the tools/call result and reports \"session expired\". JSON mode awaits\n // the result inside the request lifecycle and returns it as one body.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n // JSON request/response (not SSE) — see the Node fast-path note above.\n // This is the serverless-safe framing: the result is computed and returned\n // within the request, never pushed onto a stream after the instance froze.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions, JSON\n * request/response (no SSE), and no standalone GET stream, so it survives\n * serverless instances that freeze between invocations (SSE framing there\n * drops the result and clients report \"session expired\"). Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GAInB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,EACjB,uCAAuC,EACvC,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAE1B,6EAA6E;AAC7E,4EAA4E;AAC5E,yDAAyD;AACzD,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AAGF,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,KAAc;IAInC,MAAM,CAAC,GAAG,KAAY,CAAC;IACvB,MAAM,OAAO,GAA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ourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport {\n buildMcpOAuthChallenge,\n getMcpOAuthAudiences,\n getMcpOAuthIssuer,\n getMcpOAuthProtectedResourceMetadataUrl,\n getMcpOAuthResource,\n} from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const inlineAppsHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-inline-apps\",\n )?.toLowerCase();\n const inlineAppsRequested =\n inlineAppsHeader === \"1\" ||\n inlineAppsHeader === \"true\" ||\n inlineAppsHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n ...(inlineAppsRequested ? { inlineMcpApps: true } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}/_agent-native/mcp`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n/**\n * Build an actionable JSON body for the 401 response. OAuth-capable clients\n * follow the `WWW-Authenticate` header automatically, but the JSON body is what\n * a human or a coding agent reads when a tool call comes back unauthorized — so\n * spell out the exact remediation: the `agent-native connect <url>` command and\n * the authorize/metadata URL. Keeping the legacy `error: \"Unauthorized\"` field\n * means existing clients that only check that field still work.\n */\nfunction buildUnauthorizedBody(event: H3Event): {\n error: string;\n message: string;\n authenticate: {\n command?: string;\n firstTimeCommand?: string;\n authorizeUrl?: string;\n resourceMetadataUrl?: string;\n mcpUrl?: string;\n };\n} {\n const issuer = getMcpOAuthIssuer(event);\n const mcpUrl = getMcpOAuthResource(event);\n const resourceMetadataUrl = getMcpOAuthProtectedResourceMetadataUrl(event);\n const command = issuer\n ? `npx -y @agent-native/core@latest reconnect ${issuer}`\n : undefined;\n const firstTimeCommand = issuer\n ? `npx @agent-native/core@latest connect ${issuer}`\n : undefined;\n const authorizeUrl = issuer\n ? `${issuer}/_agent-native/mcp/oauth/authorize`\n : undefined;\n const message = command\n ? `Authentication required. Run \\`${command}\\` to re-authenticate this ` +\n `MCP connector without reinstalling it (or, in a Claude Code host, ` +\n `run /mcp and choose Authenticate), then retry. For first-time ` +\n `setup, run \\`${firstTimeCommand}\\`.`\n : \"Authentication required. Authenticate the MCP connector in your host, \" +\n \"then retry.\";\n return {\n error: \"Unauthorized\",\n message,\n authenticate: {\n ...(command ? { command } : {}),\n ...(firstTimeCommand ? { firstTimeCommand } : {}),\n ...(authorizeUrl ? { authorizeUrl } : {}),\n ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),\n ...(mcpUrl ? { mcpUrl } : {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<\n Response | string | { error: string } | Record<string, unknown> | undefined\n> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthAudiences(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return buildUnauthorizedBody(event);\n }\n\n // Stateless mode: only POST is meaningful. A stateless, per-request transport\n // on serverless cannot keep the standalone GET SSE stream (server->client\n // channel) alive across invocations — once the function returns and freezes,\n // that stream dies and the client reports \"session expired\" / \"not\n // connected\". The spec lets a server that offers no GET stream answer 405, so\n // the client falls back to plain POST request/response. Reject GET here\n // instead of letting the SDK open a doomed stream.\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Optional diagnostics for host capability negotiation. Keep disabled by\n // default because initialize payloads can include client-specific metadata.\n if (process.env.MCP_DEBUG_INIT && body) {\n const msgs = Array.isArray(body) ? body : [body];\n const init = msgs.find(\n (m): m is { params?: { capabilities?: unknown; clientInfo?: unknown } } =>\n typeof m === \"object\" &&\n m !== null &&\n (m as { method?: unknown }).method === \"initialize\",\n );\n if (init) {\n console.error(\n \"[MCP_DEBUG_INIT] clientInfo=\",\n JSON.stringify(init.params?.clientInfo),\n \"capabilities=\",\n JSON.stringify(init.params?.capabilities),\n );\n }\n }\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n inlineMcpApps:\n requestMeta.inlineMcpApps === true &&\n authResult.identity?.firstPartyMcp === true\n ? true\n : undefined,\n // When the caller minted their token with --full-catalog (catalog_scope:\n // \"full\" JWT claim), bypass the connector-catalog tier filter.\n ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n // Return JSON request/response instead of SSE. A stateless serverless\n // instance can freeze right after returning a streaming Response, before\n // the deferred SSE result event is flushed — the client then never gets\n // the tools/call result and reports \"session expired\". JSON mode awaits\n // the result inside the request lifecycle and returns it as one body.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n // JSON request/response (not SSE) — see the Node fast-path note above.\n // This is the serverless-safe framing: the result is computed and returned\n // within the request, never pushed onto a stream after the instance froze.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions, JSON\n * request/response (no SSE), and no standalone GET stream, so it survives\n * serverless instances that freeze between invocations (SSE framing there\n * drops the result and clients report \"session expired\"). Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
@@ -38,6 +38,18 @@ export interface McpHttpServerConfig {
38
38
  url: string;
39
39
  /** Extra headers to send with every request (e.g. Authorization). */
40
40
  headers?: Record<string, string>;
41
+ /**
42
+ * Trusted first-party Agent-Native app. This is set only by framework-owned
43
+ * org-scoped registrations, not by raw file/env config.
44
+ */
45
+ firstParty?: boolean;
46
+ /** Canonical first-party app id from the org directory, e.g. `assets`. */
47
+ firstPartyAppId?: string;
48
+ /**
49
+ * Org id the first-party server is trusted for. Runtime-only metadata set by
50
+ * framework-owned registrations; raw file/env config cannot provide it.
51
+ */
52
+ firstPartyOrgId?: string;
41
53
  /** Human-readable description (optional, shown in /mcp/status) */
42
54
  description?: string;
43
55
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/mcp-client/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAOH;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,6CAA6C;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,oEAAoE;IACpE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,yDAAyD;IACzD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,mB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AE,CAAC;QACnC,IAAI,CAAC;YACH,IAAI,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;gBAC7B,OAAO;oBACL,OAAO,EAAE;wBACP,kBAAkB,EAAE;4BAClB,IAAI,EAAE,OAAO;4BACb,OAAO,EAAE,SAAS;4BAClB,WAAW,EACT,+DAA+D;yBAClE;qBACF;oBACD,MAAM,EAAE,cAAc,SAAS,EAAE;iBAClC,CAAC;YACJ,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,+BAA+B;QACjC,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * MCP client configuration loading.\n *\n * Resolves `mcp.config.json` in the following precedence order:\n * 1. Workspace root (detected via `agent-native.workspaceCore` in package.json)\n * 2. App root (`process.cwd()`)\n * 3. `MCP_SERVERS` env var (JSON string) — for CI / production deploys\n *\n * Returns `null` when nothing is configured.\n *\n * This module is Node-only — it reads the filesystem. `loadMcpConfig()` guards\n * every fs operation with `isNode()` so a non-Node bundle simply gets `null`.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { findWorkspaceRoot } from \"../scripts/utils.js\";\n\n/**\n * Stdio transport — spawns a local binary and speaks MCP over its stdio.\n * This is the default when no `type` field is set (backward compat).\n */\nexport interface McpStdioServerConfig {\n type?: \"stdio\";\n /** Executable or path to spawn over stdio */\n command: string;\n /** Arguments passed to the command */\n args?: string[];\n /** Extra env vars merged into process.env for the spawned server */\n env?: Record<string, string>;\n /** Optional working directory for the spawned process */\n cwd?: string;\n /** Human-readable description (optional, shown in /mcp/status) */\n description?: string;\n}\n\n/**\n * HTTP transport — connects to a remote MCP server over Streamable HTTP\n * (the transport hosted providers like Zapier / Cloudflare / Composio use).\n */\nexport interface McpHttpServerConfig {\n type: \"http\";\n /** Full URL of the remote MCP server's Streamable HTTP endpoint. */\n url: string;\n /** Extra headers to send with every request (e.g. Authorization). */\n headers?: Record<string, string>;\n /** Human-readable description (optional, shown in /mcp/status) */\n description?: string;\n}\n\nexport type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;\n\nexport interface McpConfig {\n /** Map of server id → config */\n servers: Record<string, McpServerConfig>;\n /** Where the config was loaded from (workspace root path, app path, or \"env\") */\n source?: string;\n}\n\nfunction isNode(): boolean {\n return (\n typeof process !== \"undefined\" &&\n !!(process as any).versions?.node &&\n typeof (process as any).versions.node === \"string\"\n );\n}\n\nfunction parseConfig(raw: string, source: string): McpConfig | null {\n try {\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") return null;\n const servers =\n parsed.servers && typeof parsed.servers === \"object\"\n ? (parsed.servers as Record<string, McpServerConfig>)\n : null;\n if (!servers) return null;\n const valid: Record<string, McpServerConfig> = {};\n for (const [id, cfg] of Object.entries(servers)) {\n if (!cfg || typeof cfg !== \"object\") continue;\n const c = cfg as any;\n const description =\n typeof c.description === \"string\" ? c.description : undefined;\n if (c.type === \"http\") {\n if (typeof c.url !== \"string\" || !c.url) continue;\n valid[id] = {\n type: \"http\",\n url: c.url,\n headers:\n c.headers && typeof c.headers === \"object\"\n ? Object.fromEntries(\n Object.entries(c.headers).map(([k, v]) => [k, String(v)]),\n )\n : undefined,\n description,\n };\n } else {\n if (typeof c.command !== \"string\" || !c.command) continue;\n valid[id] = {\n type: \"stdio\",\n command: c.command,\n args: Array.isArray(c.args) ? c.args.map(String) : undefined,\n env:\n c.env && typeof c.env === \"object\"\n ? Object.fromEntries(\n Object.entries(c.env).map(([k, v]) => [k, String(v)]),\n )\n : undefined,\n cwd: typeof c.cwd === \"string\" ? c.cwd : undefined,\n description,\n };\n }\n }\n if (Object.keys(valid).length === 0) return null;\n return { servers: valid, source };\n } catch {\n return null;\n }\n}\n\n/**\n * Load MCP configuration.\n *\n * @param startDir - Directory to start the upward search from (defaults to cwd)\n */\nexport function loadMcpConfig(startDir?: string): McpConfig | null {\n const envConfig = readEnvConfig();\n\n let fileConfig: McpConfig | null = null;\n if (isNode()) {\n try {\n fileConfig = readFileConfig(startDir);\n } catch {\n fileConfig = null;\n }\n }\n\n if (fileConfig) return fileConfig;\n return envConfig;\n}\n\nfunction readEnvConfig(): McpConfig | null {\n if (typeof process === \"undefined\") return null;\n const raw = process.env?.MCP_SERVERS;\n if (!raw || !raw.trim()) return null;\n const trimmed = raw.trim();\n // Try full shape first ({ servers: {...} })\n const full = parseConfig(trimmed, \"env:MCP_SERVERS\");\n if (full) return full;\n // Then try inner-map shape ({ <id>: {...} })\n return parseConfig(`{\"servers\":${trimmed}}`, \"env:MCP_SERVERS\");\n}\n\nfunction readFileConfig(startDir?: string): McpConfig | null {\n const cwd = startDir ?? process.cwd();\n\n const workspaceRoot = findWorkspaceRoot(cwd);\n if (workspaceRoot) {\n const wsConfigPath = path.join(workspaceRoot, \"mcp.config.json\");\n if (fs.existsSync(wsConfigPath)) {\n return parseConfig(fs.readFileSync(wsConfigPath, \"utf-8\"), wsConfigPath);\n }\n }\n\n const appConfigPath = path.join(cwd, \"mcp.config.json\");\n if (fs.existsSync(appConfigPath)) {\n return parseConfig(fs.readFileSync(appConfigPath, \"utf-8\"), appConfigPath);\n }\n\n return null;\n}\n\n/**\n * Auto-detect the claude-in-chrome MCP server if it's installed but no\n * config file exists. Gated by `AGENT_NATIVE_DISABLE_MCP_AUTODETECT`.\n *\n * Returns a synthesized config pointing at the detected binary, or `null`\n * when nothing is found or auto-detect is disabled.\n */\nexport function autoDetectMcpConfig(): McpConfig | null {\n if (!isNode()) return null;\n if (process.env.AGENT_NATIVE_DISABLE_MCP_AUTODETECT) return null;\n\n const candidates: string[] = [];\n\n const home = os.homedir();\n if (home) {\n candidates.push(\n path.join(home, \".claude-in-chrome\", \"bin\", \"claude-in-chrome-mcp\"),\n );\n }\n\n const pathEnv = process.env.PATH || \"\";\n const sep = process.platform === \"win32\" ? \";\" : \":\";\n const exeSuffix = process.platform === \"win32\" ? \".exe\" : \"\";\n for (const dir of pathEnv.split(sep)) {\n if (!dir) continue;\n candidates.push(path.join(dir, `claude-in-chrome-mcp${exeSuffix}`));\n }\n\n for (const candidate of candidates) {\n try {\n if (fs.existsSync(candidate)) {\n return {\n servers: {\n \"claude-in-chrome\": {\n type: \"stdio\",\n command: candidate,\n description:\n \"Auto-detected claude-in-chrome MCP server (Chrome automation)\",\n },\n },\n source: `autodetect:${candidate}`,\n };\n }\n } catch {\n // Keep trying other candidates\n }\n }\n\n return null;\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/mcp-client/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAuDxD,SAAS,MAAM;IACb,OAAO,CACL,OAAO,OAAO,KAAK,WAAW;QAC9B,CAAC,CAAE,OAAe,CAAC,QAAQ,EAAE,IAAI;QACjC,OAAQ,OAAe,CAAC,QAAQ,CAAC,IAAI,KAAK,QAAQ,CACnD,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,GAAW,EAAE,MAAc;IAC9C,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QACvD,MAAM,OAAO,GACX,MAAM,CAAC,OAAO,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ;YAClD,CAAC,CAAE,MAAM,CAAC,OAA2C;YACrD,CAAC,CAAC,IAAI,CAAC;QACX,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC;QAC1B,MAAM,KAAK,GAAoC,EAAE,CAAC;QAClD,KAAK,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,IAAI,MAAM,CA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AAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * MCP client configuration loading.\n *\n * Resolves `mcp.config.json` in the following precedence order:\n * 1. Workspace root (detected via `agent-native.workspaceCore` in package.json)\n * 2. App root (`process.cwd()`)\n * 3. `MCP_SERVERS` env var (JSON string) — for CI / production deploys\n *\n * Returns `null` when nothing is configured.\n *\n * This module is Node-only — it reads the filesystem. `loadMcpConfig()` guards\n * every fs operation with `isNode()` so a non-Node bundle simply gets `null`.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { findWorkspaceRoot } from \"../scripts/utils.js\";\n\n/**\n * Stdio transport — spawns a local binary and speaks MCP over its stdio.\n * This is the default when no `type` field is set (backward compat).\n */\nexport interface McpStdioServerConfig {\n type?: \"stdio\";\n /** Executable or path to spawn over stdio */\n command: string;\n /** Arguments passed to the command */\n args?: string[];\n /** Extra env vars merged into process.env for the spawned server */\n env?: Record<string, string>;\n /** Optional working directory for the spawned process */\n cwd?: string;\n /** Human-readable description (optional, shown in /mcp/status) */\n description?: string;\n}\n\n/**\n * HTTP transport — connects to a remote MCP server over Streamable HTTP\n * (the transport hosted providers like Zapier / Cloudflare / Composio use).\n */\nexport interface McpHttpServerConfig {\n type: \"http\";\n /** Full URL of the remote MCP server's Streamable HTTP endpoint. */\n url: string;\n /** Extra headers to send with every request (e.g. Authorization). */\n headers?: Record<string, string>;\n /**\n * Trusted first-party Agent-Native app. This is set only by framework-owned\n * org-scoped registrations, not by raw file/env config.\n */\n firstParty?: boolean;\n /** Canonical first-party app id from the org directory, e.g. `assets`. */\n firstPartyAppId?: string;\n /**\n * Org id the first-party server is trusted for. Runtime-only metadata set by\n * framework-owned registrations; raw file/env config cannot provide it.\n */\n firstPartyOrgId?: string;\n /** Human-readable description (optional, shown in /mcp/status) */\n description?: string;\n}\n\nexport type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;\n\nexport interface McpConfig {\n /** Map of server id → config */\n servers: Record<string, McpServerConfig>;\n /** Where the config was loaded from (workspace root path, app path, or \"env\") */\n source?: string;\n}\n\nfunction isNode(): boolean {\n return (\n typeof process !== \"undefined\" &&\n !!(process as any).versions?.node &&\n typeof (process as any).versions.node === \"string\"\n );\n}\n\nfunction parseConfig(raw: string, source: string): McpConfig | null {\n try {\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") return null;\n const servers =\n parsed.servers && typeof parsed.servers === \"object\"\n ? (parsed.servers as Record<string, McpServerConfig>)\n : null;\n if (!servers) return null;\n const valid: Record<string, McpServerConfig> = {};\n for (const [id, cfg] of Object.entries(servers)) {\n if (!cfg || typeof cfg !== \"object\") continue;\n const c = cfg as any;\n const description =\n typeof c.description === \"string\" ? c.description : undefined;\n if (c.type === \"http\") {\n if (typeof c.url !== \"string\" || !c.url) continue;\n valid[id] = {\n type: \"http\",\n url: c.url,\n headers:\n c.headers && typeof c.headers === \"object\"\n ? Object.fromEntries(\n Object.entries(c.headers).map(([k, v]) => [k, String(v)]),\n )\n : undefined,\n description,\n };\n } else {\n if (typeof c.command !== \"string\" || !c.command) continue;\n valid[id] = {\n type: \"stdio\",\n command: c.command,\n args: Array.isArray(c.args) ? c.args.map(String) : undefined,\n env:\n c.env && typeof c.env === \"object\"\n ? Object.fromEntries(\n Object.entries(c.env).map(([k, v]) => [k, String(v)]),\n )\n : undefined,\n cwd: typeof c.cwd === \"string\" ? c.cwd : undefined,\n description,\n };\n }\n }\n if (Object.keys(valid).length === 0) return null;\n return { servers: valid, source };\n } catch {\n return null;\n }\n}\n\n/**\n * Load MCP configuration.\n *\n * @param startDir - Directory to start the upward search from (defaults to cwd)\n */\nexport function loadMcpConfig(startDir?: string): McpConfig | null {\n const envConfig = readEnvConfig();\n\n let fileConfig: McpConfig | null = null;\n if (isNode()) {\n try {\n fileConfig = readFileConfig(startDir);\n } catch {\n fileConfig = null;\n }\n }\n\n if (fileConfig) return fileConfig;\n return envConfig;\n}\n\nfunction readEnvConfig(): McpConfig | null {\n if (typeof process === \"undefined\") return null;\n const raw = process.env?.MCP_SERVERS;\n if (!raw || !raw.trim()) return null;\n const trimmed = raw.trim();\n // Try full shape first ({ servers: {...} })\n const full = parseConfig(trimmed, \"env:MCP_SERVERS\");\n if (full) return full;\n // Then try inner-map shape ({ <id>: {...} })\n return parseConfig(`{\"servers\":${trimmed}}`, \"env:MCP_SERVERS\");\n}\n\nfunction readFileConfig(startDir?: string): McpConfig | null {\n const cwd = startDir ?? process.cwd();\n\n const workspaceRoot = findWorkspaceRoot(cwd);\n if (workspaceRoot) {\n const wsConfigPath = path.join(workspaceRoot, \"mcp.config.json\");\n if (fs.existsSync(wsConfigPath)) {\n return parseConfig(fs.readFileSync(wsConfigPath, \"utf-8\"), wsConfigPath);\n }\n }\n\n const appConfigPath = path.join(cwd, \"mcp.config.json\");\n if (fs.existsSync(appConfigPath)) {\n return parseConfig(fs.readFileSync(appConfigPath, \"utf-8\"), appConfigPath);\n }\n\n return null;\n}\n\n/**\n * Auto-detect the claude-in-chrome MCP server if it's installed but no\n * config file exists. Gated by `AGENT_NATIVE_DISABLE_MCP_AUTODETECT`.\n *\n * Returns a synthesized config pointing at the detected binary, or `null`\n * when nothing is found or auto-detect is disabled.\n */\nexport function autoDetectMcpConfig(): McpConfig | null {\n if (!isNode()) return null;\n if (process.env.AGENT_NATIVE_DISABLE_MCP_AUTODETECT) return null;\n\n const candidates: string[] = [];\n\n const home = os.homedir();\n if (home) {\n candidates.push(\n path.join(home, \".claude-in-chrome\", \"bin\", \"claude-in-chrome-mcp\"),\n );\n }\n\n const pathEnv = process.env.PATH || \"\";\n const sep = process.platform === \"win32\" ? \";\" : \":\";\n const exeSuffix = process.platform === \"win32\" ? \".exe\" : \"\";\n for (const dir of pathEnv.split(sep)) {\n if (!dir) continue;\n candidates.push(path.join(dir, `claude-in-chrome-mcp${exeSuffix}`));\n }\n\n for (const candidate of candidates) {\n try {\n if (fs.existsSync(candidate)) {\n return {\n servers: {\n \"claude-in-chrome\": {\n type: \"stdio\",\n command: candidate,\n description:\n \"Auto-detected claude-in-chrome MCP server (Chrome automation)\",\n },\n },\n source: `autodetect:${candidate}`,\n };\n }\n } catch {\n // Keep trying other candidates\n }\n }\n\n return null;\n}\n"]}
@@ -6,7 +6,7 @@
6
6
  */
7
7
  export { loadMcpConfig, autoDetectMcpConfig, type McpConfig, type McpServerConfig, } from "./config.js";
8
8
  export { McpClientManager, buildMcpToolName, parseMcpToolName, MCP_TOOL_PREFIX, type McpTool, type McpClientManagerOptions, } from "./manager.js";
9
- export { listRemoteServers, addRemoteServer, removeRemoteServer, validateRemoteUrl, normalizeServerName, mergedConfigKey, parseMergedKey, hashEmail, toHttpServerConfig, toHttpServerConfigAsync, materializeHeaders, type RemoteMcpScope, type StoredRemoteMcpServer, } from "./remote-store.js";
9
+ export { listRemoteServers, addRemoteServer, addFirstPartyRemoteServer, isFirstPartyRemoteEndpointTrusted, removeRemoteServer, validateRemoteUrl, normalizeServerName, mergedConfigKey, parseMergedKey, hashEmail, toHttpServerConfig, toHttpServerConfigAsync, materializeHeaders, type RemoteMcpScope, type StoredRemoteMcpServer, } from "./remote-store.js";
10
10
  export { areBuiltinMcpCapabilitiesSupported, BUILTIN_MCP_CAPABILITIES, getBuiltinMcpCapability, isBuiltinMcpCapabilityAvailable, listSupportedBuiltinMcpCapabilities, normalizeBuiltinMcpCapabilityIds, toBuiltinMcpServerConfig, type BuiltinMcpCapability, type BuiltinMcpCapabilityId, } from "./builtin-capabilities.js";
11
11
  export { builtinMcpCapabilitiesSettingsKey, listEnabledBuiltinMcpCapabilities, setEnabledBuiltinMcpCapabilities, setBuiltinMcpCapabilityEnabled, type StoredBuiltinMcpCapabilities, } from "./builtin-store.js";
12
12
  export { mountMcpServersRoutes, buildMergedConfig, builtinMergedConfigKey, startMcpConfigRefresh, type ClientBuiltinCapability, } from "./routes.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mcp-client/index.ts"],"names":[],"mappings":"AAAA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M,iBAAiB,CAAC;AAezB;;;;GAIG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE9D,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,gBAAgB,GACxB,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAM7B;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,gBAAgB,EACzB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GAClC,IAAI,CAWN;AA8CD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAMxD;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,CAiB5D"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mcp-client/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,SAAS,EACd,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,KAAK,OAAO,EACZ,KAAK,uBAAuB,GAC7B,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,yBAAyB,EACzB,iCAAiC,EACjC,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,KAAK,cAAc,EACnB,KAAK,qBAAqB,GAC3B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,kCAAkC,EAClC,wBAAwB,EACxB,uBAAuB,EACvB,+BAA+B,EAC/B,mCAAmC,EACnC,gCAAgC,EAChC,wBAAwB,EACxB,KAAK,oBAAoB,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} from "./config.js";
8
8
  export { McpClientManager, buildMcpToolName, parseMcpToolName, MCP_TOOL_PREFIX, } from "./manager.js";
9
- export { listRemoteServers, addRemoteServer, removeRemoteServer, validateRemoteUrl, normalizeServerName, mergedConfigKey, parseMergedKey, hashEmail, toHttpServerConfig, toHttpServerConfigAsync, materializeHeaders, } from "./remote-store.js";
9
+ export { listRemoteServers, addRemoteServer, addFirstPartyRemoteServer, isFirstPartyRemoteEndpointTrusted, removeRemoteServer, validateRemoteUrl, normalizeServerName, mergedConfigKey, parseMergedKey, hashEmail, toHttpServerConfig, toHttpServerConfigAsync, materializeHeaders, } from "./remote-store.js";
10
10
  export { areBuiltinMcpCapabilitiesSupported, BUILTIN_MCP_CAPABILITIES, getBuiltinMcpCapability, isBuiltinMcpCapabilityAvailable, listSupportedBuiltinMcpCapabilities, normalizeBuiltinMcpCapabilityIds, toBuiltinMcpServerConfig, } from "./builtin-capabilities.js";
11
11
  export { builtinMcpCapabilitiesSettingsKey, listEnabledBuiltinMcpCapabilities, setEnabledBuiltinMcpCapabilities, setBuiltinMcpCapabilityEnabled, } from "./builtin-store.js";
12
12
  export { mountMcpServersRoutes, buildMergedConfig, builtinMergedConfigKey, startMcpConfigRefresh, } from "./routes.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/mcp-client/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,aAAa,EACb,mBAAmB,GAGpB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,GAGhB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,GAGnB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,kCAAkC,EA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G,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACjC,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,kBAAkB,CAC/B,OAAyB,EACzB,IAAa,EACb,WAAmB;IAEnB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACzE,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAE,MAAc,EAAE,QAAQ,CAAC;YACvD,CAAC,CAAG,MAAc,CAAC,QAAsB;YACzC,CAAC,CAAC,EAAE,CAAC;QACP,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,MAAM,QAAQ,GAAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;YACzD,IACE,QAAQ,EAAE,GAAG,KAAK,WAAW;gBAC7B,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,EACnC,CAAC;gBACD,OAAO,QAAQ,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,OAAO,CAAC,IAAI,CACV,gDAAgD,WAAW,KAAK,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CACtF,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["/**\n * MCP client module — symmetric counterpart to `@agent-native/core/mcp`\n * (the MCP server). Connects to local MCP servers configured in\n * `mcp.config.json` or the `MCP_SERVERS` env var and exposes their tools\n * to the agent-chat tool-use loop.\n */\n\nexport {\n loadMcpConfig,\n autoDetectMcpConfig,\n type McpConfig,\n type McpServerConfig,\n} from \"./config.js\";\n\nexport {\n McpClientManager,\n buildMcpToolName,\n parseMcpToolName,\n MCP_TOOL_PREFIX,\n type McpTool,\n type McpClientManagerOptions,\n} from \"./manager.js\";\n\nexport {\n listRemoteServers,\n addRemoteServer,\n removeRemoteServer,\n validateRemoteUrl,\n normalizeServerName,\n mergedConfigKey,\n parseMergedKey,\n hashEmail,\n toHttpServerConfig,\n toHttpServerConfigAsync,\n materializeHeaders,\n type RemoteMcpScope,\n type StoredRemoteMcpServer,\n} from \"./remote-store.js\";\n\nexport {\n areBuiltinMcpCapabilitiesSupported,\n BUILTIN_MCP_CAPABILITIES,\n getBuiltinMcpCapability,\n isBuiltinMcpCapabilityAvailable,\n listSupportedBuiltinMcpCapabilities,\n normalizeBuiltinMcpCapabilityIds,\n toBuiltinMcpServerConfig,\n type BuiltinMcpCapability,\n type BuiltinMcpCapabilityId,\n} from \"./builtin-capabilities.js\";\n\nexport {\n builtinMcpCapabilitiesSettingsKey,\n listEnabledBuiltinMcpCapabilities,\n setEnabledBuiltinMcpCapabilities,\n setBuiltinMcpCapabilityEnabled,\n type StoredBuiltinMcpCapabilities,\n} from \"./builtin-store.js\";\n\nexport {\n mountMcpServersRoutes,\n buildMergedConfig,\n builtinMergedConfigKey,\n startMcpConfigRefresh,\n type ClientBuiltinCapability,\n} from \"./routes.js\";\n\nexport {\n mountMcpHubRoutes,\n listHubServers,\n getHubStatus,\n isHubServeEnabled,\n isHubConsumeEnabled,\n type HubServerRecord,\n type HubServersResponse,\n} from \"./hub-routes.js\";\n\nexport { fetchHubServers } from \"./hub-client.js\";\n\nexport { isMcpToolAllowedForRequest } from \"./visibility.js\";\nimport { isMcpToolAllowedForRequest } from \"./visibility.js\";\nexport {\n MCP_ACTION_RESULT_MARKER,\n isMcpActionResult,\n type AgentMcpAppPayload,\n type AgentMcpAppResourceContent,\n type McpActionResult,\n} from \"./app-result.js\";\nimport {\n MCP_ACTION_RESULT_MARKER,\n toolForMcpAppPayload,\n type AgentMcpAppPayload,\n type AgentMcpAppResourceContent,\n type McpActionResult,\n} from \"./app-result.js\";\nimport {\n getToolUiResourceUri,\n isToolVisibilityAppOnly,\n isToolVisibilityModelOnly,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport { MCP_APP_MIME_TYPE } from \"../action.js\";\n\n/**\n * Convert MCP tools into `ActionEntry` values suitable for registration in\n * the agent's action registry. Each tool is marked `http: false` so it's\n * never auto-mounted as an HTTP endpoint — MCP tools are agent-only.\n */\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { McpClientManager, McpTool } from \"./manager.js\";\n\nexport function mcpToolsToActionEntries(\n manager: McpClientManager,\n): Record<string, ActionEntry> {\n const entries: Record<string, ActionEntry> = {};\n for (const tool of manager.getTools().filter(isVisibleToModel)) {\n entries[tool.name] = mcpToolToActionEntry(manager, tool);\n }\n return entries;\n}\n\n/**\n * Mutate a target action dict in place so it matches the current MCP tool set:\n * - adds new `mcp__*` keys that aren't in target,\n * - removes `mcp__*` keys that no longer exist in the manager,\n * - leaves non-MCP keys untouched.\n *\n * Used by the agent-chat plugin to keep its `prodActions` / `devActions`\n * registries in sync after `McpClientManager.reconfigure()` runs.\n */\nexport function syncMcpActionEntries(\n manager: McpClientManager,\n target: Record<string, ActionEntry>,\n): void {\n const current = new Set<string>();\n for (const tool of manager.getTools().filter(isVisibleToModel)) {\n current.add(tool.name);\n target[tool.name] = mcpToolToActionEntry(manager, tool);\n }\n for (const key of Object.keys(target)) {\n if (key.startsWith(\"mcp__\") && !current.has(key)) {\n delete target[key];\n }\n }\n}\n\nfunction mcpToolToActionEntry(\n manager: McpClientManager,\n tool: McpTool,\n): ActionEntry {\n return {\n tool: {\n description: tool.description,\n parameters: tool.inputSchema as any,\n },\n http: false,\n ...(tool.annotations?.readOnlyHint === true ? { readOnly: true } : {}),\n run: async (args: Record<string, string>) => {\n // Defense-in-depth: even if a cross-scope MCP tool somehow makes it\n // into the LLM's visible tool list, reject invocation here so we never\n // execute a user's credentials on behalf of another user.\n if (!isMcpToolAllowedForRequest(tool.name)) {\n return buildMcpErrorActionResult(\n tool,\n args,\n `Error: MCP tool ${tool.name} is not available in the current request scope.`,\n );\n }\n try {\n const result = await manager.callTool(tool.name, args);\n return await buildMcpActionResult(manager, tool, args, result);\n } catch (err: any) {\n return buildMcpErrorActionResult(\n tool,\n args,\n `Error calling MCP tool ${tool.name}: ${err?.message ?? err}`,\n );\n }\n },\n };\n}\n\nfunction isVisibleToModel(tool: McpTool): boolean {\n try {\n return !isToolVisibilityAppOnly(tool.raw as any);\n } catch {\n return true;\n }\n}\n\nexport function isVisibleToMcpApp(tool: McpTool): boolean {\n try {\n return !isToolVisibilityModelOnly(tool.raw as any);\n } catch {\n return true;\n }\n}\n\nexport function flattenMcpToolResult(result: unknown): string {\n if (\n result &&\n typeof result === \"object\" &&\n Array.isArray((result as any).content)\n ) {\n const parts = (result as any).content as Array<Record<string, any>>;\n const text = parts.map(formatMcpContentPart).join(\"\\n\");\n const fallback =\n text ||\n (hasStructuredContent(result)\n ? JSON.stringify((result as any).structuredContent, null, 2)\n : \"(no output)\");\n if ((result as any).isError) return `Error: ${fallback}`;\n return fallback;\n }\n return typeof result === \"string\" ? result : JSON.stringify(result);\n}\n\nfunction formatMcpContentPart(part: Record<string, any>): string {\n if (part?.type === \"text\" && typeof part.text === \"string\") {\n return part.text;\n }\n if (part?.type === \"image\") {\n return `[image: ${part?.mimeType ?? \"unknown\"}]`;\n }\n if (part?.type === \"resource\") {\n const resource = part.resource ?? {};\n const uri = typeof resource.uri === \"string\" ? ` ${resource.uri}` : \"\";\n return `[resource: ${resource.mimeType ?? \"unknown\"}${uri}]`;\n }\n if (part?.type === \"resource_link\") {\n const uri = typeof part.uri === \"string\" ? ` ${part.uri}` : \"\";\n return `[resource: ${part.mimeType ?? \"unknown\"}${uri}]`;\n }\n return JSON.stringify(part);\n}\n\nfunction hasStructuredContent(result: unknown): boolean {\n return (\n !!result &&\n typeof result === \"object\" &&\n Object.prototype.hasOwnProperty.call(result, \"structuredContent\")\n );\n}\n\nasync function buildMcpActionResult(\n manager: McpClientManager,\n tool: McpTool,\n input: Record<string, unknown>,\n raw: unknown,\n): Promise<McpActionResult> {\n const text = flattenMcpToolResult(raw);\n const mcpApp = await extractMcpAppPayload(manager, tool, input, raw);\n return {\n [MCP_ACTION_RESULT_MARKER]: true,\n text,\n raw,\n serverId: tool.source,\n toolName: tool.name,\n originalToolName: tool.originalName,\n input,\n ...(mcpApp ? { mcpApp } : {}),\n };\n}\n\nfunction buildMcpErrorActionResult(\n tool: McpTool,\n input: Record<string, unknown>,\n text: string,\n): McpActionResult {\n return {\n [MCP_ACTION_RESULT_MARKER]: true,\n text,\n raw: {\n isError: true,\n content: [{ type: \"text\", text }],\n },\n serverId: tool.source,\n toolName: tool.name,\n originalToolName: tool.originalName,\n input,\n };\n}\n\nasync function extractMcpAppPayload(\n manager: McpClientManager,\n tool: McpTool,\n input: Record<string, unknown>,\n raw: unknown,\n): Promise<AgentMcpAppPayload | undefined> {\n const inlineResource = findInlineMcpAppResource(raw);\n const resourceUri =\n inlineResource?.uri ??\n resourceUriFromTool(tool) ??\n resourceUriFromResult(raw);\n if (!resourceUri) return undefined;\n\n const resource =\n inlineResource ?? (await readMcpAppResource(manager, tool, resourceUri));\n\n return {\n serverId: tool.source,\n toolName: tool.name,\n originalToolName: tool.originalName,\n resourceUri,\n toolInput: input,\n toolResult:\n raw && typeof raw === \"object\"\n ? ({ ...(raw as Record<string, unknown>) } as Record<string, unknown>)\n : { content: [{ type: \"text\", text: String(raw ?? \"\") }] },\n tool: toolForMcpAppPayload(tool),\n ...(resource ? { resource } : {}),\n };\n}\n\nfunction resourceUriFromTool(tool: McpTool): string | undefined {\n try {\n return getToolUiResourceUri(tool.raw as any);\n } catch {\n return undefined;\n }\n}\n\nfunction resourceUriFromResult(raw: unknown): string | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const meta = (raw as any)._meta;\n const nested = meta?.ui?.resourceUri;\n if (typeof nested === \"string\" && nested.startsWith(\"ui://\")) return nested;\n const flat = meta?.[\"ui/resourceUri\"] ?? meta?.[\"ui.resourceUri\"];\n if (typeof flat === \"string\" && flat.startsWith(\"ui://\")) return flat;\n return findInlineMcpAppResource(raw)?.uri;\n}\n\nfunction findInlineMcpAppResource(\n raw: unknown,\n): AgentMcpAppResourceContent | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const content = Array.isArray((raw as any).content)\n ? ((raw as any).content as unknown[])\n : [];\n for (const part of content) {\n const resource = normalizeMcpAppResourceContent(part);\n if (resource) return resource;\n }\n return undefined;\n}\n\nfunction normalizeMcpAppResourceContent(\n part: unknown,\n): AgentMcpAppResourceContent | undefined {\n if (!part || typeof part !== \"object\") return undefined;\n const candidate =\n (part as any).type === \"resource\"\n ? (part as any).resource\n : ((part as any).resource ?? part);\n if (!candidate || typeof candidate !== \"object\") return undefined;\n const uri = (candidate as any).uri;\n if (typeof uri !== \"string\" || !uri.startsWith(\"ui://\")) return undefined;\n const mimeType =\n typeof (candidate as any).mimeType === \"string\"\n ? (candidate as any).mimeType\n : undefined;\n if (mimeType && !mimeType.includes(MCP_APP_MIME_TYPE)) return undefined;\n const text =\n typeof (candidate as any).text === \"string\"\n ? (candidate as any).text\n : undefined;\n const blob =\n typeof (candidate as any).blob === \"string\"\n ? (candidate as any).blob\n : undefined;\n const meta =\n (candidate as any)._meta && typeof (candidate as any)._meta === \"object\"\n ? ((candidate as any)._meta as Record<string, unknown>)\n : (part as any)._meta && typeof (part as any)._meta === \"object\"\n ? ((part as any)._meta as Record<string, unknown>)\n : undefined;\n return {\n uri,\n ...(mimeType ? { mimeType } : {}),\n ...(text ? { text } : {}),\n ...(blob ? { blob } : {}),\n ...(meta ? { _meta: meta } : {}),\n };\n}\n\nasync function readMcpAppResource(\n manager: McpClientManager,\n tool: McpTool,\n resourceUri: string,\n): Promise<AgentMcpAppResourceContent | undefined> {\n try {\n const result = await manager.readResourceForTool(tool.name, resourceUri);\n const contents = Array.isArray((result as any)?.contents)\n ? ((result as any).contents as unknown[])\n : [];\n for (const content of contents) {\n const resource = normalizeMcpAppResourceContent(content);\n if (\n resource?.uri === resourceUri ||\n (resource && contents.length === 1)\n ) {\n return resource;\n }\n }\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to read MCP App resource ${resourceUri}: ${err?.message ?? err}`,\n );\n }\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/mcp-client/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,aAAa,EACb,mBAAmB,GAGpB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,GAGhB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,yBAAyB,EACzB,iCAAiC,EACjC,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,GAGnB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,kCAAkC,EAClC,wBAAwB,EACxB,uBAAuB,EACvB,+BAA+B,EAC/B,mCAAmC,EACnC,gCAAgC,EAChC,wBAAwB,GAGzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EACL,iCAAiC,EACjC,iCAAiC,EACjC,gCAAgC,EAChC,8BAA8B,GAE/B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,GAEtB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,GAGpB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EACL,wBAAwB,EACxB,iBAAiB,GAIlB,MAAM,iBAAiB,CAAC;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AK,CAAC,CAAC,EACnC,CAAC;gBACD,OAAO,QAAQ,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,OAAO,CAAC,IAAI,CACV,gDAAgD,WAAW,KAAK,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CACtF,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["/**\n * MCP client module — symmetric counterpart to `@agent-native/core/mcp`\n * (the MCP server). Connects to local MCP servers configured in\n * `mcp.config.json` or the `MCP_SERVERS` env var and exposes their tools\n * to the agent-chat tool-use loop.\n */\n\nexport {\n loadMcpConfig,\n autoDetectMcpConfig,\n type McpConfig,\n type McpServerConfig,\n} from \"./config.js\";\n\nexport {\n McpClientManager,\n buildMcpToolName,\n parseMcpToolName,\n MCP_TOOL_PREFIX,\n type McpTool,\n type McpClientManagerOptions,\n} from \"./manager.js\";\n\nexport {\n listRemoteServers,\n addRemoteServer,\n addFirstPartyRemoteServer,\n isFirstPartyRemoteEndpointTrusted,\n removeRemoteServer,\n validateRemoteUrl,\n normalizeServerName,\n mergedConfigKey,\n parseMergedKey,\n hashEmail,\n toHttpServerConfig,\n toHttpServerConfigAsync,\n materializeHeaders,\n type RemoteMcpScope,\n type StoredRemoteMcpServer,\n} from \"./remote-store.js\";\n\nexport {\n areBuiltinMcpCapabilitiesSupported,\n BUILTIN_MCP_CAPABILITIES,\n getBuiltinMcpCapability,\n isBuiltinMcpCapabilityAvailable,\n listSupportedBuiltinMcpCapabilities,\n normalizeBuiltinMcpCapabilityIds,\n toBuiltinMcpServerConfig,\n type BuiltinMcpCapability,\n type BuiltinMcpCapabilityId,\n} from \"./builtin-capabilities.js\";\n\nexport {\n builtinMcpCapabilitiesSettingsKey,\n listEnabledBuiltinMcpCapabilities,\n setEnabledBuiltinMcpCapabilities,\n setBuiltinMcpCapabilityEnabled,\n type StoredBuiltinMcpCapabilities,\n} from \"./builtin-store.js\";\n\nexport {\n mountMcpServersRoutes,\n buildMergedConfig,\n builtinMergedConfigKey,\n startMcpConfigRefresh,\n type ClientBuiltinCapability,\n} from \"./routes.js\";\n\nexport {\n mountMcpHubRoutes,\n listHubServers,\n getHubStatus,\n isHubServeEnabled,\n isHubConsumeEnabled,\n type HubServerRecord,\n type HubServersResponse,\n} from \"./hub-routes.js\";\n\nexport { fetchHubServers } from \"./hub-client.js\";\n\nexport { isMcpToolAllowedForRequest } from \"./visibility.js\";\nimport { isMcpToolAllowedForRequest } from \"./visibility.js\";\nexport {\n MCP_ACTION_RESULT_MARKER,\n isMcpActionResult,\n type AgentMcpAppPayload,\n type AgentMcpAppResourceContent,\n type McpActionResult,\n} from \"./app-result.js\";\nimport {\n MCP_ACTION_RESULT_MARKER,\n toolForMcpAppPayload,\n type AgentMcpAppPayload,\n type AgentMcpAppResourceContent,\n type McpActionResult,\n} from \"./app-result.js\";\nimport {\n getToolUiResourceUri,\n isToolVisibilityAppOnly,\n isToolVisibilityModelOnly,\n} from \"@modelcontextprotocol/ext-apps/app-bridge\";\nimport { MCP_APP_MIME_TYPE } from \"../action.js\";\n\n/**\n * Convert MCP tools into `ActionEntry` values suitable for registration in\n * the agent's action registry. Each tool is marked `http: false` so it's\n * never auto-mounted as an HTTP endpoint — MCP tools are agent-only.\n */\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { McpClientManager, McpTool } from \"./manager.js\";\n\nexport function mcpToolsToActionEntries(\n manager: McpClientManager,\n): Record<string, ActionEntry> {\n const entries: Record<string, ActionEntry> = {};\n for (const tool of manager.getTools().filter(isVisibleToModel)) {\n entries[tool.name] = mcpToolToActionEntry(manager, tool);\n }\n return entries;\n}\n\n/**\n * Mutate a target action dict in place so it matches the current MCP tool set:\n * - adds new `mcp__*` keys that aren't in target,\n * - removes `mcp__*` keys that no longer exist in the manager,\n * - leaves non-MCP keys untouched.\n *\n * Used by the agent-chat plugin to keep its `prodActions` / `devActions`\n * registries in sync after `McpClientManager.reconfigure()` runs.\n */\nexport function syncMcpActionEntries(\n manager: McpClientManager,\n target: Record<string, ActionEntry>,\n): void {\n const current = new Set<string>();\n for (const tool of manager.getTools().filter(isVisibleToModel)) {\n current.add(tool.name);\n target[tool.name] = mcpToolToActionEntry(manager, tool);\n }\n for (const key of Object.keys(target)) {\n if (key.startsWith(\"mcp__\") && !current.has(key)) {\n delete target[key];\n }\n }\n}\n\nfunction mcpToolToActionEntry(\n manager: McpClientManager,\n tool: McpTool,\n): ActionEntry {\n return {\n tool: {\n description: tool.description,\n parameters: tool.inputSchema as any,\n },\n http: false,\n ...(tool.annotations?.readOnlyHint === true ? { readOnly: true } : {}),\n run: async (args: Record<string, string>) => {\n // Defense-in-depth: even if a cross-scope MCP tool somehow makes it\n // into the LLM's visible tool list, reject invocation here so we never\n // execute a user's credentials on behalf of another user.\n if (!isMcpToolAllowedForRequest(tool.name)) {\n return buildMcpErrorActionResult(\n tool,\n args,\n `Error: MCP tool ${tool.name} is not available in the current request scope.`,\n );\n }\n try {\n const result = await manager.callTool(tool.name, args);\n return await buildMcpActionResult(manager, tool, args, result);\n } catch (err: any) {\n return buildMcpErrorActionResult(\n tool,\n args,\n `Error calling MCP tool ${tool.name}: ${err?.message ?? err}`,\n );\n }\n },\n };\n}\n\nfunction isVisibleToModel(tool: McpTool): boolean {\n try {\n return !isToolVisibilityAppOnly(tool.raw as any);\n } catch {\n return true;\n }\n}\n\nexport function isVisibleToMcpApp(tool: McpTool): boolean {\n try {\n return !isToolVisibilityModelOnly(tool.raw as any);\n } catch {\n return true;\n }\n}\n\nexport function flattenMcpToolResult(result: unknown): string {\n if (\n result &&\n typeof result === \"object\" &&\n Array.isArray((result as any).content)\n ) {\n const parts = (result as any).content as Array<Record<string, any>>;\n const text = parts.map(formatMcpContentPart).join(\"\\n\");\n const fallback =\n text ||\n (hasStructuredContent(result)\n ? JSON.stringify((result as any).structuredContent, null, 2)\n : \"(no output)\");\n if ((result as any).isError) return `Error: ${fallback}`;\n return fallback;\n }\n return typeof result === \"string\" ? result : JSON.stringify(result);\n}\n\nfunction formatMcpContentPart(part: Record<string, any>): string {\n if (part?.type === \"text\" && typeof part.text === \"string\") {\n return part.text;\n }\n if (part?.type === \"image\") {\n return `[image: ${part?.mimeType ?? \"unknown\"}]`;\n }\n if (part?.type === \"resource\") {\n const resource = part.resource ?? {};\n const uri = typeof resource.uri === \"string\" ? ` ${resource.uri}` : \"\";\n return `[resource: ${resource.mimeType ?? \"unknown\"}${uri}]`;\n }\n if (part?.type === \"resource_link\") {\n const uri = typeof part.uri === \"string\" ? ` ${part.uri}` : \"\";\n return `[resource: ${part.mimeType ?? \"unknown\"}${uri}]`;\n }\n return JSON.stringify(part);\n}\n\nfunction hasStructuredContent(result: unknown): boolean {\n return (\n !!result &&\n typeof result === \"object\" &&\n Object.prototype.hasOwnProperty.call(result, \"structuredContent\")\n );\n}\n\nasync function buildMcpActionResult(\n manager: McpClientManager,\n tool: McpTool,\n input: Record<string, unknown>,\n raw: unknown,\n): Promise<McpActionResult> {\n const text = flattenMcpToolResult(raw);\n const mcpApp = await extractMcpAppPayload(manager, tool, input, raw);\n return {\n [MCP_ACTION_RESULT_MARKER]: true,\n text,\n raw,\n serverId: tool.source,\n toolName: tool.name,\n originalToolName: tool.originalName,\n input,\n ...(mcpApp ? { mcpApp } : {}),\n };\n}\n\nfunction buildMcpErrorActionResult(\n tool: McpTool,\n input: Record<string, unknown>,\n text: string,\n): McpActionResult {\n return {\n [MCP_ACTION_RESULT_MARKER]: true,\n text,\n raw: {\n isError: true,\n content: [{ type: \"text\", text }],\n },\n serverId: tool.source,\n toolName: tool.name,\n originalToolName: tool.originalName,\n input,\n };\n}\n\nasync function extractMcpAppPayload(\n manager: McpClientManager,\n tool: McpTool,\n input: Record<string, unknown>,\n raw: unknown,\n): Promise<AgentMcpAppPayload | undefined> {\n const inlineResource = findInlineMcpAppResource(raw);\n const resourceUri =\n inlineResource?.uri ??\n resourceUriFromTool(tool) ??\n resourceUriFromResult(raw);\n if (!resourceUri) return undefined;\n\n const resource =\n inlineResource ?? (await readMcpAppResource(manager, tool, resourceUri));\n\n return {\n serverId: tool.source,\n toolName: tool.name,\n originalToolName: tool.originalName,\n resourceUri,\n toolInput: input,\n toolResult:\n raw && typeof raw === \"object\"\n ? ({ ...(raw as Record<string, unknown>) } as Record<string, unknown>)\n : { content: [{ type: \"text\", text: String(raw ?? \"\") }] },\n tool: toolForMcpAppPayload(tool),\n ...(resource ? { resource } : {}),\n };\n}\n\nfunction resourceUriFromTool(tool: McpTool): string | undefined {\n try {\n return getToolUiResourceUri(tool.raw as any);\n } catch {\n return undefined;\n }\n}\n\nfunction resourceUriFromResult(raw: unknown): string | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const meta = (raw as any)._meta;\n const nested = meta?.ui?.resourceUri;\n if (typeof nested === \"string\" && nested.startsWith(\"ui://\")) return nested;\n const flat = meta?.[\"ui/resourceUri\"] ?? meta?.[\"ui.resourceUri\"];\n if (typeof flat === \"string\" && flat.startsWith(\"ui://\")) return flat;\n return findInlineMcpAppResource(raw)?.uri;\n}\n\nfunction findInlineMcpAppResource(\n raw: unknown,\n): AgentMcpAppResourceContent | undefined {\n if (!raw || typeof raw !== \"object\") return undefined;\n const content = Array.isArray((raw as any).content)\n ? ((raw as any).content as unknown[])\n : [];\n for (const part of content) {\n const resource = normalizeMcpAppResourceContent(part);\n if (resource) return resource;\n }\n return undefined;\n}\n\nfunction normalizeMcpAppResourceContent(\n part: unknown,\n): AgentMcpAppResourceContent | undefined {\n if (!part || typeof part !== \"object\") return undefined;\n const candidate =\n (part as any).type === \"resource\"\n ? (part as any).resource\n : ((part as any).resource ?? part);\n if (!candidate || typeof candidate !== \"object\") return undefined;\n const uri = (candidate as any).uri;\n if (typeof uri !== \"string\" || !uri.startsWith(\"ui://\")) return undefined;\n const mimeType =\n typeof (candidate as any).mimeType === \"string\"\n ? (candidate as any).mimeType\n : undefined;\n if (mimeType && !mimeType.includes(MCP_APP_MIME_TYPE)) return undefined;\n const text =\n typeof (candidate as any).text === \"string\"\n ? (candidate as any).text\n : undefined;\n const blob =\n typeof (candidate as any).blob === \"string\"\n ? (candidate as any).blob\n : undefined;\n const meta =\n (candidate as any)._meta && typeof (candidate as any)._meta === \"object\"\n ? ((candidate as any)._meta as Record<string, unknown>)\n : (part as any)._meta && typeof (part as any)._meta === \"object\"\n ? ((part as any)._meta as Record<string, unknown>)\n : undefined;\n return {\n uri,\n ...(mimeType ? { mimeType } : {}),\n ...(text ? { text } : {}),\n ...(blob ? { blob } : {}),\n ...(meta ? { _meta: meta } : {}),\n };\n}\n\nasync function readMcpAppResource(\n manager: McpClientManager,\n tool: McpTool,\n resourceUri: string,\n): Promise<AgentMcpAppResourceContent | undefined> {\n try {\n const result = await manager.readResourceForTool(tool.name, resourceUri);\n const contents = Array.isArray((result as any)?.contents)\n ? ((result as any).contents as unknown[])\n : [];\n for (const content of contents) {\n const resource = normalizeMcpAppResourceContent(content);\n if (\n resource?.uri === resourceUri ||\n (resource && contents.length === 1)\n ) {\n return resource;\n }\n }\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to read MCP App resource ${resourceUri}: ${err?.message ?? err}`,\n );\n }\n return undefined;\n}\n"]}
@@ -137,5 +137,7 @@ export declare class McpClientManager {
137
137
  }>;
138
138
  errors: Record<string, string>;
139
139
  };
140
+ private shouldInjectFirstPartyIdentity;
141
+ private firstPartyTrust;
140
142
  }
141
143
  //# sourceMappingURL=manager.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/mcp-client/manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,aAAa,CAAC;AAI9D,eAAO,MAAM,eAAe,UAAU,CAAC;AAEvC,MAAM,WAAW,OAAO;IACtB,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC;IACf,kEAAkE;IAClE,IAAI,EAAE,MAAM,CAAC;IACb,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