@agent-native/core 0.98.16 → 0.99.0
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.
- package/corpus/README.md +2 -2
- package/corpus/core/CHANGELOG.md +21 -0
- package/corpus/core/docs/content/actions.mdx +1 -1
- package/corpus/core/docs/content/authentication.mdx +1 -1
- package/corpus/core/docs/content/dispatch.mdx +3 -3
- package/corpus/core/docs/content/external-agents.mdx +30 -19
- package/corpus/core/docs/content/locales/ar-SA/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/ar-SA/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/ar-SA/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/ar-SA/external-agents.mdx +23 -19
- package/corpus/core/docs/content/locales/ar-SA/mcp-clients.mdx +31 -3
- package/corpus/core/docs/content/locales/ar-SA/mcp-protocol.mdx +29 -15
- package/corpus/core/docs/content/locales/ar-SA/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/ar-SA/server.mdx +2 -2
- package/corpus/core/docs/content/locales/ar-SA/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/ar-SA/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/ar-SA/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/ar-SA/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/de-DE/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/de-DE/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/de-DE/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/de-DE/external-agents.mdx +23 -19
- package/corpus/core/docs/content/locales/de-DE/mcp-clients.mdx +37 -3
- package/corpus/core/docs/content/locales/de-DE/mcp-protocol.mdx +29 -15
- package/corpus/core/docs/content/locales/de-DE/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/de-DE/server.mdx +2 -2
- package/corpus/core/docs/content/locales/de-DE/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/de-DE/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/de-DE/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/de-DE/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/es-ES/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/es-ES/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/es-ES/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/es-ES/external-agents.mdx +32 -19
- package/corpus/core/docs/content/locales/es-ES/mcp-clients.mdx +17 -3
- package/corpus/core/docs/content/locales/es-ES/mcp-protocol.mdx +38 -15
- package/corpus/core/docs/content/locales/es-ES/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/es-ES/server.mdx +2 -2
- package/corpus/core/docs/content/locales/es-ES/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/es-ES/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/es-ES/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/es-ES/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/fr-FR/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/fr-FR/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/fr-FR/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/fr-FR/external-agents.mdx +23 -19
- package/corpus/core/docs/content/locales/fr-FR/mcp-clients.mdx +17 -3
- package/corpus/core/docs/content/locales/fr-FR/mcp-protocol.mdx +29 -15
- package/corpus/core/docs/content/locales/fr-FR/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/fr-FR/server.mdx +2 -2
- package/corpus/core/docs/content/locales/fr-FR/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/fr-FR/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/fr-FR/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/fr-FR/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/hi-IN/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/hi-IN/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/hi-IN/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/hi-IN/external-agents.mdx +31 -19
- package/corpus/core/docs/content/locales/hi-IN/mcp-clients.mdx +17 -3
- package/corpus/core/docs/content/locales/hi-IN/mcp-protocol.mdx +36 -15
- package/corpus/core/docs/content/locales/hi-IN/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/hi-IN/server.mdx +2 -2
- package/corpus/core/docs/content/locales/hi-IN/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/hi-IN/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/hi-IN/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/hi-IN/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/ja-JP/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/ja-JP/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/ja-JP/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/ja-JP/external-agents.mdx +23 -19
- package/corpus/core/docs/content/locales/ja-JP/mcp-clients.mdx +34 -3
- package/corpus/core/docs/content/locales/ja-JP/mcp-protocol.mdx +29 -15
- package/corpus/core/docs/content/locales/ja-JP/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/ja-JP/server.mdx +2 -2
- package/corpus/core/docs/content/locales/ja-JP/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/ja-JP/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/ja-JP/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/ja-JP/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/ko-KR/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/ko-KR/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/ko-KR/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/ko-KR/external-agents.mdx +30 -19
- package/corpus/core/docs/content/locales/ko-KR/mcp-clients.mdx +33 -3
- package/corpus/core/docs/content/locales/ko-KR/mcp-protocol.mdx +36 -15
- package/corpus/core/docs/content/locales/ko-KR/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/ko-KR/server.mdx +2 -2
- package/corpus/core/docs/content/locales/ko-KR/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/ko-KR/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/ko-KR/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/ko-KR/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/pt-BR/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/pt-BR/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/pt-BR/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/pt-BR/external-agents.mdx +32 -19
- package/corpus/core/docs/content/locales/pt-BR/mcp-clients.mdx +34 -3
- package/corpus/core/docs/content/locales/pt-BR/mcp-protocol.mdx +32 -15
- package/corpus/core/docs/content/locales/pt-BR/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/pt-BR/server.mdx +2 -2
- package/corpus/core/docs/content/locales/pt-BR/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/pt-BR/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/pt-BR/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/pt-BR/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/zh-CN/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-CN/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-CN/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/zh-CN/external-agents.mdx +23 -19
- package/corpus/core/docs/content/locales/zh-CN/mcp-clients.mdx +28 -3
- package/corpus/core/docs/content/locales/zh-CN/mcp-protocol.mdx +29 -15
- package/corpus/core/docs/content/locales/zh-CN/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/zh-CN/server.mdx +2 -2
- package/corpus/core/docs/content/locales/zh-CN/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-CN/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-CN/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/zh-CN/template-plan.mdx +3 -3
- package/corpus/core/docs/content/locales/zh-TW/actions.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-TW/authentication.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-TW/dispatch.mdx +3 -3
- package/corpus/core/docs/content/locales/zh-TW/external-agents.mdx +23 -19
- package/corpus/core/docs/content/locales/zh-TW/mcp-clients.mdx +28 -3
- package/corpus/core/docs/content/locales/zh-TW/mcp-protocol.mdx +30 -15
- package/corpus/core/docs/content/locales/zh-TW/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/locales/zh-TW/server.mdx +2 -2
- package/corpus/core/docs/content/locales/zh-TW/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-TW/template-assets.mdx +1 -1
- package/corpus/core/docs/content/locales/zh-TW/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/locales/zh-TW/template-plan.mdx +3 -3
- package/corpus/core/docs/content/mcp-clients.mdx +31 -4
- package/corpus/core/docs/content/mcp-protocol.mdx +35 -15
- package/corpus/core/docs/content/plan-plugin.mdx +3 -3
- package/corpus/core/docs/content/server.mdx +2 -2
- package/corpus/core/docs/content/skills-guide.mdx +1 -1
- package/corpus/core/docs/content/template-assets.mdx +1 -1
- package/corpus/core/docs/content/template-dispatch.mdx +2 -2
- package/corpus/core/docs/content/template-plan.mdx +3 -3
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/a2a/client.ts +3 -0
- package/corpus/core/src/a2a/handlers.ts +95 -7
- package/corpus/core/src/cli/connect.ts +50 -24
- package/corpus/core/src/cli/mcp-config-writers.ts +10 -0
- package/corpus/core/src/cli/mcp.ts +5 -5
- package/corpus/core/src/cli/skills-content/assets-skill.ts +1 -1
- package/corpus/core/src/cli/skills-content/design-exploration-skill.ts +1 -1
- package/corpus/core/src/cli/skills-content/help.ts +1 -1
- package/corpus/core/src/cli/skills-content/plan-setup-auth.ts +1 -1
- package/corpus/core/src/cli/skills-content/visual-plan-skill.ts +1 -1
- package/corpus/core/src/cli/skills-content/visual-recap-skill.ts +2 -2
- package/corpus/core/src/cli/skills.ts +23 -12
- package/corpus/core/src/client/resources/McpIntegrationDialog.tsx +5 -0
- package/corpus/core/src/client/resources/mcp-integration-catalog.ts +17 -0
- package/corpus/core/src/embedding/agent.ts +8 -6
- package/corpus/core/src/localization/default-messages.ts +7 -0
- package/corpus/core/src/mcp/ask-app-inline-tasks.ts +125 -0
- package/corpus/core/src/mcp/build-server.ts +65 -3
- package/corpus/core/src/mcp/builtin-tools.ts +186 -22
- package/corpus/core/src/mcp/connect-route.ts +17 -14
- package/corpus/core/src/mcp/oauth-route.ts +38 -13
- package/corpus/core/src/mcp/route-paths.ts +34 -0
- package/corpus/core/src/mcp/server.ts +21 -10
- package/corpus/core/src/mcp/stdio.ts +34 -16
- package/corpus/core/src/mcp/workspace-resolve.ts +2 -1
- package/corpus/core/src/mcp-client/manager.ts +5 -3
- package/corpus/core/src/mcp-client/remote-store.ts +10 -10
- package/corpus/core/src/server/agent-chat-plugin.ts +59 -8
- package/corpus/core/src/server/auth.ts +22 -6
- package/corpus/core/src/server/core-routes-plugin.ts +30 -24
- package/corpus/core/src/server/csrf.ts +17 -0
- package/corpus/core/src/server/framework-request-handler.ts +8 -2
- package/corpus/core/src/server/google-oauth.ts +6 -0
- package/corpus/core/src/server/http-response-telemetry.ts +6 -1
- package/corpus/core/src/server/recap-image-route.ts +3 -3
- package/corpus/core/src/server/security-headers.ts +7 -1
- package/corpus/core/src/server/ssr-handler.ts +2 -0
- package/corpus/core/src/shared/cache-control.ts +6 -4
- package/corpus/core/src/templates/default/.agents/skills/security/SKILL.md +10 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +15 -6
- package/corpus/core/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +16 -10
- package/corpus/core/src/templates/workspace-core/.agents/skills/performance/SKILL.md +20 -1
- package/corpus/core/src/templates/workspace-core/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/analytics/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/analytics/app/global.css +63 -4
- package/corpus/templates/analytics/app/pages/sessions/SessionDetailPage.tsx +8 -5
- package/corpus/templates/analytics/changelog/2026-07-13-daily-dashboard-emails-recover-more-reliably-from-serverless.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-13-session-replays-keep-a-visible-mac-style-cursor-over-the-vis.md +6 -0
- package/corpus/templates/analytics/server/jobs/dashboard-report.ts +21 -2
- package/corpus/templates/analytics/server/lib/dashboard-report-subscriptions.ts +57 -1
- package/corpus/templates/analytics/server/lib/dashboard-report.ts +266 -28
- package/corpus/templates/analytics/server/routes/[...page].get.ts +0 -2
- package/corpus/templates/assets/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/assets/agent-native.app-skill.json +1 -1
- package/corpus/templates/brain/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/calendar/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/calendar/AGENTS.md +2 -1
- package/corpus/templates/calendar/app/components/calendar/EventDetailPopover.tsx +0 -19
- package/corpus/templates/calendar/app/lib/attendee-local-time.ts +14 -5
- package/corpus/templates/calendar/changelog/2026-07-13-your-local-time-now-follows-your-browser-timezone-and-event-.md +6 -0
- package/corpus/templates/chat/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/clips/.agents/skills/recording/SKILL.md +7 -2
- package/corpus/templates/clips/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/clips/AGENTS.md +7 -0
- package/corpus/templates/clips/actions/list-meetings.ts +19 -4
- package/corpus/templates/clips/actions/start-meeting-recording.ts +7 -1
- package/corpus/templates/clips/app/components/meetings/transcript-bubbles.tsx +75 -78
- package/corpus/templates/clips/app/components/recorder/confetti-canvas.tsx +18 -1
- package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +6 -12
- package/corpus/templates/clips/app/components/recorder/recording-toolbar.tsx +19 -2
- package/corpus/templates/clips/app/lib/camera-composite.ts +70 -10
- package/corpus/templates/clips/app/routes/_app.meetings.$meetingId.tsx +1 -1
- package/corpus/templates/clips/app/routes/record.tsx +5 -25
- package/corpus/templates/clips/changelog/2026-07-13-clips-desktop-now-requires-macos-13-for-native-capture.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-13-clips-hide-solo-meeting-reminders.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-13-clips-now-removes-duplicate-mic-and-system-transcript-turns-.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-13-desktop-recordings-run-cooler-and-quieter-live-transcription.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-13-meeting-recordings-now-stop-after-a-calendar-meeting-ends-an.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-13-meeting-transcripts-now-use-a-clean-agent-chat-style-reading.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-13-screen-recordings-use-less-processing-power-during-longer-ca.md +6 -0
- package/corpus/templates/clips/chrome-extension/src/background.ts +5 -3
- package/corpus/templates/clips/chrome-extension/src/offscreen.ts +17 -14
- package/corpus/templates/clips/chrome-extension/src/overlay.ts +8 -2
- package/corpus/templates/clips/desktop/README.md +3 -0
- package/corpus/templates/clips/desktop/src/hooks/useMeetingTranscription.ts +9 -0
- package/corpus/templates/clips/desktop/src/lib/recorder.ts +8 -2
- package/corpus/templates/clips/desktop/src/lib/silence-events.ts +1 -0
- package/corpus/templates/clips/desktop/src/lib/transcription-capture.ts +5 -0
- package/corpus/templates/clips/desktop/src/lib/transcription-engine.ts +134 -5
- package/corpus/templates/clips/desktop/src/lib/upload-video-stream.ts +28 -0
- package/corpus/templates/clips/desktop/src/overlays/flow-bar.tsx +10 -3
- package/corpus/templates/clips/desktop/src/overlays/meeting-notification.tsx +42 -9
- package/corpus/templates/clips/desktop/src/overlays/recording-pill.tsx +10 -2
- package/corpus/templates/clips/desktop/src-tauri/Cargo.toml +6 -1
- package/corpus/templates/clips/desktop/src-tauri/src/notifications.rs +77 -1
- package/corpus/templates/clips/desktop/src-tauri/src/silence_detector.rs +104 -25
- package/corpus/templates/clips/desktop/src-tauri/src/system_audio.rs +4 -0
- package/corpus/templates/clips/desktop/src-tauri/src/whisper_speech.rs +287 -32
- package/corpus/templates/clips/desktop/src-tauri/tauri.conf.json +1 -1
- package/corpus/templates/clips/server/lib/calendar-event-classification.ts +28 -0
- package/corpus/templates/clips/server/routes/[...page].get.ts +1 -59
- package/corpus/templates/clips/shared/recording-capture.ts +37 -0
- package/corpus/templates/content/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/content/agent-native.app-skill.json +1 -1
- package/corpus/templates/content/server/routes/[...page].get.ts +1 -15
- package/corpus/templates/design/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/design/actions/connect-assets-mcp.ts +1 -1
- package/corpus/templates/design/agent-native.app-skill.json +1 -1
- package/corpus/templates/design/app/components/design/DesignCanvas.tsx +88 -12
- package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +1 -0
- package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +4 -1
- package/corpus/templates/design/changelog/2026-07-13-adding-shapes-preserves-canvas-background.md +6 -0
- package/corpus/templates/design/changelog/2026-07-13-clicking-quickly-between-overlapping-elements-no-longer-bounc.md +6 -0
- package/corpus/templates/design/server/plugins/assets-mcp.ts +1 -1
- package/corpus/templates/design/server/routes/[...page].get.ts +0 -2
- package/corpus/templates/dispatch/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/forms/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/macros/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/mail/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/plan/.agents/skills/security/SKILL.md +10 -0
- package/corpus/templates/plan/.agents/skills/visual-plan/SKILL.md +1 -1
- package/corpus/templates/plan/.agents/skills/visual-recap/SKILL.md +2 -2
- package/corpus/templates/plan/agent-native.app-skill.json +1 -1
- package/corpus/templates/plan/app/lib/plan-local-bridge.ts +6 -1
- package/corpus/templates/plan/app/pages/PlansPage.tsx +15 -6
- package/corpus/templates/plan/changelog/2026-07-13-fixed-local-plan-previews-continuously-flickering-while-revi.md +6 -0
- package/corpus/templates/plan/server/routes/[...page].get.ts +0 -2
- package/corpus/templates/slides/.agents/skills/security/SKILL.md +10 -0
- package/dist/a2a/client.d.ts +2 -0
- package/dist/a2a/client.d.ts.map +1 -1
- package/dist/a2a/client.js +2 -0
- package/dist/a2a/client.js.map +1 -1
- package/dist/a2a/handlers.d.ts.map +1 -1
- package/dist/a2a/handlers.js +84 -7
- package/dist/a2a/handlers.js.map +1 -1
- package/dist/cli/connect.d.ts +2 -2
- package/dist/cli/connect.d.ts.map +1 -1
- package/dist/cli/connect.js +45 -23
- package/dist/cli/connect.js.map +1 -1
- package/dist/cli/mcp-config-writers.d.ts.map +1 -1
- package/dist/cli/mcp-config-writers.js +7 -0
- package/dist/cli/mcp-config-writers.js.map +1 -1
- package/dist/cli/mcp.js +5 -3
- package/dist/cli/mcp.js.map +1 -1
- package/dist/cli/skills-content/assets-skill.d.ts +1 -1
- package/dist/cli/skills-content/assets-skill.d.ts.map +1 -1
- package/dist/cli/skills-content/assets-skill.js +1 -1
- package/dist/cli/skills-content/assets-skill.js.map +1 -1
- package/dist/cli/skills-content/design-exploration-skill.d.ts +1 -1
- package/dist/cli/skills-content/design-exploration-skill.d.ts.map +1 -1
- package/dist/cli/skills-content/design-exploration-skill.js +1 -1
- package/dist/cli/skills-content/design-exploration-skill.js.map +1 -1
- package/dist/cli/skills-content/help.d.ts +1 -1
- package/dist/cli/skills-content/help.d.ts.map +1 -1
- package/dist/cli/skills-content/help.js +1 -1
- package/dist/cli/skills-content/help.js.map +1 -1
- package/dist/cli/skills-content/plan-setup-auth.d.ts +1 -1
- package/dist/cli/skills-content/plan-setup-auth.d.ts.map +1 -1
- package/dist/cli/skills-content/plan-setup-auth.js +1 -1
- package/dist/cli/skills-content/plan-setup-auth.js.map +1 -1
- package/dist/cli/skills-content/visual-plan-skill.d.ts +1 -1
- package/dist/cli/skills-content/visual-plan-skill.d.ts.map +1 -1
- package/dist/cli/skills-content/visual-plan-skill.js +1 -1
- package/dist/cli/skills-content/visual-plan-skill.js.map +1 -1
- package/dist/cli/skills-content/visual-recap-skill.d.ts +1 -1
- package/dist/cli/skills-content/visual-recap-skill.d.ts.map +1 -1
- package/dist/cli/skills-content/visual-recap-skill.js +2 -2
- package/dist/cli/skills-content/visual-recap-skill.js.map +1 -1
- package/dist/cli/skills.d.ts.map +1 -1
- package/dist/cli/skills.js +16 -12
- package/dist/cli/skills.js.map +1 -1
- package/dist/client/resources/McpIntegrationDialog.d.ts.map +1 -1
- package/dist/client/resources/McpIntegrationDialog.js +1 -1
- package/dist/client/resources/McpIntegrationDialog.js.map +1 -1
- package/dist/client/resources/mcp-integration-catalog.d.ts +1 -0
- package/dist/client/resources/mcp-integration-catalog.d.ts.map +1 -1
- package/dist/client/resources/mcp-integration-catalog.js +14 -0
- package/dist/client/resources/mcp-integration-catalog.js.map +1 -1
- package/dist/collab/awareness.d.ts +2 -2
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/embedding/agent.d.ts.map +1 -1
- package/dist/embedding/agent.js +6 -7
- package/dist/embedding/agent.js.map +1 -1
- package/dist/localization/default-messages.d.ts +5 -0
- package/dist/localization/default-messages.d.ts.map +1 -1
- package/dist/localization/default-messages.js +5 -0
- package/dist/localization/default-messages.js.map +1 -1
- package/dist/mcp/ask-app-inline-tasks.d.ts +47 -0
- package/dist/mcp/ask-app-inline-tasks.d.ts.map +1 -0
- package/dist/mcp/ask-app-inline-tasks.js +87 -0
- package/dist/mcp/ask-app-inline-tasks.js.map +1 -0
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +56 -3
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/builtin-tools.d.ts.map +1 -1
- package/dist/mcp/builtin-tools.js +141 -21
- package/dist/mcp/builtin-tools.js.map +1 -1
- package/dist/mcp/connect-route.d.ts +12 -10
- package/dist/mcp/connect-route.d.ts.map +1 -1
- package/dist/mcp/connect-route.js +17 -14
- package/dist/mcp/connect-route.js.map +1 -1
- package/dist/mcp/oauth-route.d.ts +1 -1
- package/dist/mcp/oauth-route.d.ts.map +1 -1
- package/dist/mcp/oauth-route.js +30 -13
- package/dist/mcp/oauth-route.js.map +1 -1
- package/dist/mcp/route-paths.d.ts +13 -0
- package/dist/mcp/route-paths.d.ts.map +1 -0
- package/dist/mcp/route-paths.js +27 -0
- package/dist/mcp/route-paths.js.map +1 -0
- package/dist/mcp/server.d.ts +2 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +14 -6
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/stdio.d.ts +7 -6
- package/dist/mcp/stdio.d.ts.map +1 -1
- package/dist/mcp/stdio.js +27 -15
- package/dist/mcp/stdio.js.map +1 -1
- package/dist/mcp/workspace-resolve.d.ts +2 -1
- package/dist/mcp/workspace-resolve.d.ts.map +1 -1
- package/dist/mcp/workspace-resolve.js +2 -1
- package/dist/mcp/workspace-resolve.js.map +1 -1
- package/dist/mcp-client/manager.js +6 -3
- package/dist/mcp-client/manager.js.map +1 -1
- package/dist/mcp-client/remote-store.js +5 -7
- package/dist/mcp-client/remote-store.js.map +1 -1
- package/dist/notifications/routes.d.ts +2 -2
- package/dist/observability/routes.d.ts +3 -3
- package/dist/progress/routes.d.ts +1 -1
- package/dist/provider-api/corpus-jobs.d.ts +2 -2
- package/dist/resources/handlers.d.ts +3 -3
- package/dist/secrets/routes.d.ts +6 -6
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +60 -9
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +16 -6
- package/dist/server/auth.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts +4 -3
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +20 -15
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/csrf.d.ts.map +1 -1
- package/dist/server/csrf.js +11 -0
- package/dist/server/csrf.js.map +1 -1
- package/dist/server/framework-request-handler.d.ts.map +1 -1
- package/dist/server/framework-request-handler.js +8 -2
- package/dist/server/framework-request-handler.js.map +1 -1
- package/dist/server/google-oauth.d.ts +2 -0
- package/dist/server/google-oauth.d.ts.map +1 -1
- package/dist/server/google-oauth.js +5 -0
- package/dist/server/google-oauth.js.map +1 -1
- package/dist/server/http-response-telemetry.d.ts.map +1 -1
- package/dist/server/http-response-telemetry.js +4 -1
- package/dist/server/http-response-telemetry.js.map +1 -1
- package/dist/server/recap-image-route.js +3 -3
- package/dist/server/recap-image-route.js.map +1 -1
- package/dist/server/security-headers.d.ts.map +1 -1
- package/dist/server/security-headers.js +4 -1
- package/dist/server/security-headers.js.map +1 -1
- package/dist/server/ssr-handler.d.ts.map +1 -1
- package/dist/server/ssr-handler.js +3 -1
- package/dist/server/ssr-handler.js.map +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/dist/shared/cache-control.d.ts +7 -6
- package/dist/shared/cache-control.d.ts.map +1 -1
- package/dist/shared/cache-control.js +4 -3
- package/dist/shared/cache-control.js.map +1 -1
- package/dist/templates/default/.agents/skills/security/SKILL.md +10 -0
- package/dist/templates/workspace-core/.agents/skills/authentication/SKILL.md +15 -6
- package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +16 -10
- package/dist/templates/workspace-core/.agents/skills/performance/SKILL.md +20 -1
- package/dist/templates/workspace-core/.agents/skills/security/SKILL.md +10 -0
- package/docs/content/actions.mdx +1 -1
- package/docs/content/authentication.mdx +1 -1
- package/docs/content/dispatch.mdx +3 -3
- package/docs/content/external-agents.mdx +30 -19
- package/docs/content/locales/ar-SA/actions.mdx +1 -1
- package/docs/content/locales/ar-SA/authentication.mdx +1 -1
- package/docs/content/locales/ar-SA/dispatch.mdx +3 -3
- package/docs/content/locales/ar-SA/external-agents.mdx +23 -19
- package/docs/content/locales/ar-SA/mcp-clients.mdx +31 -3
- package/docs/content/locales/ar-SA/mcp-protocol.mdx +29 -15
- package/docs/content/locales/ar-SA/plan-plugin.mdx +3 -3
- package/docs/content/locales/ar-SA/server.mdx +2 -2
- package/docs/content/locales/ar-SA/skills-guide.mdx +1 -1
- package/docs/content/locales/ar-SA/template-assets.mdx +1 -1
- package/docs/content/locales/ar-SA/template-dispatch.mdx +2 -2
- package/docs/content/locales/ar-SA/template-plan.mdx +3 -3
- package/docs/content/locales/de-DE/actions.mdx +1 -1
- package/docs/content/locales/de-DE/authentication.mdx +1 -1
- package/docs/content/locales/de-DE/dispatch.mdx +3 -3
- package/docs/content/locales/de-DE/external-agents.mdx +23 -19
- package/docs/content/locales/de-DE/mcp-clients.mdx +37 -3
- package/docs/content/locales/de-DE/mcp-protocol.mdx +29 -15
- package/docs/content/locales/de-DE/plan-plugin.mdx +3 -3
- package/docs/content/locales/de-DE/server.mdx +2 -2
- package/docs/content/locales/de-DE/skills-guide.mdx +1 -1
- package/docs/content/locales/de-DE/template-assets.mdx +1 -1
- package/docs/content/locales/de-DE/template-dispatch.mdx +2 -2
- package/docs/content/locales/de-DE/template-plan.mdx +3 -3
- package/docs/content/locales/es-ES/actions.mdx +1 -1
- package/docs/content/locales/es-ES/authentication.mdx +1 -1
- package/docs/content/locales/es-ES/dispatch.mdx +3 -3
- package/docs/content/locales/es-ES/external-agents.mdx +32 -19
- package/docs/content/locales/es-ES/mcp-clients.mdx +17 -3
- package/docs/content/locales/es-ES/mcp-protocol.mdx +38 -15
- package/docs/content/locales/es-ES/plan-plugin.mdx +3 -3
- package/docs/content/locales/es-ES/server.mdx +2 -2
- package/docs/content/locales/es-ES/skills-guide.mdx +1 -1
- package/docs/content/locales/es-ES/template-assets.mdx +1 -1
- package/docs/content/locales/es-ES/template-dispatch.mdx +2 -2
- package/docs/content/locales/es-ES/template-plan.mdx +3 -3
- package/docs/content/locales/fr-FR/actions.mdx +1 -1
- package/docs/content/locales/fr-FR/authentication.mdx +1 -1
- package/docs/content/locales/fr-FR/dispatch.mdx +3 -3
- package/docs/content/locales/fr-FR/external-agents.mdx +23 -19
- package/docs/content/locales/fr-FR/mcp-clients.mdx +17 -3
- package/docs/content/locales/fr-FR/mcp-protocol.mdx +29 -15
- package/docs/content/locales/fr-FR/plan-plugin.mdx +3 -3
- package/docs/content/locales/fr-FR/server.mdx +2 -2
- package/docs/content/locales/fr-FR/skills-guide.mdx +1 -1
- package/docs/content/locales/fr-FR/template-assets.mdx +1 -1
- package/docs/content/locales/fr-FR/template-dispatch.mdx +2 -2
- package/docs/content/locales/fr-FR/template-plan.mdx +3 -3
- package/docs/content/locales/hi-IN/actions.mdx +1 -1
- package/docs/content/locales/hi-IN/authentication.mdx +1 -1
- package/docs/content/locales/hi-IN/dispatch.mdx +3 -3
- package/docs/content/locales/hi-IN/external-agents.mdx +31 -19
- package/docs/content/locales/hi-IN/mcp-clients.mdx +17 -3
- package/docs/content/locales/hi-IN/mcp-protocol.mdx +36 -15
- package/docs/content/locales/hi-IN/plan-plugin.mdx +3 -3
- package/docs/content/locales/hi-IN/server.mdx +2 -2
- package/docs/content/locales/hi-IN/skills-guide.mdx +1 -1
- package/docs/content/locales/hi-IN/template-assets.mdx +1 -1
- package/docs/content/locales/hi-IN/template-dispatch.mdx +2 -2
- package/docs/content/locales/hi-IN/template-plan.mdx +3 -3
- package/docs/content/locales/ja-JP/actions.mdx +1 -1
- package/docs/content/locales/ja-JP/authentication.mdx +1 -1
- package/docs/content/locales/ja-JP/dispatch.mdx +3 -3
- package/docs/content/locales/ja-JP/external-agents.mdx +23 -19
- package/docs/content/locales/ja-JP/mcp-clients.mdx +34 -3
- package/docs/content/locales/ja-JP/mcp-protocol.mdx +29 -15
- package/docs/content/locales/ja-JP/plan-plugin.mdx +3 -3
- package/docs/content/locales/ja-JP/server.mdx +2 -2
- package/docs/content/locales/ja-JP/skills-guide.mdx +1 -1
- package/docs/content/locales/ja-JP/template-assets.mdx +1 -1
- package/docs/content/locales/ja-JP/template-dispatch.mdx +2 -2
- package/docs/content/locales/ja-JP/template-plan.mdx +3 -3
- package/docs/content/locales/ko-KR/actions.mdx +1 -1
- package/docs/content/locales/ko-KR/authentication.mdx +1 -1
- package/docs/content/locales/ko-KR/dispatch.mdx +3 -3
- package/docs/content/locales/ko-KR/external-agents.mdx +30 -19
- package/docs/content/locales/ko-KR/mcp-clients.mdx +33 -3
- package/docs/content/locales/ko-KR/mcp-protocol.mdx +36 -15
- package/docs/content/locales/ko-KR/plan-plugin.mdx +3 -3
- package/docs/content/locales/ko-KR/server.mdx +2 -2
- package/docs/content/locales/ko-KR/skills-guide.mdx +1 -1
- package/docs/content/locales/ko-KR/template-assets.mdx +1 -1
- package/docs/content/locales/ko-KR/template-dispatch.mdx +2 -2
- package/docs/content/locales/ko-KR/template-plan.mdx +3 -3
- package/docs/content/locales/pt-BR/actions.mdx +1 -1
- package/docs/content/locales/pt-BR/authentication.mdx +1 -1
- package/docs/content/locales/pt-BR/dispatch.mdx +3 -3
- package/docs/content/locales/pt-BR/external-agents.mdx +32 -19
- package/docs/content/locales/pt-BR/mcp-clients.mdx +34 -3
- package/docs/content/locales/pt-BR/mcp-protocol.mdx +32 -15
- package/docs/content/locales/pt-BR/plan-plugin.mdx +3 -3
- package/docs/content/locales/pt-BR/server.mdx +2 -2
- package/docs/content/locales/pt-BR/skills-guide.mdx +1 -1
- package/docs/content/locales/pt-BR/template-assets.mdx +1 -1
- package/docs/content/locales/pt-BR/template-dispatch.mdx +2 -2
- package/docs/content/locales/pt-BR/template-plan.mdx +3 -3
- package/docs/content/locales/zh-CN/actions.mdx +1 -1
- package/docs/content/locales/zh-CN/authentication.mdx +1 -1
- package/docs/content/locales/zh-CN/dispatch.mdx +3 -3
- package/docs/content/locales/zh-CN/external-agents.mdx +23 -19
- package/docs/content/locales/zh-CN/mcp-clients.mdx +28 -3
- package/docs/content/locales/zh-CN/mcp-protocol.mdx +29 -15
- package/docs/content/locales/zh-CN/plan-plugin.mdx +3 -3
- package/docs/content/locales/zh-CN/server.mdx +2 -2
- package/docs/content/locales/zh-CN/skills-guide.mdx +1 -1
- package/docs/content/locales/zh-CN/template-assets.mdx +1 -1
- package/docs/content/locales/zh-CN/template-dispatch.mdx +2 -2
- package/docs/content/locales/zh-CN/template-plan.mdx +3 -3
- package/docs/content/locales/zh-TW/actions.mdx +1 -1
- package/docs/content/locales/zh-TW/authentication.mdx +1 -1
- package/docs/content/locales/zh-TW/dispatch.mdx +3 -3
- package/docs/content/locales/zh-TW/external-agents.mdx +23 -19
- package/docs/content/locales/zh-TW/mcp-clients.mdx +28 -3
- package/docs/content/locales/zh-TW/mcp-protocol.mdx +30 -15
- package/docs/content/locales/zh-TW/plan-plugin.mdx +3 -3
- package/docs/content/locales/zh-TW/server.mdx +2 -2
- package/docs/content/locales/zh-TW/skills-guide.mdx +1 -1
- package/docs/content/locales/zh-TW/template-assets.mdx +1 -1
- package/docs/content/locales/zh-TW/template-dispatch.mdx +2 -2
- package/docs/content/locales/zh-TW/template-plan.mdx +3 -3
- package/docs/content/mcp-clients.mdx +31 -4
- package/docs/content/mcp-protocol.mdx +35 -15
- package/docs/content/plan-plugin.mdx +3 -3
- package/docs/content/server.mdx +2 -2
- package/docs/content/skills-guide.mdx +1 -1
- package/docs/content/template-assets.mdx +1 -1
- package/docs/content/template-dispatch.mdx +2 -2
- package/docs/content/template-plan.mdx +3 -3
- package/package.json +1 -1
- package/src/templates/default/.agents/skills/security/SKILL.md +10 -0
- package/src/templates/workspace-core/.agents/skills/authentication/SKILL.md +15 -6
- package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +16 -10
- package/src/templates/workspace-core/.agents/skills/performance/SKILL.md +20 -1
- package/src/templates/workspace-core/.agents/skills/security/SKILL.md +10 -0
package/dist/mcp/stdio.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAUH,MAAM,WAAW,kBAAkB;IACjC,yEAAyE;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qEAAqE;IACrE,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,qDAAqD;IACrD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,qCAAqC;IACrC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,sEAAsE;IACtE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAmQD;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,IAAI,GAAE,kBAAuB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAef"}
|
package/dist/mcp/stdio.js
CHANGED
|
@@ -7,12 +7,13 @@
|
|
|
7
7
|
*
|
|
8
8
|
* - **proxy (default)** — connect an MCP `Client` over
|
|
9
9
|
* `StreamableHTTPClientTransport` to the *already-running* local app's
|
|
10
|
-
* `http://127.0.0.1:<port>/
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* it lazily on first
|
|
10
|
+
* `http://127.0.0.1:<port>/mcp` (falling back to the legacy
|
|
11
|
+
* `/_agent-native/mcp` path), and run a stdio `Server` that forwards tools
|
|
12
|
+
* and optional MCP App resources to it. The live app is the single source
|
|
13
|
+
* of truth: HMR'd actions, the real registry, correct per-request deep
|
|
14
|
+
* links, and tenant scoping all come for free. If the app isn't running,
|
|
15
|
+
* we wait briefly for it (the workspace gateway boots it lazily on first
|
|
16
|
+
* request).
|
|
16
17
|
*
|
|
17
18
|
* - **standalone (`--standalone`)** — no running server, no HMR. Build the
|
|
18
19
|
* MCP server in-process from `autoDiscoverActions(cwd)` +
|
|
@@ -22,8 +23,12 @@
|
|
|
22
23
|
* Node-only: imports `node:*` and the SDK stdio/http transports. Never part
|
|
23
24
|
* of the serverless bundle.
|
|
24
25
|
*/
|
|
26
|
+
import { MCP_LEGACY_ROUTE_PREFIX, MCP_PUBLIC_ROUTE_PREFIX, } from "./route-paths.js";
|
|
25
27
|
import { resolveLocalAppOrigin } from "./workspace-resolve.js";
|
|
26
|
-
const
|
|
28
|
+
const MCP_SUBPATHS = [
|
|
29
|
+
MCP_PUBLIC_ROUTE_PREFIX,
|
|
30
|
+
MCP_LEGACY_ROUTE_PREFIX,
|
|
31
|
+
];
|
|
27
32
|
function log(msg) {
|
|
28
33
|
// stderr only — stdout is the MCP protocol channel and must stay clean.
|
|
29
34
|
process.stderr.write(`[mcp] ${msg}\n`);
|
|
@@ -54,9 +59,9 @@ function authHeaders(env) {
|
|
|
54
59
|
headers["X-Agent-Native-Owner-Email"] = owner;
|
|
55
60
|
return headers;
|
|
56
61
|
}
|
|
57
|
-
async function probeOrigin(origin, timeoutMs = 800) {
|
|
62
|
+
async function probeOrigin(origin, subpath, timeoutMs = 800) {
|
|
58
63
|
try {
|
|
59
|
-
const res = await fetch(`${origin}${
|
|
64
|
+
const res = await fetch(`${origin}${subpath}`, {
|
|
60
65
|
method: "GET",
|
|
61
66
|
signal: AbortSignal.timeout(timeoutMs),
|
|
62
67
|
});
|
|
@@ -67,6 +72,13 @@ async function probeOrigin(origin, timeoutMs = 800) {
|
|
|
67
72
|
return false;
|
|
68
73
|
}
|
|
69
74
|
}
|
|
75
|
+
async function resolveMcpSubpath(origin) {
|
|
76
|
+
for (const subpath of MCP_SUBPATHS) {
|
|
77
|
+
if (await probeOrigin(origin, subpath))
|
|
78
|
+
return subpath;
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
70
82
|
/**
|
|
71
83
|
* Proxy mode: stdio Server ⇄ HTTP Client to the running app.
|
|
72
84
|
*
|
|
@@ -83,24 +95,24 @@ async function runProxy(opts) {
|
|
|
83
95
|
port: opts.port,
|
|
84
96
|
});
|
|
85
97
|
const env = opts.env ?? process.env;
|
|
86
|
-
const target = `${origin}${MCP_SUBPATH}`;
|
|
87
98
|
// Wait for the app to come up. The workspace gateway lazily boots an app's
|
|
88
99
|
// dev server on first request, so a fresh `mcp serve` may briefly race the
|
|
89
100
|
// boot. Hit the gateway path too so the lazy start is triggered.
|
|
90
101
|
const deadline = Date.now() + (opts.waitForAppMs ?? 60_000);
|
|
91
|
-
let
|
|
92
|
-
if (!
|
|
102
|
+
let mcpSubpath = await resolveMcpSubpath(origin);
|
|
103
|
+
if (!mcpSubpath) {
|
|
93
104
|
log(`Waiting for ${appId} at ${origin} …`);
|
|
94
|
-
while (!
|
|
105
|
+
while (!mcpSubpath && Date.now() < deadline) {
|
|
95
106
|
await new Promise((r) => setTimeout(r, 750));
|
|
96
|
-
|
|
107
|
+
mcpSubpath = await resolveMcpSubpath(origin);
|
|
97
108
|
}
|
|
98
109
|
}
|
|
99
|
-
if (!
|
|
110
|
+
if (!mcpSubpath) {
|
|
100
111
|
throw new Error(`Timed out waiting for the local app at ${origin}. Start it with ` +
|
|
101
112
|
`\`agent-native dev\` (or \`agent-native workspace-dev\`), or run ` +
|
|
102
113
|
`\`agent-native mcp serve --standalone\` to build the server from disk.`);
|
|
103
114
|
}
|
|
115
|
+
const target = `${origin}${mcpSubpath}`;
|
|
104
116
|
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
|
|
105
117
|
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
106
118
|
const { Server } = await import("@modelcontextprotocol/sdk/server/index.js");
|
package/dist/mcp/stdio.js.map
CHANGED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,GAAuB,EAAE;IAE7B,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,MAAM,aAAa,CAAC,IAAI,CAAC,CAAC;QAC1B,OAAO;IACT,CAAC;IACD,IAAI,CAAC;QACH,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,mEAAmE;QACnE,qEAAqE;QACrE,qEAAqE;QACrE,2CAA2C;QAC3C,GAAG,CAAC,sBAAsB,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC,CAAC;QACjD,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * MCP **stdio** transport for the `agent-native mcp serve` command.\n *\n * This is the binary external coding agents (Claude Code, Claude Cowork,\n * Codex) actually launch — they speak MCP over a child process's stdio, not\n * HTTP. We expose the agent-native app's MCP surface over stdio in two modes:\n *\n * - **proxy (default)** — connect an MCP `Client` over\n * `StreamableHTTPClientTransport` to the *already-running* local app's\n * `http://127.0.0.1:<port>/_agent-native/mcp`, and run a stdio `Server`\n * that forwards tools and optional MCP App resources to it. The live app\n * is the single source of truth: HMR'd actions, the real registry, correct\n * per-request deep links, and tenant scoping all come for free. If the\n * app isn't running, we wait briefly for it (the workspace gateway boots\n * it lazily on first request).\n *\n * - **standalone (`--standalone`)** — no running server, no HMR. Build the\n * MCP server in-process from `autoDiscoverActions(cwd)` +\n * `createMCPServerForRequest`, connected straight to a\n * `StdioServerTransport`. Useful in CI / when nothing is serving.\n *\n * Node-only: imports `node:*` and the SDK stdio/http transports. Never part\n * of the serverless bundle.\n */\n\nimport type { ServerCapabilities } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport { resolveLocalAppOrigin } from \"./workspace-resolve.js\";\n\nexport interface RunMCPStdioOptions {\n /** App id to bridge to (workspace). Optional in a single-app project. */\n appId?: string;\n /** Explicit port of the running app's dev server. Overrides discovery. */\n port?: number;\n /** Skip the HTTP proxy and build the server in-process from disk. */\n standalone?: boolean;\n /** Working directory (defaults to process.cwd()). */\n cwd?: string;\n /** Env (defaults to process.env). */\n env?: NodeJS.ProcessEnv;\n /** Max ms to wait for the running app before failing (proxy mode). */\n waitForAppMs?: number;\n}\n\nconst MCP_SUBPATH = \"/_agent-native/mcp\";\n\nfunction log(msg: string): void {\n // stderr only — stdout is the MCP protocol channel and must stay clean.\n process.stderr.write(`[mcp] ${msg}\\n`);\n}\n\n/**\n * Owner identity the installer wrote into the client config's env. Passed\n * through to the HTTP MCP endpoint as a JWT/identity bearer (when present)\n * so tool runs stay tenant-scoped. For local dev with a static ACCESS_TOKEN\n * the email is informational; for hosted JWT auth the token already carries\n * `sub`, so we only add an `X-Agent-Native-Owner-Email` hint header.\n */\nfunction authHeaders(env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = {\n \"X-Agent-Native-MCP-Client\": \"agent-native-mcp-proxy\",\n };\n // Default to the compact/connector catalog + tool-search like every other\n // client. The local CLI no longer auto-pulls the full ~105-tool catalog;\n // opt in explicitly with AGENT_NATIVE_MCP_FULL_CATALOG=1 when you really want\n // every tool schema loaded up front.\n if (env.AGENT_NATIVE_MCP_FULL_CATALOG === \"1\") {\n headers[\"X-Agent-Native-MCP-Full-Catalog\"] = \"1\";\n }\n const token = env.ACCESS_TOKEN || env.AGENT_NATIVE_MCP_TOKEN;\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n const owner = env.AGENT_NATIVE_OWNER_EMAIL;\n if (owner) headers[\"X-Agent-Native-Owner-Email\"] = owner;\n return headers;\n}\n\nasync function probeOrigin(origin: string, timeoutMs = 800): Promise<boolean> {\n try {\n const res = await fetch(`${origin}${MCP_SUBPATH}`, {\n method: \"GET\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n // Any HTTP response (even 401/405/406) means the server is up.\n return res.status > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Proxy mode: stdio Server ⇄ HTTP Client to the running app.\n *\n * We register the standard handlers on the stdio server and forward them\n * verbatim to the upstream HTTP MCP server via the SDK `Client`. The upstream\n * owns tool definitions, results, MCP App resources, and the appended\n * deep-link block / `_meta`, so nothing is duplicated here.\n */\nasync function runProxy(opts: RunMCPStdioOptions): Promise<void> {\n const { origin, appId } = await resolveLocalAppOrigin({\n cwd: opts.cwd,\n env: opts.env,\n appId: opts.appId,\n port: opts.port,\n });\n const env = opts.env ?? process.env;\n const target = `${origin}${MCP_SUBPATH}`;\n\n // Wait for the app to come up. The workspace gateway lazily boots an app's\n // dev server on first request, so a fresh `mcp serve` may briefly race the\n // boot. Hit the gateway path too so the lazy start is triggered.\n const deadline = Date.now() + (opts.waitForAppMs ?? 60_000);\n let up = await probeOrigin(origin);\n if (!up) {\n log(`Waiting for ${appId} at ${origin} …`);\n while (!up && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 750));\n up = await probeOrigin(origin);\n }\n }\n if (!up) {\n throw new Error(\n `Timed out waiting for the local app at ${origin}. Start it with ` +\n `\\`agent-native dev\\` (or \\`agent-native workspace-dev\\`), or run ` +\n `\\`agent-native mcp serve --standalone\\` to build the server from disk.`,\n );\n }\n\n const { Client } = await import(\"@modelcontextprotocol/sdk/client/index.js\");\n const { StreamableHTTPClientTransport } =\n await import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\");\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n } = await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // --- Upstream HTTP client -------------------------------------------------\n const clientTransport = new StreamableHTTPClientTransport(new URL(target), {\n requestInit: { headers: authHeaders(env) },\n });\n const client = new Client(\n { name: \"agent-native-mcp-proxy\", version: \"1.0.0\" },\n { capabilities: {} },\n );\n await client.connect(clientTransport);\n log(`Proxying stdio ⇄ ${target} (app: ${appId})`);\n\n // --- Downstream stdio server ---------------------------------------------\n const upstreamCapabilities = client.getServerCapabilities();\n const capabilities: ServerCapabilities = { tools: {} };\n if (upstreamCapabilities?.resources) capabilities.resources = {};\n if (upstreamCapabilities?.extensions) {\n capabilities.extensions = upstreamCapabilities.extensions;\n }\n\n const server = new Server(\n { name: `agent-native-${appId}`, version: \"1.0.0\" },\n { capabilities },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request: any) => {\n return client.listTools(request.params);\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n // Forward the call verbatim; the upstream appends the deep-link block.\n return client.callTool(request.params);\n });\n\n if (upstreamCapabilities?.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\n async (request: any) => {\n return client.listResources(request.params);\n },\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async (request: any) => {\n return client.listResourceTemplates(request.params);\n },\n );\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request: any) => {\n return client.readResource(request.params);\n },\n );\n }\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n\n // Keep the proxy alive until the client/transport closes.\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n stdioTransport.onclose = done;\n clientTransport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n\n try {\n await client.close();\n } catch {\n // best-effort\n }\n}\n\n/**\n * Standalone mode: build the MCP server in-process from disk.\n *\n * No running server, no HMR — actions are discovered via\n * `autoDiscoverActions(cwd)` and the shared `createMCPServerForRequest`\n * builder is reused so behavior (tools, deep links, builtin cross-app tools)\n * matches the HTTP mount exactly.\n */\nasync function runStandalone(opts: RunMCPStdioOptions): Promise<void> {\n const cwd = opts.cwd ?? process.cwd();\n const env = opts.env ?? process.env;\n\n const { resolveLocalAppOrigin } = await import(\"./workspace-resolve.js\");\n let appId = opts.appId ?? \"app\";\n let origin: string | undefined;\n try {\n const resolved = await resolveLocalAppOrigin({\n cwd,\n env,\n appId: opts.appId,\n port: opts.port,\n });\n appId = resolved.appId;\n // Origin is best-effort here (server may not be running) — still useful\n // so a `link` builder's relative deep link becomes an absolute URL.\n origin = resolved.origin;\n } catch {\n // No workspace / can't resolve — fall back to a bare app id.\n }\n\n const { autoDiscoverActions } = await import(\"../server/action-discovery.js\");\n const { createMCPServerForRequest } = await import(\"./build-server.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n\n const actions = await autoDiscoverActions(cwd);\n log(\n `Standalone: discovered ${Object.keys(actions).length} action(s) in ${cwd}`,\n );\n\n const server = await createMCPServerForRequest(\n {\n name: appId.charAt(0).toUpperCase() + appId.slice(1),\n appId,\n description: `Agent-native ${appId} app (standalone MCP)`,\n actions,\n // No askAgent in standalone — there is no running engine/runtime here.\n // builtin cross-app tools stay on so `list_apps` / `open_app` /\n // `create_workspace_app` / `list_templates` still work from disk.\n },\n // No verified identity in standalone (no inbound auth header). Runs with\n // platform-default scope, same as a tokenless local HTTP mount.\n undefined,\n {\n origin,\n clientName: \"agent-native-mcp-standalone\",\n // Compact by default; opt into the full catalog with the env flag.\n fullCatalog: process.env.AGENT_NATIVE_MCP_FULL_CATALOG === \"1\",\n },\n );\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n transport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n}\n\n/**\n * Entry point for `agent-native mcp serve`. Defaults to proxy mode; pass\n * `standalone: true` to build the server from disk with no running app.\n */\nexport async function runMCPStdio(\n opts: RunMCPStdioOptions = {},\n): Promise<void> {\n if (opts.standalone) {\n await runStandalone(opts);\n return;\n }\n try {\n await runProxy(opts);\n } catch (err: any) {\n // Proxy couldn't reach a running app — surface a clear, actionable\n // message on stderr. We do NOT silently fall back to standalone: the\n // caller asked for the live registry; auto-falling-back would hide a\n // broken dev server and serve stale tools.\n log(`Proxy mode failed: ${err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O,EAAE,EAAE;QAClC,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC;QAC7B,SAAS,CAAC,OAAO,GAAG,IAAI,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAC7B,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,IAAI,GAAuB,EAAE;IAE7B,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,MAAM,aAAa,CAAC,IAAI,CAAC,CAAC;QAC1B,OAAO;IACT,CAAC;IACD,IAAI,CAAC;QACH,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,mEAAmE;QACnE,qEAAqE;QACrE,qEAAqE;QACrE,2CAA2C;QAC3C,GAAG,CAAC,sBAAsB,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC,CAAC;QACjD,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * MCP **stdio** transport for the `agent-native mcp serve` command.\n *\n * This is the binary external coding agents (Claude Code, Claude Cowork,\n * Codex) actually launch — they speak MCP over a child process's stdio, not\n * HTTP. We expose the agent-native app's MCP surface over stdio in two modes:\n *\n * - **proxy (default)** — connect an MCP `Client` over\n * `StreamableHTTPClientTransport` to the *already-running* local app's\n * `http://127.0.0.1:<port>/mcp` (falling back to the legacy\n * `/_agent-native/mcp` path), and run a stdio `Server` that forwards tools\n * and optional MCP App resources to it. The live app is the single source\n * of truth: HMR'd actions, the real registry, correct per-request deep\n * links, and tenant scoping all come for free. If the app isn't running,\n * we wait briefly for it (the workspace gateway boots it lazily on first\n * request).\n *\n * - **standalone (`--standalone`)** — no running server, no HMR. Build the\n * MCP server in-process from `autoDiscoverActions(cwd)` +\n * `createMCPServerForRequest`, connected straight to a\n * `StdioServerTransport`. Useful in CI / when nothing is serving.\n *\n * Node-only: imports `node:*` and the SDK stdio/http transports. Never part\n * of the serverless bundle.\n */\n\nimport type { ServerCapabilities } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport {\n MCP_LEGACY_ROUTE_PREFIX,\n MCP_PUBLIC_ROUTE_PREFIX,\n} from \"./route-paths.js\";\nimport { resolveLocalAppOrigin } from \"./workspace-resolve.js\";\n\nexport interface RunMCPStdioOptions {\n /** App id to bridge to (workspace). Optional in a single-app project. */\n appId?: string;\n /** Explicit port of the running app's dev server. Overrides discovery. */\n port?: number;\n /** Skip the HTTP proxy and build the server in-process from disk. */\n standalone?: boolean;\n /** Working directory (defaults to process.cwd()). */\n cwd?: string;\n /** Env (defaults to process.env). */\n env?: NodeJS.ProcessEnv;\n /** Max ms to wait for the running app before failing (proxy mode). */\n waitForAppMs?: number;\n}\n\nconst MCP_SUBPATHS = [\n MCP_PUBLIC_ROUTE_PREFIX,\n MCP_LEGACY_ROUTE_PREFIX,\n] as const;\n\nfunction log(msg: string): void {\n // stderr only — stdout is the MCP protocol channel and must stay clean.\n process.stderr.write(`[mcp] ${msg}\\n`);\n}\n\n/**\n * Owner identity the installer wrote into the client config's env. Passed\n * through to the HTTP MCP endpoint as a JWT/identity bearer (when present)\n * so tool runs stay tenant-scoped. For local dev with a static ACCESS_TOKEN\n * the email is informational; for hosted JWT auth the token already carries\n * `sub`, so we only add an `X-Agent-Native-Owner-Email` hint header.\n */\nfunction authHeaders(env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = {\n \"X-Agent-Native-MCP-Client\": \"agent-native-mcp-proxy\",\n };\n // Default to the compact/connector catalog + tool-search like every other\n // client. The local CLI no longer auto-pulls the full ~105-tool catalog;\n // opt in explicitly with AGENT_NATIVE_MCP_FULL_CATALOG=1 when you really want\n // every tool schema loaded up front.\n if (env.AGENT_NATIVE_MCP_FULL_CATALOG === \"1\") {\n headers[\"X-Agent-Native-MCP-Full-Catalog\"] = \"1\";\n }\n const token = env.ACCESS_TOKEN || env.AGENT_NATIVE_MCP_TOKEN;\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n const owner = env.AGENT_NATIVE_OWNER_EMAIL;\n if (owner) headers[\"X-Agent-Native-Owner-Email\"] = owner;\n return headers;\n}\n\nasync function probeOrigin(\n origin: string,\n subpath: string,\n timeoutMs = 800,\n): Promise<boolean> {\n try {\n const res = await fetch(`${origin}${subpath}`, {\n method: \"GET\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n // Any HTTP response (even 401/405/406) means the server is up.\n return res.status > 0;\n } catch {\n return false;\n }\n}\n\nasync function resolveMcpSubpath(origin: string): Promise<string | null> {\n for (const subpath of MCP_SUBPATHS) {\n if (await probeOrigin(origin, subpath)) return subpath;\n }\n return null;\n}\n\n/**\n * Proxy mode: stdio Server ⇄ HTTP Client to the running app.\n *\n * We register the standard handlers on the stdio server and forward them\n * verbatim to the upstream HTTP MCP server via the SDK `Client`. The upstream\n * owns tool definitions, results, MCP App resources, and the appended\n * deep-link block / `_meta`, so nothing is duplicated here.\n */\nasync function runProxy(opts: RunMCPStdioOptions): Promise<void> {\n const { origin, appId } = await resolveLocalAppOrigin({\n cwd: opts.cwd,\n env: opts.env,\n appId: opts.appId,\n port: opts.port,\n });\n const env = opts.env ?? process.env;\n // Wait for the app to come up. The workspace gateway lazily boots an app's\n // dev server on first request, so a fresh `mcp serve` may briefly race the\n // boot. Hit the gateway path too so the lazy start is triggered.\n const deadline = Date.now() + (opts.waitForAppMs ?? 60_000);\n let mcpSubpath = await resolveMcpSubpath(origin);\n if (!mcpSubpath) {\n log(`Waiting for ${appId} at ${origin} …`);\n while (!mcpSubpath && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 750));\n mcpSubpath = await resolveMcpSubpath(origin);\n }\n }\n if (!mcpSubpath) {\n throw new Error(\n `Timed out waiting for the local app at ${origin}. Start it with ` +\n `\\`agent-native dev\\` (or \\`agent-native workspace-dev\\`), or run ` +\n `\\`agent-native mcp serve --standalone\\` to build the server from disk.`,\n );\n }\n const target = `${origin}${mcpSubpath}`;\n\n const { Client } = await import(\"@modelcontextprotocol/sdk/client/index.js\");\n const { StreamableHTTPClientTransport } =\n await import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\");\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n } = await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // --- Upstream HTTP client -------------------------------------------------\n const clientTransport = new StreamableHTTPClientTransport(new URL(target), {\n requestInit: { headers: authHeaders(env) },\n });\n const client = new Client(\n { name: \"agent-native-mcp-proxy\", version: \"1.0.0\" },\n { capabilities: {} },\n );\n await client.connect(clientTransport);\n log(`Proxying stdio ⇄ ${target} (app: ${appId})`);\n\n // --- Downstream stdio server ---------------------------------------------\n const upstreamCapabilities = client.getServerCapabilities();\n const capabilities: ServerCapabilities = { tools: {} };\n if (upstreamCapabilities?.resources) capabilities.resources = {};\n if (upstreamCapabilities?.extensions) {\n capabilities.extensions = upstreamCapabilities.extensions;\n }\n\n const server = new Server(\n { name: `agent-native-${appId}`, version: \"1.0.0\" },\n { capabilities },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request: any) => {\n return client.listTools(request.params);\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n // Forward the call verbatim; the upstream appends the deep-link block.\n return client.callTool(request.params);\n });\n\n if (upstreamCapabilities?.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\n async (request: any) => {\n return client.listResources(request.params);\n },\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async (request: any) => {\n return client.listResourceTemplates(request.params);\n },\n );\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request: any) => {\n return client.readResource(request.params);\n },\n );\n }\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n\n // Keep the proxy alive until the client/transport closes.\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n stdioTransport.onclose = done;\n clientTransport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n\n try {\n await client.close();\n } catch {\n // best-effort\n }\n}\n\n/**\n * Standalone mode: build the MCP server in-process from disk.\n *\n * No running server, no HMR — actions are discovered via\n * `autoDiscoverActions(cwd)` and the shared `createMCPServerForRequest`\n * builder is reused so behavior (tools, deep links, builtin cross-app tools)\n * matches the HTTP mount exactly.\n */\nasync function runStandalone(opts: RunMCPStdioOptions): Promise<void> {\n const cwd = opts.cwd ?? process.cwd();\n const env = opts.env ?? process.env;\n\n const { resolveLocalAppOrigin } = await import(\"./workspace-resolve.js\");\n let appId = opts.appId ?? \"app\";\n let origin: string | undefined;\n try {\n const resolved = await resolveLocalAppOrigin({\n cwd,\n env,\n appId: opts.appId,\n port: opts.port,\n });\n appId = resolved.appId;\n // Origin is best-effort here (server may not be running) — still useful\n // so a `link` builder's relative deep link becomes an absolute URL.\n origin = resolved.origin;\n } catch {\n // No workspace / can't resolve — fall back to a bare app id.\n }\n\n const { autoDiscoverActions } = await import(\"../server/action-discovery.js\");\n const { createMCPServerForRequest } = await import(\"./build-server.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n\n const actions = await autoDiscoverActions(cwd);\n log(\n `Standalone: discovered ${Object.keys(actions).length} action(s) in ${cwd}`,\n );\n\n const server = await createMCPServerForRequest(\n {\n name: appId.charAt(0).toUpperCase() + appId.slice(1),\n appId,\n description: `Agent-native ${appId} app (standalone MCP)`,\n actions,\n // No askAgent in standalone — there is no running engine/runtime here.\n // builtin cross-app tools stay on so `list_apps` / `open_app` /\n // `create_workspace_app` / `list_templates` still work from disk.\n },\n // No verified identity in standalone (no inbound auth header). Runs with\n // platform-default scope, same as a tokenless local HTTP mount.\n undefined,\n {\n origin,\n clientName: \"agent-native-mcp-standalone\",\n // Compact by default; opt into the full catalog with the env flag.\n fullCatalog: process.env.AGENT_NATIVE_MCP_FULL_CATALOG === \"1\",\n },\n );\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n transport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n}\n\n/**\n * Entry point for `agent-native mcp serve`. Defaults to proxy mode; pass\n * `standalone: true` to build the server from disk with no running app.\n */\nexport async function runMCPStdio(\n opts: RunMCPStdioOptions = {},\n): Promise<void> {\n if (opts.standalone) {\n await runStandalone(opts);\n return;\n }\n try {\n await runProxy(opts);\n } catch (err: any) {\n // Proxy couldn't reach a running app — surface a clear, actionable\n // message on stderr. We do NOT silently fall back to standalone: the\n // caller asked for the live registry; auto-falling-back would hide a\n // broken dev server and serve stale tools.\n log(`Proxy mode failed: ${err?.message ?? err}`);\n throw err;\n }\n}\n"]}
|
|
@@ -47,7 +47,8 @@ export declare function resolveWorkspace(cwd?: string, env?: NodeJS.ProcessEnv):
|
|
|
47
47
|
/**
|
|
48
48
|
* Resolve the local app the stdio proxy should connect its MCP HTTP client
|
|
49
49
|
* to. Honours an explicit `--app` / appId and `--port` / explicit port.
|
|
50
|
-
* Returns the chosen app's origin (where `/
|
|
50
|
+
* Returns the chosen app's origin (where `/mcp` is mounted; the legacy
|
|
51
|
+
* `/_agent-native/mcp` alias is supported too).
|
|
51
52
|
*
|
|
52
53
|
* Order of precedence:
|
|
53
54
|
* 1. explicit `port` → http://127.0.0.1:<port>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-resolve.d.ts","sourceRoot":"","sources":["../../src/mcp/workspace-resolve.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAKH,MAAM,WAAW,WAA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AAI,CAwBjE;AAgFD;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,GAAG,GAAE,MAAsB,EAC3B,GAAG,GAAE,MAAM,CAAC,UAAwB,GACnC,OAAO,CAAC,iBAAiB,CAAC,CAkD5B;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CAAC,IAAI,EAAE;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,iBAAiB,CAAA;CAAE,CAAC,CA+BpE"}
|
|
@@ -171,7 +171,8 @@ export async function resolveWorkspace(cwd = process.cwd(), env = process.env) {
|
|
|
171
171
|
/**
|
|
172
172
|
* Resolve the local app the stdio proxy should connect its MCP HTTP client
|
|
173
173
|
* to. Honours an explicit `--app` / appId and `--port` / explicit port.
|
|
174
|
-
* Returns the chosen app's origin (where `/
|
|
174
|
+
* Returns the chosen app's origin (where `/mcp` is mounted; the legacy
|
|
175
|
+
* `/_agent-native/mcp` alias is supported too).
|
|
175
176
|
*
|
|
176
177
|
* Order of precedence:
|
|
177
178
|
* 1. explicit `port` → http://127.0.0.1:<port>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-resolve.js","sourceRoot":"","sources":["../../src/mcp/workspace-resolve.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAsB7B,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,oFAAoF;AACpF,MAAM,UAAU,iBAAiB,CAAC,QAAgB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CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,UAAU,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,QAAQ,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC;AACtD,CAAC","sourcesContent":["/**\n * Workspace / app resolution for the MCP stdio transport + builtin tools.\n *\n * Node-only. Never bundled into the serverless function — only the local\n * `agent-native mcp` CLI path and the in-process standalone builder use it.\n *\n * Resolution model (mirrors `cli/workspace-dev.ts`):\n *\n * - Workspace root = nearest ancestor whose package.json has\n * `agent-native.workspaceCore` set, with an `apps/` dir.\n * - Gateway = `http://127.0.0.1:<WORKSPACE_PORT|PORT|8080>`.\n * - Per-app ports = the gateway's `/_workspace/apps` JSON (authoritative,\n * accounts for port reservation when 8100+ are taken). Fallback when the\n * gateway isn't up yet: discover `apps/*` dirs and assign `8100 + index`\n * in the same sorted order `discoverApps` uses (dispatch first).\n * - Standalone (no workspace) = the single app at the cwd; dev server on\n * `PORT` (default Vite 5173 / framework dev). The app id is the package\n * name's last path segment.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface ResolvedApp {\n id: string;\n /** Local origin where this app's dev server listens, e.g. http://127.0.0.1:8100 */\n url: string;\n port: number;\n /** True when a TCP probe to the port succeeds. */\n running: boolean;\n}\n\nexport interface ResolvedWorkspace {\n /** Workspace root dir, or the standalone app dir. */\n root: string;\n /** True when `root` is a multi-app workspace (has apps/ + workspaceCore). */\n isWorkspace: boolean;\n /** Gateway origin (workspace) — undefined for standalone single app. */\n gatewayUrl?: string;\n /** Discovered apps. For standalone this is a single entry. */\n apps: ResolvedApp[];\n}\n\nconst DEFAULT_GATEWAY_PORT = 8080;\nconst DEFAULT_APP_PORT_START = 8100;\n\n/** Walk up from `startDir` for a package.json with `agent-native.workspaceCore`. */\nexport function findWorkspaceRoot(startDir: string): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const wsCore = pkg?.[\"agent-native\"]?.workspaceCore;\n if (\n typeof wsCore === \"string\" &&\n wsCore.length > 0 &&\n fs.existsSync(path.join(dir, \"apps\"))\n ) {\n return dir;\n }\n } catch {\n // ignore unparsable package.json and keep walking up\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\n/**\n * Mirror of `cli/workspace-dev.ts`'s `compareApps` — dispatch first, then\n * alphabetical. Keeps the fallback port assignment aligned with the gateway's.\n */\nfunction compareApps(a: { id: string }, b: { id: string }): number {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.id.localeCompare(b.id);\n}\n\nfunction discoverAppDirs(\n appsDir: string,\n appPortStart: number,\n): Array<{ id: string; port: number }> {\n if (!fs.existsSync(appsDir)) return [];\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(appsDir, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries\n .filter((e) => e.isDirectory())\n .map((e) => ({ id: e.name }))\n .filter((a) => fs.existsSync(path.join(appsDir, a.id, \"package.json\")))\n .sort(compareApps)\n .map((a, index) => ({ id: a.id, port: appPortStart + index }));\n}\n\nfunction probePort(port: number, timeoutMs = 600): Promise<boolean> {\n return new Promise((resolve) => {\n import(\"node:net\")\n .then(({ default: net }) => {\n const socket = new net.Socket();\n let done = false;\n const finish = (ok: boolean) => {\n if (done) return;\n done = true;\n socket.destroy();\n resolve(ok);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => finish(true));\n socket.once(\"error\", () => finish(false));\n socket.once(\"timeout\", () => finish(false));\n socket.connect(port, \"127.0.0.1\");\n })\n .catch(() => resolve(false));\n });\n}\n\n/** Fetch the gateway's authoritative apps list (ports may be reassigned). */\nasync function fetchGatewayApps(\n gatewayUrl: string,\n): Promise<Array<{ id: string; port: number }> | null> {\n try {\n const res = await fetch(`${gatewayUrl}/_workspace/apps`, {\n signal: AbortSignal.timeout(1500),\n });\n if (!res.ok) return null;\n const json = (await res.json()) as Array<{ id: string; port: number }>;\n if (!Array.isArray(json)) return null;\n return json\n .filter((a) => a && typeof a.id === \"string\")\n .map((a) => ({ id: a.id, port: Number(a.port) }));\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the workspace (or standalone app) the MCP server should bridge to.\n *\n * @param cwd Working directory (defaults to process.cwd()).\n * @param env Env (defaults to process.env). Reads WORKSPACE_PORT / PORT.\n */\nexport async function resolveWorkspace(\n cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n): Promise<ResolvedWorkspace> {\n const root = findWorkspaceRoot(cwd);\n\n if (root) {\n const gatewayPort = Number(\n env.WORKSPACE_PORT || env.PORT || DEFAULT_GATEWAY_PORT,\n );\n const gatewayHost = env.WORKSPACE_HOST || \"127.0.0.1\";\n const gatewayUrl = `http://${gatewayHost}:${gatewayPort}`;\n const appPortStart = Number(\n env.WORKSPACE_APP_PORT_START || DEFAULT_APP_PORT_START,\n );\n\n // Prefer the gateway's authoritative list (handles port reassignment);\n // fall back to a filesystem scan with the same ordering the gateway uses.\n const fromGateway = await fetchGatewayApps(gatewayUrl);\n const discovered =\n fromGateway ?? discoverAppDirs(path.join(root, \"apps\"), appPortStart);\n\n const apps: ResolvedApp[] = await Promise.all(\n discovered.map(async (a) => ({\n id: a.id,\n port: a.port,\n url: `http://127.0.0.1:${a.port}`,\n running: await probePort(a.port),\n })),\n );\n\n return { root, isWorkspace: true, gatewayUrl, apps };\n }\n\n // Standalone single app — the cwd is the app.\n const pkg = readJson(path.join(cwd, \"package.json\"));\n const rawName: string =\n (typeof pkg?.name === \"string\" && pkg.name) ||\n path.basename(path.resolve(cwd));\n const id = rawName.replace(/^@[^/]+\\//, \"\").replace(/^agent-native-/, \"\");\n const port = Number(env.PORT || 5173);\n return {\n root: path.resolve(cwd),\n isWorkspace: false,\n apps: [\n {\n id,\n port,\n url: `http://127.0.0.1:${port}`,\n running: await probePort(port),\n },\n ],\n };\n}\n\n/**\n * Resolve the local app the stdio proxy should connect its MCP HTTP client\n * to. Honours an explicit `--app` / appId and `--port` / explicit port.\n * Returns the chosen app's origin (where `/_agent-native/mcp` is mounted).\n *\n * Order of precedence:\n * 1. explicit `port` → http://127.0.0.1:<port>\n * 2. explicit `appId` matched against resolved apps\n * 3. workspace default (dispatch if present, else first app)\n * 4. standalone single app\n */\nexport async function resolveLocalAppOrigin(opts: {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n appId?: string;\n port?: number;\n}): Promise<{ origin: string; appId: string; ws: ResolvedWorkspace }> {\n const ws = await resolveWorkspace(opts.cwd, opts.env);\n\n if (opts.port) {\n const match = ws.apps.find((a) => a.port === opts.port);\n return {\n origin: `http://127.0.0.1:${opts.port}`,\n appId: match?.id ?? opts.appId ?? ws.apps[0]?.id ?? \"app\",\n ws,\n };\n }\n\n if (opts.appId) {\n const match = ws.apps.find((a) => a.id === opts.appId);\n if (match) return { origin: match.url, appId: match.id, ws };\n throw new Error(\n `App \"${opts.appId}\" not found. Available: ${\n ws.apps.map((a) => a.id).join(\", \") || \"(none)\"\n }`,\n );\n }\n\n if (ws.apps.length === 0) {\n throw new Error(\n \"No apps found. Run this from a workspace root (with apps/) or a single app directory.\",\n );\n }\n\n const dispatch = ws.apps.find((a) => a.id === \"dispatch\");\n const chosen = dispatch ?? ws.apps[0];\n return { origin: chosen.url, appId: chosen.id, ws };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workspace-resolve.js","sourceRoot":"","sources":["../../src/mcp/workspace-resolve.ts"],"names":[],"mappings":"AAAA;;;;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AI,CAAC,IAAI,QACzC,EAAE,CACH,CAAC;IACJ,CAAC;IAED,IAAI,EAAE,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF,CAAC;IACJ,CAAC;IAED,MAAM,QAAQ,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,UAAU,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,QAAQ,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACtC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC;AACtD,CAAC","sourcesContent":["/**\n * Workspace / app resolution for the MCP stdio transport + builtin tools.\n *\n * Node-only. Never bundled into the serverless function — only the local\n * `agent-native mcp` CLI path and the in-process standalone builder use it.\n *\n * Resolution model (mirrors `cli/workspace-dev.ts`):\n *\n * - Workspace root = nearest ancestor whose package.json has\n * `agent-native.workspaceCore` set, with an `apps/` dir.\n * - Gateway = `http://127.0.0.1:<WORKSPACE_PORT|PORT|8080>`.\n * - Per-app ports = the gateway's `/_workspace/apps` JSON (authoritative,\n * accounts for port reservation when 8100+ are taken). Fallback when the\n * gateway isn't up yet: discover `apps/*` dirs and assign `8100 + index`\n * in the same sorted order `discoverApps` uses (dispatch first).\n * - Standalone (no workspace) = the single app at the cwd; dev server on\n * `PORT` (default Vite 5173 / framework dev). The app id is the package\n * name's last path segment.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface ResolvedApp {\n id: string;\n /** Local origin where this app's dev server listens, e.g. http://127.0.0.1:8100 */\n url: string;\n port: number;\n /** True when a TCP probe to the port succeeds. */\n running: boolean;\n}\n\nexport interface ResolvedWorkspace {\n /** Workspace root dir, or the standalone app dir. */\n root: string;\n /** True when `root` is a multi-app workspace (has apps/ + workspaceCore). */\n isWorkspace: boolean;\n /** Gateway origin (workspace) — undefined for standalone single app. */\n gatewayUrl?: string;\n /** Discovered apps. For standalone this is a single entry. */\n apps: ResolvedApp[];\n}\n\nconst DEFAULT_GATEWAY_PORT = 8080;\nconst DEFAULT_APP_PORT_START = 8100;\n\n/** Walk up from `startDir` for a package.json with `agent-native.workspaceCore`. */\nexport function findWorkspaceRoot(startDir: string): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkgPath = path.join(dir, \"package.json\");\n if (fs.existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf-8\"));\n const wsCore = pkg?.[\"agent-native\"]?.workspaceCore;\n if (\n typeof wsCore === \"string\" &&\n wsCore.length > 0 &&\n fs.existsSync(path.join(dir, \"apps\"))\n ) {\n return dir;\n }\n } catch {\n // ignore unparsable package.json and keep walking up\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\n/**\n * Mirror of `cli/workspace-dev.ts`'s `compareApps` — dispatch first, then\n * alphabetical. Keeps the fallback port assignment aligned with the gateway's.\n */\nfunction compareApps(a: { id: string }, b: { id: string }): number {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.id.localeCompare(b.id);\n}\n\nfunction discoverAppDirs(\n appsDir: string,\n appPortStart: number,\n): Array<{ id: string; port: number }> {\n if (!fs.existsSync(appsDir)) return [];\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(appsDir, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries\n .filter((e) => e.isDirectory())\n .map((e) => ({ id: e.name }))\n .filter((a) => fs.existsSync(path.join(appsDir, a.id, \"package.json\")))\n .sort(compareApps)\n .map((a, index) => ({ id: a.id, port: appPortStart + index }));\n}\n\nfunction probePort(port: number, timeoutMs = 600): Promise<boolean> {\n return new Promise((resolve) => {\n import(\"node:net\")\n .then(({ default: net }) => {\n const socket = new net.Socket();\n let done = false;\n const finish = (ok: boolean) => {\n if (done) return;\n done = true;\n socket.destroy();\n resolve(ok);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"connect\", () => finish(true));\n socket.once(\"error\", () => finish(false));\n socket.once(\"timeout\", () => finish(false));\n socket.connect(port, \"127.0.0.1\");\n })\n .catch(() => resolve(false));\n });\n}\n\n/** Fetch the gateway's authoritative apps list (ports may be reassigned). */\nasync function fetchGatewayApps(\n gatewayUrl: string,\n): Promise<Array<{ id: string; port: number }> | null> {\n try {\n const res = await fetch(`${gatewayUrl}/_workspace/apps`, {\n signal: AbortSignal.timeout(1500),\n });\n if (!res.ok) return null;\n const json = (await res.json()) as Array<{ id: string; port: number }>;\n if (!Array.isArray(json)) return null;\n return json\n .filter((a) => a && typeof a.id === \"string\")\n .map((a) => ({ id: a.id, port: Number(a.port) }));\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the workspace (or standalone app) the MCP server should bridge to.\n *\n * @param cwd Working directory (defaults to process.cwd()).\n * @param env Env (defaults to process.env). Reads WORKSPACE_PORT / PORT.\n */\nexport async function resolveWorkspace(\n cwd: string = process.cwd(),\n env: NodeJS.ProcessEnv = process.env,\n): Promise<ResolvedWorkspace> {\n const root = findWorkspaceRoot(cwd);\n\n if (root) {\n const gatewayPort = Number(\n env.WORKSPACE_PORT || env.PORT || DEFAULT_GATEWAY_PORT,\n );\n const gatewayHost = env.WORKSPACE_HOST || \"127.0.0.1\";\n const gatewayUrl = `http://${gatewayHost}:${gatewayPort}`;\n const appPortStart = Number(\n env.WORKSPACE_APP_PORT_START || DEFAULT_APP_PORT_START,\n );\n\n // Prefer the gateway's authoritative list (handles port reassignment);\n // fall back to a filesystem scan with the same ordering the gateway uses.\n const fromGateway = await fetchGatewayApps(gatewayUrl);\n const discovered =\n fromGateway ?? discoverAppDirs(path.join(root, \"apps\"), appPortStart);\n\n const apps: ResolvedApp[] = await Promise.all(\n discovered.map(async (a) => ({\n id: a.id,\n port: a.port,\n url: `http://127.0.0.1:${a.port}`,\n running: await probePort(a.port),\n })),\n );\n\n return { root, isWorkspace: true, gatewayUrl, apps };\n }\n\n // Standalone single app — the cwd is the app.\n const pkg = readJson(path.join(cwd, \"package.json\"));\n const rawName: string =\n (typeof pkg?.name === \"string\" && pkg.name) ||\n path.basename(path.resolve(cwd));\n const id = rawName.replace(/^@[^/]+\\//, \"\").replace(/^agent-native-/, \"\");\n const port = Number(env.PORT || 5173);\n return {\n root: path.resolve(cwd),\n isWorkspace: false,\n apps: [\n {\n id,\n port,\n url: `http://127.0.0.1:${port}`,\n running: await probePort(port),\n },\n ],\n };\n}\n\n/**\n * Resolve the local app the stdio proxy should connect its MCP HTTP client\n * to. Honours an explicit `--app` / appId and `--port` / explicit port.\n * Returns the chosen app's origin (where `/mcp` is mounted; the legacy\n * `/_agent-native/mcp` alias is supported too).\n *\n * Order of precedence:\n * 1. explicit `port` → http://127.0.0.1:<port>\n * 2. explicit `appId` matched against resolved apps\n * 3. workspace default (dispatch if present, else first app)\n * 4. standalone single app\n */\nexport async function resolveLocalAppOrigin(opts: {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n appId?: string;\n port?: number;\n}): Promise<{ origin: string; appId: string; ws: ResolvedWorkspace }> {\n const ws = await resolveWorkspace(opts.cwd, opts.env);\n\n if (opts.port) {\n const match = ws.apps.find((a) => a.port === opts.port);\n return {\n origin: `http://127.0.0.1:${opts.port}`,\n appId: match?.id ?? opts.appId ?? ws.apps[0]?.id ?? \"app\",\n ws,\n };\n }\n\n if (opts.appId) {\n const match = ws.apps.find((a) => a.id === opts.appId);\n if (match) return { origin: match.url, appId: match.id, ws };\n throw new Error(\n `App \"${opts.appId}\" not found. Available: ${\n ws.apps.map((a) => a.id).join(\", \") || \"(none)\"\n }`,\n );\n }\n\n if (ws.apps.length === 0) {\n throw new Error(\n \"No apps found. Run this from a workspace root (with apps/) or a single app directory.\",\n );\n }\n\n const dispatch = ws.apps.find((a) => a.id === \"dispatch\");\n const chosen = dispatch ?? ws.apps[0];\n return { origin: chosen.url, appId: chosen.id, ws };\n}\n"]}
|
|
@@ -733,9 +733,12 @@ function firstPartyMcpAudienceForUrl(rawUrl) {
|
|
|
733
733
|
try {
|
|
734
734
|
const url = new URL(rawUrl);
|
|
735
735
|
const pathname = url.pathname.replace(/\/+$/, "");
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
736
|
+
if (pathname.endsWith("/_agent-native/mcp")) {
|
|
737
|
+
url.pathname = `${pathname.slice(0, -"/_agent-native/mcp".length)}/mcp`;
|
|
738
|
+
}
|
|
739
|
+
else {
|
|
740
|
+
url.pathname = pathname.endsWith("/mcp") ? pathname : `${pathname}/mcp`;
|
|
741
|
+
}
|
|
739
742
|
url.search = "";
|
|
740
743
|
url.hash = "";
|
|
741
744
|
return url.toString().replace(/\/+$/, "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/mcp-client/manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEvE,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,iCAAiC,EACjC,cAAc,GACf,MAAM,mBAAmB,CAAC;AAE3B,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC;AAoCvC,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,iBAAiB,CAAC,QAAgB,EAAE,QAAgB;IAC3D,OAAO,GAAG,eAAe,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,CAAC,CAAC,GAAG,QAAQ,oBAAoB,CAAC;QACpC,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * McpClientManager — connects to configured MCP servers (stdio or remote\n * Streamable HTTP), enumerates their tools, and exposes a flat tool registry\n * prefixed with `mcp__<server-id>__` so the agent's tool-use loop can call them.\n *\n * Stdio servers are a strict no-op in non-Node runtimes (Cloudflare Workers,\n * browsers). HTTP servers work in any runtime with `fetch`; `reconfigure()`\n * lets callers add or remove servers at runtime without restarting the process.\n */\n\nimport { MCP_APP_EXTENSION_ID, MCP_APP_MIME_TYPE } from \"../action.js\";\nimport type { McpConfig, McpServerConfig } from \"./config.js\";\nimport { formatMcpConnectError } from \"./errors.js\";\nimport {\n isFirstPartyRemoteEndpointTrusted,\n parseMergedKey,\n} from \"./remote-store.js\";\n\nexport const MCP_TOOL_PREFIX = \"mcp__\";\n\nexport interface McpTool {\n /** Server id the tool belongs to */\n source: string;\n /** Prefixed tool name (e.g. \"mcp__claude-in-chrome__navigate\") */\n name: string;\n /** Original name as reported by the MCP server */\n originalName: string;\n /** Human-readable description */\n description: string;\n /** JSON-Schema input spec forwarded verbatim from the server */\n inputSchema: Record<string, unknown>;\n /** Optional title as reported by the MCP server */\n title?: string;\n /** JSON-Schema output spec forwarded verbatim from the server */\n outputSchema?: Record<string, unknown>;\n /** MCP tool annotations forwarded verbatim from the server */\n annotations?: Record<string, unknown>;\n /** MCP metadata forwarded verbatim from the server */\n _meta?: Record<string, unknown>;\n /** Full raw tool object for extensions that depend on fields core does not know yet. */\n raw: Record<string, unknown>;\n}\n\ninterface ServerEntry {\n id: string;\n config: McpServerConfig;\n client: any | null;\n transport: any | null;\n tools: McpTool[];\n error?: string;\n}\n\ntype ErrorSink = (error: unknown) => void;\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 buildPrefixedName(serverId: string, toolName: string): string {\n return `${MCP_TOOL_PREFIX}${serverId}__${toolName}`;\n}\n\nexport function buildMcpToolName(serverId: string, toolName: string): string {\n return buildPrefixedName(serverId, toolName);\n}\n\n/**\n * Parse a prefixed tool name back into its server id and original tool name.\n * Returns `null` if the name doesn't match the MCP prefix convention.\n */\nexport function parseMcpToolName(\n prefixedName: string,\n): { serverId: string; toolName: string } | null {\n if (!prefixedName.startsWith(MCP_TOOL_PREFIX)) return null;\n const rest = prefixedName.slice(MCP_TOOL_PREFIX.length);\n const idx = rest.indexOf(\"__\");\n if (idx < 0) return null;\n return {\n serverId: rest.slice(0, idx),\n toolName: rest.slice(idx + 2),\n };\n}\n\nexport interface McpClientManagerOptions {\n /** Emit debug logs on startup */\n debug?: boolean;\n}\n\nfunction sameServerConfig(a: McpServerConfig, b: McpServerConfig): boolean {\n const typeA = a.type ?? \"stdio\";\n const typeB = b.type ?? \"stdio\";\n if (typeA !== typeB) return false;\n if (typeA === \"http\" && b.type === \"http\" && a.type === \"http\") {\n return (\n a.url === b.url &&\n JSON.stringify(a.headers ?? {}) === JSON.stringify(b.headers ?? {}) &&\n a.firstParty === b.firstParty &&\n a.firstPartyAppId === b.firstPartyAppId &&\n a.firstPartyOrgId === b.firstPartyOrgId\n );\n }\n if (a.type !== \"http\" && b.type !== \"http\") {\n return (\n a.command === b.command &&\n JSON.stringify(a.args ?? []) === JSON.stringify(b.args ?? []) &&\n JSON.stringify(a.env ?? {}) === JSON.stringify(b.env ?? {}) &&\n (a.cwd ?? \"\") === (b.cwd ?? \"\")\n );\n }\n return false;\n}\n\nasync function safelyClose(value: any, recordError?: ErrorSink): Promise<void> {\n try {\n if (value?.close) await value.close();\n } catch (err) {\n recordError?.(err);\n }\n}\n\nfunction guardClose(\n value: any,\n recordError: ErrorSink,\n): (() => void) | undefined {\n if (!value || typeof value.close !== \"function\") return undefined;\n const originalClose = value.close.bind(value);\n value.close = async (...args: unknown[]) => {\n try {\n return await originalClose(...args);\n } catch (err) {\n recordError(err);\n return undefined;\n }\n };\n return () => {\n value.close = originalClose;\n };\n}\n\ntype SdkModules = {\n Client: any;\n StdioClientTransport: any | null;\n StreamableHTTPClientTransport: any | null;\n};\n\nconst DEFAULT_MCP_CONNECT_TIMEOUT_MS = 5_000;\n\nfunction mcpConnectTimeoutMs(): number {\n const raw =\n typeof process !== \"undefined\"\n ? process.env.AGENT_NATIVE_MCP_CLIENT_CONNECT_TIMEOUT_MS ||\n process.env.MCP_CLIENT_CONNECT_TIMEOUT_MS\n : undefined;\n const parsed = raw ? Number(raw) : NaN;\n if (Number.isFinite(parsed) && parsed >= 0) return parsed;\n return DEFAULT_MCP_CONNECT_TIMEOUT_MS;\n}\n\nasync function withConnectTimeout<T>(\n work: Promise<T>,\n label: string,\n timeoutMs: number,\n): Promise<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return work;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`${label} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class McpClientManager {\n private readonly servers: Map<string, ServerEntry> = new Map();\n private readonly debug: boolean;\n private started = false;\n private config: McpConfig | null;\n private sdk: SdkModules | null = null;\n private readonly listeners: Set<() => void> = new Set();\n /** Serialises reconfigure()/start() — two concurrent callers would\n * otherwise race on `this.config` and on connect/disconnect ordering. */\n private reconfigureQueue: Promise<unknown> = Promise.resolve();\n\n constructor(config: McpConfig | null, options: McpClientManagerOptions = {}) {\n this.config = config;\n this.debug = !!options.debug;\n }\n\n /** True when the manager has any configured servers. */\n get enabled(): boolean {\n return !!this.config && Object.keys(this.config.servers).length > 0;\n }\n\n /** Return the current config (read-only snapshot for callers that need to\n * merge new servers into the existing set before calling reconfigure). */\n getConfig(): McpConfig | null {\n return this.config;\n }\n\n /** List of configured server ids (whether or not they're connected). */\n get configuredServers(): string[] {\n if (!this.config) return [];\n return Object.keys(this.config.servers);\n }\n\n /** List of server ids that successfully connected and enumerated tools. */\n get connectedServers(): string[] {\n return Array.from(this.servers.values())\n .filter((s) => s.client && !s.error)\n .map((s) => s.id);\n }\n\n /**\n * Load MCP SDK modules lazily so non-Node bundles don't pull them in.\n * Stdio transport is only loaded when a stdio server is actually configured.\n */\n private async loadSdk(needStdio: boolean): Promise<SdkModules | null> {\n if (this.sdk) {\n // If we previously loaded without stdio and now need it, top up.\n if (needStdio && !this.sdk.StdioClientTransport && isNode()) {\n try {\n const stdioMod =\n await import(\"@modelcontextprotocol/sdk/client/stdio.js\");\n this.sdk.StdioClientTransport = stdioMod.StdioClientTransport;\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to load stdio transport: ${err?.message ?? err}.`,\n );\n }\n }\n return this.sdk;\n }\n try {\n const clientMod =\n await import(\"@modelcontextprotocol/sdk/client/index.js\");\n const httpMod =\n await import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\");\n let StdioClientTransport: any = null;\n if (needStdio && isNode()) {\n try {\n const stdioMod =\n await import(\"@modelcontextprotocol/sdk/client/stdio.js\");\n StdioClientTransport = stdioMod.StdioClientTransport;\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to load stdio transport: ${err?.message ?? err}.`,\n );\n }\n }\n this.sdk = {\n Client: clientMod.Client,\n StdioClientTransport,\n StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,\n };\n return this.sdk;\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to load MCP SDK: ${err?.message ?? err}. MCP tools disabled.`,\n );\n return null;\n }\n }\n\n /**\n * Subscribe to tool-set changes (e.g. after `reconfigure()` adds/removes\n * servers). The listener is called *after* connect/disconnect completes.\n * Returns an unsubscribe function.\n */\n onChange(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n private emitChange(): void {\n for (const l of this.listeners) {\n try {\n l();\n } catch (err: any) {\n console.warn(\n `[mcp-client] onChange listener threw: ${err?.message ?? err}`,\n );\n }\n }\n }\n\n /**\n * Connect to each configured MCP server (stdio or http) and enumerate tools.\n * Individual server failures are logged and skipped — the manager stays\n * usable with whichever servers did come up.\n *\n * Queued against `reconfigure()` so a `reconfigure` that lands before\n * `start()` finishes can't race on `this.started` / `this.servers`.\n */\n async start(): Promise<void> {\n const task = this.reconfigureQueue.then(() => this.startInternal());\n this.reconfigureQueue = task.catch(() => {\n /* failures surface on the caller, not on the queue */\n });\n return task;\n }\n\n private async startInternal(): Promise<void> {\n if (this.started) return;\n this.started = true;\n if (!this.enabled) return;\n\n const needStdio = Object.values(this.config!.servers).some(\n (cfg) => (cfg.type ?? \"stdio\") === \"stdio\",\n );\n const sdk = await this.loadSdk(needStdio);\n if (!sdk) return;\n\n const entries = Object.entries(this.config!.servers);\n await Promise.all(\n entries.map(async ([id, cfg]) => this.addServer(id, cfg, sdk)),\n );\n this.emitChange();\n }\n\n /**\n * Create a new ServerEntry and attempt to connect. Logs and records errors\n * on the entry rather than throwing — callers iterate many servers.\n */\n private async addServer(\n id: string,\n cfg: McpServerConfig,\n sdk: SdkModules,\n ): Promise<void> {\n if (this.servers.has(id)) {\n console.warn(\n `[mcp-client] Duplicate server ID '${id}' — overwriting previous registration`,\n );\n }\n const entry: ServerEntry = {\n id,\n config: cfg,\n client: null,\n transport: null,\n tools: [],\n };\n this.servers.set(id, entry);\n try {\n await this.connectServer(entry, sdk);\n console.log(\n `[mcp-client] connected to ${id}: ${entry.tools.length} tools`,\n );\n } catch (err: any) {\n entry.error = formatMcpConnectError(err);\n console.warn(`[mcp-client] failed to connect to ${id}: ${entry.error}`);\n }\n }\n\n private async connectServer(\n entry: ServerEntry,\n sdk: SdkModules,\n ): Promise<void> {\n const cfg = entry.config;\n const { Client } = sdk;\n\n let transport: any;\n if (cfg.type === \"http\") {\n if (!sdk.StreamableHTTPClientTransport) {\n throw new Error(\"HTTP transport not available\");\n }\n const requestInit: Record<string, unknown> = {};\n const staticHeaders = { ...(cfg.headers ?? {}) };\n const transportOptions: Record<string, unknown> = { requestInit };\n if (this.shouldInjectFirstPartyIdentity(entry)) {\n const baselineHeaders = { ...staticHeaders };\n removeAuthorizationHeaders(baselineHeaders);\n if (Object.keys(baselineHeaders).length > 0) {\n requestInit.headers = baselineHeaders;\n }\n if (typeof fetch === \"function\") {\n const nativeFetch = fetch.bind(globalThis);\n transportOptions.fetch = async (input: unknown, init?: unknown) =>\n nativeFetch(\n input as Parameters<typeof fetch>[0],\n await buildFirstPartyRequestInit(\n staticHeaders,\n init,\n this.firstPartyTrust(entry),\n ),\n );\n }\n } else if (Object.keys(staticHeaders).length > 0) {\n requestInit.headers = staticHeaders;\n }\n transport = new sdk.StreamableHTTPClientTransport(\n new URL(cfg.url),\n transportOptions,\n );\n } else {\n if (!sdk.StdioClientTransport) {\n throw new Error(\n \"Stdio transport not available (needs Node runtime with MCP SDK)\",\n );\n }\n const { command, args = [], env, cwd } = cfg;\n // SECURITY: stdio MCP servers run as child processes that inherit\n // their environment from us. We previously merged the entire\n // `process.env` into the child, which exposed every deployment\n // secret (A2A_SECRET, ANTHROPIC_API_KEY, BUILDER_PRIVATE_KEY, all\n // database URLs, all platform tokens) to any MCP server in\n // `mcp.config.json` — a malicious npx-fetched server could exfil\n // them by reading its own env. Instead, only forward a minimal\n // baseline plus the keys explicitly listed in `cfg.env`. See\n // finding #10 in /tmp/security-audit/12-mcp-a2a-agent.md.\n const ENV_ALLOWLIST = [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"USER\",\n \"SHELL\",\n ];\n const baseline: Record<string, string> = {};\n for (const k of ENV_ALLOWLIST) {\n const v = process.env[k];\n if (typeof v === \"string\") baseline[k] = v;\n }\n const mergedEnv = env ? { ...baseline, ...env } : baseline;\n transport = new sdk.StdioClientTransport({\n command,\n args,\n env: mergedEnv as Record<string, string>,\n cwd,\n });\n }\n\n const client = new Client(\n { name: \"agent-native-mcp-client\", version: \"1.0.0\" },\n {\n capabilities: {\n extensions: {\n [MCP_APP_EXTENSION_ID]: {\n mimeTypes: [MCP_APP_MIME_TYPE],\n },\n },\n },\n } as any,\n );\n const recordConnectionError: ErrorSink = () => {};\n const restoreClientClose = guardClose(client, recordConnectionError);\n const restoreTransportClose = guardClose(transport, recordConnectionError);\n client.onerror = recordConnectionError;\n // Attach a transport-level error handler before connect() so the SDK's\n // internal fire-and-forget paths (initial SSE stream open, scheduled\n // reconnects, message-handler-triggered reconnects — see processStream()\n // in @modelcontextprotocol/sdk/client/streamableHttp.js) cannot leak as\n // unhandled promise rejections. On AWS Lambda the long-lived socket\n // gets reaped ~60s after the function returns; without this handler the\n // resulting `socket hang up` surfaces as an unhandledRejection and\n // pollutes Sentry. Client.connect() chains its own onerror on top of\n // ours (see protocol.js: const _onerror = transport.onerror; ...).\n transport.onerror = recordConnectionError;\n\n // If connect or listTools throws, we still need to release the child\n // process (stdio) or pending HTTP session — otherwise repeated failures\n // leak transports. Assign to the entry only after the handshake succeeds.\n try {\n const timeoutMs = mcpConnectTimeoutMs();\n await withConnectTimeout(\n Promise.resolve(client.connect(transport)),\n `MCP server ${entry.id} connect`,\n timeoutMs,\n );\n const listed = await withConnectTimeout(\n Promise.resolve(client.listTools()),\n `MCP server ${entry.id} tools/list`,\n timeoutMs,\n );\n const rawTools: Array<{\n name: string;\n title?: string;\n description?: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n }> = (listed?.tools ?? []) as any[];\n\n entry.client = client;\n entry.transport = transport;\n entry.tools = rawTools.map((t) => ({\n source: entry.id,\n name: buildPrefixedName(entry.id, t.name),\n originalName: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description ?? t.name,\n inputSchema: (t.inputSchema ?? {\n type: \"object\",\n properties: {},\n }) as Record<string, unknown>,\n ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),\n ...(t.annotations ? { annotations: t.annotations } : {}),\n ...(t._meta ? { _meta: t._meta } : {}),\n raw: { ...t },\n }));\n client.onerror = (error: unknown) => {\n entry.error = formatMcpConnectError(error);\n if (this.debug) {\n console.warn(\n `[mcp-client] runtime error from ${entry.id}: ${entry.error}`,\n );\n }\n };\n } catch (err) {\n await safelyClose(client, recordConnectionError);\n await safelyClose(transport, recordConnectionError);\n throw err;\n } finally {\n restoreClientClose?.();\n restoreTransportClose?.();\n }\n }\n\n /**\n * Replace the configured server set. Servers that appear in the new config\n * under a different shape are reconnected; unchanged entries stay live;\n * removed entries are disconnected. Safe to call while `start()` is in\n * flight or after it has completed.\n *\n * Serialised against `start()` and any other `reconfigure()` call via the\n * internal queue — two concurrent mutations would otherwise interleave on\n * `this.config` and on connect/disconnect ordering.\n *\n * Returns a summary describing what happened for logging / UI feedback.\n */\n async reconfigure(newConfig: McpConfig | null): Promise<{\n added: string[];\n removed: string[];\n unchanged: string[];\n reconnected: string[];\n }> {\n const task = this.reconfigureQueue.then(() =>\n this.reconfigureInternal(newConfig),\n );\n this.reconfigureQueue = task.catch(() => {\n /* failures surface on the caller, not on the queue */\n });\n return task;\n }\n\n private async reconfigureInternal(newConfig: McpConfig | null): Promise<{\n added: string[];\n removed: string[];\n unchanged: string[];\n reconnected: string[];\n }> {\n const prev = this.config;\n this.config = newConfig;\n\n const prevServers = prev?.servers ?? {};\n const nextServers = newConfig?.servers ?? {};\n\n const added: string[] = [];\n const removed: string[] = [];\n const unchanged: string[] = [];\n const reconnected: string[] = [];\n\n // Remove entries that vanished or changed shape.\n for (const id of Object.keys(prevServers)) {\n if (!(id in nextServers)) {\n removed.push(id);\n } else if (!sameServerConfig(prevServers[id], nextServers[id])) {\n reconnected.push(id);\n } else {\n const entry = this.servers.get(id);\n if (entry?.error) reconnected.push(id);\n else unchanged.push(id);\n }\n }\n for (const id of Object.keys(nextServers)) {\n if (!(id in prevServers)) added.push(id);\n }\n\n const toDisconnect = [...removed, ...reconnected];\n await Promise.all(\n toDisconnect.map(async (id) => {\n const entry = this.servers.get(id);\n if (!entry) return;\n this.servers.delete(id);\n try {\n if (entry.client?.close) await entry.client.close();\n } catch {\n // ignore\n }\n try {\n if (entry.transport?.close) await entry.transport.close();\n } catch {\n // ignore\n }\n }),\n );\n\n const toConnect = [...added, ...reconnected];\n if (toConnect.length > 0) {\n const needStdio = toConnect.some(\n (id) => (nextServers[id].type ?? \"stdio\") === \"stdio\",\n );\n const sdk = await this.loadSdk(needStdio);\n if (sdk) {\n await Promise.all(\n toConnect.map((id) => this.addServer(id, nextServers[id], sdk)),\n );\n }\n }\n\n // If the manager was never started (e.g. empty initial config) but now has\n // servers, mark it started so subsequent start() calls don't duplicate work.\n if (!this.started && Object.keys(nextServers).length > 0) {\n this.started = true;\n }\n\n this.emitChange();\n return { added, removed, unchanged, reconnected };\n }\n\n /** Flattened tool list across all connected servers. */\n getTools(): McpTool[] {\n if (!this.enabled) return [];\n const out: McpTool[] = [];\n for (const entry of this.servers.values()) {\n for (const tool of entry.tools) out.push(tool);\n }\n return out;\n }\n\n getTool(prefixedName: string): McpTool | null {\n const parsed = parseMcpToolName(prefixedName);\n if (!parsed) return null;\n const entry = this.servers.get(parsed.serverId);\n return entry?.tools.find((t) => t.name === prefixedName) ?? null;\n }\n\n getToolsForServer(serverId: string): McpTool[] {\n return [...(this.servers.get(serverId)?.tools ?? [])];\n }\n\n hasServer(serverId: string): boolean {\n const entry = this.servers.get(serverId);\n return !!entry?.client && !entry.error;\n }\n\n /**\n * Invoke an MCP tool by prefixed name. Routes to the owning server based on\n * the `mcp__<serverId>__` prefix.\n */\n async callTool(prefixedName: string, args: unknown): Promise<unknown> {\n const parsed = parseMcpToolName(prefixedName);\n if (!parsed) {\n throw new Error(\n `Tool name \"${prefixedName}\" does not look like an MCP tool (expected mcp__<server>__<tool>)`,\n );\n }\n const entry = this.servers.get(parsed.serverId);\n if (!entry || !entry.client) {\n throw new Error(\n `MCP server \"${parsed.serverId}\" is not connected${\n entry?.error ? `: ${entry.error}` : \"\"\n }`,\n );\n }\n // Look up the tool so we fail loud for unknown names instead of forwarding\n // garbage through to the server.\n const known = entry.tools.find((t) => t.name === prefixedName);\n if (!known) {\n throw new Error(\n `MCP server \"${parsed.serverId}\" does not expose tool \"${parsed.toolName}\"`,\n );\n }\n const result = await entry.client.callTool({\n name: parsed.toolName,\n arguments:\n args && typeof args === \"object\"\n ? (args as Record<string, unknown>)\n : {},\n });\n return result;\n }\n\n async readResource(serverId: string, uri: string): Promise<unknown> {\n if (!uri.startsWith(\"ui://\")) {\n throw new Error(`Only ui:// MCP App resources can be read by this host`);\n }\n const entry = this.servers.get(serverId);\n if (!entry || !entry.client) {\n throw new Error(\n `MCP server \"${serverId}\" is not connected${\n entry?.error ? `: ${entry.error}` : \"\"\n }`,\n );\n }\n if (typeof entry.client.readResource === \"function\") {\n return entry.client.readResource({ uri });\n }\n if (typeof entry.client.request === \"function\") {\n return entry.client.request({\n method: \"resources/read\",\n params: { uri },\n });\n }\n throw new Error(`MCP server \"${serverId}\" does not support resources/read`);\n }\n\n async readResourceForTool(\n prefixedName: string,\n uri: string,\n ): Promise<unknown> {\n const parsed = parseMcpToolName(prefixedName);\n if (!parsed) {\n throw new Error(\n `Tool name \"${prefixedName}\" does not look like an MCP tool (expected mcp__<server>__<tool>)`,\n );\n }\n return this.readResource(parsed.serverId, uri);\n }\n\n /** Cleanly close all MCP clients and child processes. */\n async stop(): Promise<void> {\n const entries = Array.from(this.servers.values());\n this.servers.clear();\n this.started = false;\n await Promise.all(\n entries.map(async (entry) => {\n try {\n if (entry.client?.close) await entry.client.close();\n } catch {\n // ignore\n }\n try {\n if (entry.transport?.close) await entry.transport.close();\n } catch {\n // ignore\n }\n }),\n );\n }\n\n /** Diagnostic snapshot used by `/_agent-native/mcp/status`. */\n getStatus(): {\n configuredServers: string[];\n connectedServers: string[];\n totalTools: number;\n tools: Array<{ source: string; name: string; description: string }>;\n errors: Record<string, string>;\n } {\n const tools = this.getTools().map((t) => ({\n source: t.source,\n name: t.name,\n description: t.description,\n }));\n const errors: Record<string, string> = {};\n for (const entry of this.servers.values()) {\n if (entry.error) errors[entry.id] = entry.error;\n }\n return {\n configuredServers: this.configuredServers,\n connectedServers: this.connectedServers,\n totalTools: tools.length,\n tools,\n errors,\n };\n }\n\n private shouldInjectFirstPartyIdentity(entry: ServerEntry): boolean {\n return this.firstPartyTrust(entry) !== null;\n }\n\n private firstPartyTrust(\n entry: ServerEntry,\n ): { orgId: string; appId: string; url: string } | null {\n if (entry.config.type !== \"http\" || entry.config.firstParty !== true) {\n return null;\n }\n const parsed = parseMergedKey(entry.id);\n if (parsed?.scope !== \"org\") return null;\n return {\n orgId: entry.config.firstPartyOrgId ?? parsed.owner,\n appId: entry.config.firstPartyAppId ?? parsed.name,\n url: entry.config.url,\n };\n }\n}\n\nfunction removeAuthorizationHeaders(headers: Record<string, string>): void {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === \"authorization\") delete headers[key];\n }\n}\n\nfunction headersToRecord(value: unknown): Record<string, string> {\n if (!value) return {};\n if (typeof Headers !== \"undefined\" && value instanceof Headers) {\n return Object.fromEntries(value.entries());\n }\n if (Array.isArray(value)) {\n return Object.fromEntries(\n value\n .filter((entry) => Array.isArray(entry) && entry.length >= 2)\n .map(([key, headerValue]) => [String(key), String(headerValue)]),\n );\n }\n if (typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(\n ([key, headerValue]) => [key, String(headerValue)],\n ),\n );\n }\n return {};\n}\n\nasync function buildFirstPartyRequestInit(\n staticHeaders: Record<string, string>,\n rawInit: unknown,\n trust: { orgId: string; appId: string; url: string } | null,\n): Promise<RequestInit> {\n const init =\n rawInit && typeof rawInit === \"object\" ? (rawInit as RequestInit) : {};\n const headers = {\n ...headersToRecord(staticHeaders),\n ...headersToRecord(init.headers),\n };\n removeAuthorizationHeaders(headers);\n const token = await mintFirstPartyMcpIdentityToken(trust).catch(() => null);\n if (token) headers.Authorization = `Bearer ${token}`;\n headers[\"x-agent-native-mcp-inline-apps\"] = \"1\";\n return { ...init, headers };\n}\n\nfunction randomJti(): string {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\nconst FIRST_PARTY_TRUST_TTL_MS = 60_000;\nconst FIRST_PARTY_TRUST_FAILURE_TTL_MS = 10_000;\nconst ORG_SIGNING_CONTEXT_TTL_MS = 60_000;\n\nconst firstPartyTrustCache = new Map<\n string,\n { ok: boolean; expiresAt: number }\n>();\nconst orgSigningContextCache = new Map<\n string,\n { orgDomain?: string; orgSecret?: string; expiresAt: number }\n>();\n\nasync function isFirstPartyTrustCached(trust: {\n orgId: string;\n appId: string;\n url: string;\n}): Promise<boolean> {\n const key = `${trust.orgId}\\n${trust.appId}\\n${trust.url}`;\n const cached = firstPartyTrustCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.ok;\n const result = await isFirstPartyRemoteEndpointTrusted(\n trust.orgId,\n trust.appId,\n trust.url,\n );\n const ok = result.ok === true;\n firstPartyTrustCache.set(key, {\n ok,\n expiresAt:\n Date.now() +\n (ok ? FIRST_PARTY_TRUST_TTL_MS : FIRST_PARTY_TRUST_FAILURE_TTL_MS),\n });\n return ok;\n}\n\nasync function resolveOrgSigningContext(orgId: string): Promise<{\n orgDomain?: string;\n orgSecret?: string;\n}> {\n const cached = orgSigningContextCache.get(orgId);\n if (cached && cached.expiresAt > Date.now()) {\n return { orgDomain: cached.orgDomain, orgSecret: cached.orgSecret };\n }\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(orgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {\n // Global A2A_SECRET remains the hosted/common path.\n }\n orgSigningContextCache.set(orgId, {\n orgDomain,\n orgSecret,\n expiresAt: Date.now() + ORG_SIGNING_CONTEXT_TTL_MS,\n });\n return { orgDomain, orgSecret };\n}\n\nasync function mintFirstPartyMcpIdentityToken(\n trust: { orgId: string; appId: string; url: string } | null,\n): Promise<string | null> {\n if (!trust) return null;\n const [{ getRequestOrgId, getRequestUserEmail }, { signA2AToken }] =\n await Promise.all([\n import(\"../server/request-context.js\"),\n import(\"../a2a/client.js\"),\n ]);\n const userEmail = getRequestUserEmail();\n const requestOrgId = getRequestOrgId();\n if (requestOrgId && requestOrgId !== trust.orgId) {\n return null;\n }\n const orgId = requestOrgId ?? trust.orgId;\n if (!orgId) return null;\n if (!(await isFirstPartyTrustCached({ ...trust, orgId }))) return null;\n\n const { orgDomain, orgSecret } = await resolveOrgSigningContext(orgId);\n const subject =\n userEmail && requestOrgId\n ? userEmail\n : (await import(\"../mcp/connect-store.js\")).serviceIdentityEmail(\n \"mcp-client\",\n orgId,\n );\n\n return signA2AToken(subject, orgDomain, orgSecret, {\n expiresIn: \"5m\",\n audience: firstPartyMcpAudienceForUrl(trust.url),\n preferGlobalSecret: !orgSecret,\n extraClaims: {\n jti: randomJti(),\n scope: \"mcp-connect\",\n org_id: orgId,\n agent_native_first_party_mcp: true,\n },\n });\n}\n\nfunction firstPartyMcpAudienceForUrl(rawUrl: string): string | undefined {\n try {\n const url = new URL(rawUrl);\n const pathname = url.pathname.replace(/\\/+$/, \"\");\n url.pathname = pathname.endsWith(\"/_agent-native/mcp\")\n ? pathname\n : `${pathname}/_agent-native/mcp`;\n url.search = \"\";\n url.hash = \"\";\n return url.toString().replace(/\\/+$/, \"\");\n } catch {\n return undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/mc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Q,EAAE,2BAA2B,CAAC,KAAK,CAAC,GAAG,CAAC;QAChD,kBAAkB,EAAE,CAAC,SAAS;QAC9B,WAAW,EAAE;YACX,GAAG,EAAE,SAAS,EAAE;YAChB,KAAK,EAAE,aAAa;YACpB,MAAM,EAAE,KAAK;YACb,4BAA4B,EAAE,IAAI;SACnC;KACF,CAAC,CAAC;AACL,CAAC;AAED,SAAS,2BAA2B,CAAC,MAAc;IACjD,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;QAC5B,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,QAAQ,CAAC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,CAAC;YAC5C,GAAG,CAAC,QAAQ,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,oBAAoB,CAAC,MAAM,CAAC,MAAM,CAAC;QAC1E,CAAC;aAAM,CAAC;YACN,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,MAAM,CAAC;QAC1E,CAAC;QACD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * McpClientManager — connects to configured MCP servers (stdio or remote\n * Streamable HTTP), enumerates their tools, and exposes a flat tool registry\n * prefixed with `mcp__<server-id>__` so the agent's tool-use loop can call them.\n *\n * Stdio servers are a strict no-op in non-Node runtimes (Cloudflare Workers,\n * browsers). HTTP servers work in any runtime with `fetch`; `reconfigure()`\n * lets callers add or remove servers at runtime without restarting the process.\n */\n\nimport { MCP_APP_EXTENSION_ID, MCP_APP_MIME_TYPE } from \"../action.js\";\nimport type { McpConfig, McpServerConfig } from \"./config.js\";\nimport { formatMcpConnectError } from \"./errors.js\";\nimport {\n isFirstPartyRemoteEndpointTrusted,\n parseMergedKey,\n} from \"./remote-store.js\";\n\nexport const MCP_TOOL_PREFIX = \"mcp__\";\n\nexport interface McpTool {\n /** Server id the tool belongs to */\n source: string;\n /** Prefixed tool name (e.g. \"mcp__claude-in-chrome__navigate\") */\n name: string;\n /** Original name as reported by the MCP server */\n originalName: string;\n /** Human-readable description */\n description: string;\n /** JSON-Schema input spec forwarded verbatim from the server */\n inputSchema: Record<string, unknown>;\n /** Optional title as reported by the MCP server */\n title?: string;\n /** JSON-Schema output spec forwarded verbatim from the server */\n outputSchema?: Record<string, unknown>;\n /** MCP tool annotations forwarded verbatim from the server */\n annotations?: Record<string, unknown>;\n /** MCP metadata forwarded verbatim from the server */\n _meta?: Record<string, unknown>;\n /** Full raw tool object for extensions that depend on fields core does not know yet. */\n raw: Record<string, unknown>;\n}\n\ninterface ServerEntry {\n id: string;\n config: McpServerConfig;\n client: any | null;\n transport: any | null;\n tools: McpTool[];\n error?: string;\n}\n\ntype ErrorSink = (error: unknown) => void;\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 buildPrefixedName(serverId: string, toolName: string): string {\n return `${MCP_TOOL_PREFIX}${serverId}__${toolName}`;\n}\n\nexport function buildMcpToolName(serverId: string, toolName: string): string {\n return buildPrefixedName(serverId, toolName);\n}\n\n/**\n * Parse a prefixed tool name back into its server id and original tool name.\n * Returns `null` if the name doesn't match the MCP prefix convention.\n */\nexport function parseMcpToolName(\n prefixedName: string,\n): { serverId: string; toolName: string } | null {\n if (!prefixedName.startsWith(MCP_TOOL_PREFIX)) return null;\n const rest = prefixedName.slice(MCP_TOOL_PREFIX.length);\n const idx = rest.indexOf(\"__\");\n if (idx < 0) return null;\n return {\n serverId: rest.slice(0, idx),\n toolName: rest.slice(idx + 2),\n };\n}\n\nexport interface McpClientManagerOptions {\n /** Emit debug logs on startup */\n debug?: boolean;\n}\n\nfunction sameServerConfig(a: McpServerConfig, b: McpServerConfig): boolean {\n const typeA = a.type ?? \"stdio\";\n const typeB = b.type ?? \"stdio\";\n if (typeA !== typeB) return false;\n if (typeA === \"http\" && b.type === \"http\" && a.type === \"http\") {\n return (\n a.url === b.url &&\n JSON.stringify(a.headers ?? {}) === JSON.stringify(b.headers ?? {}) &&\n a.firstParty === b.firstParty &&\n a.firstPartyAppId === b.firstPartyAppId &&\n a.firstPartyOrgId === b.firstPartyOrgId\n );\n }\n if (a.type !== \"http\" && b.type !== \"http\") {\n return (\n a.command === b.command &&\n JSON.stringify(a.args ?? []) === JSON.stringify(b.args ?? []) &&\n JSON.stringify(a.env ?? {}) === JSON.stringify(b.env ?? {}) &&\n (a.cwd ?? \"\") === (b.cwd ?? \"\")\n );\n }\n return false;\n}\n\nasync function safelyClose(value: any, recordError?: ErrorSink): Promise<void> {\n try {\n if (value?.close) await value.close();\n } catch (err) {\n recordError?.(err);\n }\n}\n\nfunction guardClose(\n value: any,\n recordError: ErrorSink,\n): (() => void) | undefined {\n if (!value || typeof value.close !== \"function\") return undefined;\n const originalClose = value.close.bind(value);\n value.close = async (...args: unknown[]) => {\n try {\n return await originalClose(...args);\n } catch (err) {\n recordError(err);\n return undefined;\n }\n };\n return () => {\n value.close = originalClose;\n };\n}\n\ntype SdkModules = {\n Client: any;\n StdioClientTransport: any | null;\n StreamableHTTPClientTransport: any | null;\n};\n\nconst DEFAULT_MCP_CONNECT_TIMEOUT_MS = 5_000;\n\nfunction mcpConnectTimeoutMs(): number {\n const raw =\n typeof process !== \"undefined\"\n ? process.env.AGENT_NATIVE_MCP_CLIENT_CONNECT_TIMEOUT_MS ||\n process.env.MCP_CLIENT_CONNECT_TIMEOUT_MS\n : undefined;\n const parsed = raw ? Number(raw) : NaN;\n if (Number.isFinite(parsed) && parsed >= 0) return parsed;\n return DEFAULT_MCP_CONNECT_TIMEOUT_MS;\n}\n\nasync function withConnectTimeout<T>(\n work: Promise<T>,\n label: string,\n timeoutMs: number,\n): Promise<T> {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return work;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`${label} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class McpClientManager {\n private readonly servers: Map<string, ServerEntry> = new Map();\n private readonly debug: boolean;\n private started = false;\n private config: McpConfig | null;\n private sdk: SdkModules | null = null;\n private readonly listeners: Set<() => void> = new Set();\n /** Serialises reconfigure()/start() — two concurrent callers would\n * otherwise race on `this.config` and on connect/disconnect ordering. */\n private reconfigureQueue: Promise<unknown> = Promise.resolve();\n\n constructor(config: McpConfig | null, options: McpClientManagerOptions = {}) {\n this.config = config;\n this.debug = !!options.debug;\n }\n\n /** True when the manager has any configured servers. */\n get enabled(): boolean {\n return !!this.config && Object.keys(this.config.servers).length > 0;\n }\n\n /** Return the current config (read-only snapshot for callers that need to\n * merge new servers into the existing set before calling reconfigure). */\n getConfig(): McpConfig | null {\n return this.config;\n }\n\n /** List of configured server ids (whether or not they're connected). */\n get configuredServers(): string[] {\n if (!this.config) return [];\n return Object.keys(this.config.servers);\n }\n\n /** List of server ids that successfully connected and enumerated tools. */\n get connectedServers(): string[] {\n return Array.from(this.servers.values())\n .filter((s) => s.client && !s.error)\n .map((s) => s.id);\n }\n\n /**\n * Load MCP SDK modules lazily so non-Node bundles don't pull them in.\n * Stdio transport is only loaded when a stdio server is actually configured.\n */\n private async loadSdk(needStdio: boolean): Promise<SdkModules | null> {\n if (this.sdk) {\n // If we previously loaded without stdio and now need it, top up.\n if (needStdio && !this.sdk.StdioClientTransport && isNode()) {\n try {\n const stdioMod =\n await import(\"@modelcontextprotocol/sdk/client/stdio.js\");\n this.sdk.StdioClientTransport = stdioMod.StdioClientTransport;\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to load stdio transport: ${err?.message ?? err}.`,\n );\n }\n }\n return this.sdk;\n }\n try {\n const clientMod =\n await import(\"@modelcontextprotocol/sdk/client/index.js\");\n const httpMod =\n await import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\");\n let StdioClientTransport: any = null;\n if (needStdio && isNode()) {\n try {\n const stdioMod =\n await import(\"@modelcontextprotocol/sdk/client/stdio.js\");\n StdioClientTransport = stdioMod.StdioClientTransport;\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to load stdio transport: ${err?.message ?? err}.`,\n );\n }\n }\n this.sdk = {\n Client: clientMod.Client,\n StdioClientTransport,\n StreamableHTTPClientTransport: httpMod.StreamableHTTPClientTransport,\n };\n return this.sdk;\n } catch (err: any) {\n console.warn(\n `[mcp-client] Failed to load MCP SDK: ${err?.message ?? err}. MCP tools disabled.`,\n );\n return null;\n }\n }\n\n /**\n * Subscribe to tool-set changes (e.g. after `reconfigure()` adds/removes\n * servers). The listener is called *after* connect/disconnect completes.\n * Returns an unsubscribe function.\n */\n onChange(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n private emitChange(): void {\n for (const l of this.listeners) {\n try {\n l();\n } catch (err: any) {\n console.warn(\n `[mcp-client] onChange listener threw: ${err?.message ?? err}`,\n );\n }\n }\n }\n\n /**\n * Connect to each configured MCP server (stdio or http) and enumerate tools.\n * Individual server failures are logged and skipped — the manager stays\n * usable with whichever servers did come up.\n *\n * Queued against `reconfigure()` so a `reconfigure` that lands before\n * `start()` finishes can't race on `this.started` / `this.servers`.\n */\n async start(): Promise<void> {\n const task = this.reconfigureQueue.then(() => this.startInternal());\n this.reconfigureQueue = task.catch(() => {\n /* failures surface on the caller, not on the queue */\n });\n return task;\n }\n\n private async startInternal(): Promise<void> {\n if (this.started) return;\n this.started = true;\n if (!this.enabled) return;\n\n const needStdio = Object.values(this.config!.servers).some(\n (cfg) => (cfg.type ?? \"stdio\") === \"stdio\",\n );\n const sdk = await this.loadSdk(needStdio);\n if (!sdk) return;\n\n const entries = Object.entries(this.config!.servers);\n await Promise.all(\n entries.map(async ([id, cfg]) => this.addServer(id, cfg, sdk)),\n );\n this.emitChange();\n }\n\n /**\n * Create a new ServerEntry and attempt to connect. Logs and records errors\n * on the entry rather than throwing — callers iterate many servers.\n */\n private async addServer(\n id: string,\n cfg: McpServerConfig,\n sdk: SdkModules,\n ): Promise<void> {\n if (this.servers.has(id)) {\n console.warn(\n `[mcp-client] Duplicate server ID '${id}' — overwriting previous registration`,\n );\n }\n const entry: ServerEntry = {\n id,\n config: cfg,\n client: null,\n transport: null,\n tools: [],\n };\n this.servers.set(id, entry);\n try {\n await this.connectServer(entry, sdk);\n console.log(\n `[mcp-client] connected to ${id}: ${entry.tools.length} tools`,\n );\n } catch (err: any) {\n entry.error = formatMcpConnectError(err);\n console.warn(`[mcp-client] failed to connect to ${id}: ${entry.error}`);\n }\n }\n\n private async connectServer(\n entry: ServerEntry,\n sdk: SdkModules,\n ): Promise<void> {\n const cfg = entry.config;\n const { Client } = sdk;\n\n let transport: any;\n if (cfg.type === \"http\") {\n if (!sdk.StreamableHTTPClientTransport) {\n throw new Error(\"HTTP transport not available\");\n }\n const requestInit: Record<string, unknown> = {};\n const staticHeaders = { ...(cfg.headers ?? {}) };\n const transportOptions: Record<string, unknown> = { requestInit };\n if (this.shouldInjectFirstPartyIdentity(entry)) {\n const baselineHeaders = { ...staticHeaders };\n removeAuthorizationHeaders(baselineHeaders);\n if (Object.keys(baselineHeaders).length > 0) {\n requestInit.headers = baselineHeaders;\n }\n if (typeof fetch === \"function\") {\n const nativeFetch = fetch.bind(globalThis);\n transportOptions.fetch = async (input: unknown, init?: unknown) =>\n nativeFetch(\n input as Parameters<typeof fetch>[0],\n await buildFirstPartyRequestInit(\n staticHeaders,\n init,\n this.firstPartyTrust(entry),\n ),\n );\n }\n } else if (Object.keys(staticHeaders).length > 0) {\n requestInit.headers = staticHeaders;\n }\n transport = new sdk.StreamableHTTPClientTransport(\n new URL(cfg.url),\n transportOptions,\n );\n } else {\n if (!sdk.StdioClientTransport) {\n throw new Error(\n \"Stdio transport not available (needs Node runtime with MCP SDK)\",\n );\n }\n const { command, args = [], env, cwd } = cfg;\n // SECURITY: stdio MCP servers run as child processes that inherit\n // their environment from us. We previously merged the entire\n // `process.env` into the child, which exposed every deployment\n // secret (A2A_SECRET, ANTHROPIC_API_KEY, BUILDER_PRIVATE_KEY, all\n // database URLs, all platform tokens) to any MCP server in\n // `mcp.config.json` — a malicious npx-fetched server could exfil\n // them by reading its own env. Instead, only forward a minimal\n // baseline plus the keys explicitly listed in `cfg.env`. See\n // finding #10 in /tmp/security-audit/12-mcp-a2a-agent.md.\n const ENV_ALLOWLIST = [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"USER\",\n \"SHELL\",\n ];\n const baseline: Record<string, string> = {};\n for (const k of ENV_ALLOWLIST) {\n const v = process.env[k];\n if (typeof v === \"string\") baseline[k] = v;\n }\n const mergedEnv = env ? { ...baseline, ...env } : baseline;\n transport = new sdk.StdioClientTransport({\n command,\n args,\n env: mergedEnv as Record<string, string>,\n cwd,\n });\n }\n\n const client = new Client(\n { name: \"agent-native-mcp-client\", version: \"1.0.0\" },\n {\n capabilities: {\n extensions: {\n [MCP_APP_EXTENSION_ID]: {\n mimeTypes: [MCP_APP_MIME_TYPE],\n },\n },\n },\n } as any,\n );\n const recordConnectionError: ErrorSink = () => {};\n const restoreClientClose = guardClose(client, recordConnectionError);\n const restoreTransportClose = guardClose(transport, recordConnectionError);\n client.onerror = recordConnectionError;\n // Attach a transport-level error handler before connect() so the SDK's\n // internal fire-and-forget paths (initial SSE stream open, scheduled\n // reconnects, message-handler-triggered reconnects — see processStream()\n // in @modelcontextprotocol/sdk/client/streamableHttp.js) cannot leak as\n // unhandled promise rejections. On AWS Lambda the long-lived socket\n // gets reaped ~60s after the function returns; without this handler the\n // resulting `socket hang up` surfaces as an unhandledRejection and\n // pollutes Sentry. Client.connect() chains its own onerror on top of\n // ours (see protocol.js: const _onerror = transport.onerror; ...).\n transport.onerror = recordConnectionError;\n\n // If connect or listTools throws, we still need to release the child\n // process (stdio) or pending HTTP session — otherwise repeated failures\n // leak transports. Assign to the entry only after the handshake succeeds.\n try {\n const timeoutMs = mcpConnectTimeoutMs();\n await withConnectTimeout(\n Promise.resolve(client.connect(transport)),\n `MCP server ${entry.id} connect`,\n timeoutMs,\n );\n const listed = await withConnectTimeout(\n Promise.resolve(client.listTools()),\n `MCP server ${entry.id} tools/list`,\n timeoutMs,\n );\n const rawTools: Array<{\n name: string;\n title?: string;\n description?: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n }> = (listed?.tools ?? []) as any[];\n\n entry.client = client;\n entry.transport = transport;\n entry.tools = rawTools.map((t) => ({\n source: entry.id,\n name: buildPrefixedName(entry.id, t.name),\n originalName: t.name,\n ...(t.title ? { title: t.title } : {}),\n description: t.description ?? t.name,\n inputSchema: (t.inputSchema ?? {\n type: \"object\",\n properties: {},\n }) as Record<string, unknown>,\n ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),\n ...(t.annotations ? { annotations: t.annotations } : {}),\n ...(t._meta ? { _meta: t._meta } : {}),\n raw: { ...t },\n }));\n client.onerror = (error: unknown) => {\n entry.error = formatMcpConnectError(error);\n if (this.debug) {\n console.warn(\n `[mcp-client] runtime error from ${entry.id}: ${entry.error}`,\n );\n }\n };\n } catch (err) {\n await safelyClose(client, recordConnectionError);\n await safelyClose(transport, recordConnectionError);\n throw err;\n } finally {\n restoreClientClose?.();\n restoreTransportClose?.();\n }\n }\n\n /**\n * Replace the configured server set. Servers that appear in the new config\n * under a different shape are reconnected; unchanged entries stay live;\n * removed entries are disconnected. Safe to call while `start()` is in\n * flight or after it has completed.\n *\n * Serialised against `start()` and any other `reconfigure()` call via the\n * internal queue — two concurrent mutations would otherwise interleave on\n * `this.config` and on connect/disconnect ordering.\n *\n * Returns a summary describing what happened for logging / UI feedback.\n */\n async reconfigure(newConfig: McpConfig | null): Promise<{\n added: string[];\n removed: string[];\n unchanged: string[];\n reconnected: string[];\n }> {\n const task = this.reconfigureQueue.then(() =>\n this.reconfigureInternal(newConfig),\n );\n this.reconfigureQueue = task.catch(() => {\n /* failures surface on the caller, not on the queue */\n });\n return task;\n }\n\n private async reconfigureInternal(newConfig: McpConfig | null): Promise<{\n added: string[];\n removed: string[];\n unchanged: string[];\n reconnected: string[];\n }> {\n const prev = this.config;\n this.config = newConfig;\n\n const prevServers = prev?.servers ?? {};\n const nextServers = newConfig?.servers ?? {};\n\n const added: string[] = [];\n const removed: string[] = [];\n const unchanged: string[] = [];\n const reconnected: string[] = [];\n\n // Remove entries that vanished or changed shape.\n for (const id of Object.keys(prevServers)) {\n if (!(id in nextServers)) {\n removed.push(id);\n } else if (!sameServerConfig(prevServers[id], nextServers[id])) {\n reconnected.push(id);\n } else {\n const entry = this.servers.get(id);\n if (entry?.error) reconnected.push(id);\n else unchanged.push(id);\n }\n }\n for (const id of Object.keys(nextServers)) {\n if (!(id in prevServers)) added.push(id);\n }\n\n const toDisconnect = [...removed, ...reconnected];\n await Promise.all(\n toDisconnect.map(async (id) => {\n const entry = this.servers.get(id);\n if (!entry) return;\n this.servers.delete(id);\n try {\n if (entry.client?.close) await entry.client.close();\n } catch {\n // ignore\n }\n try {\n if (entry.transport?.close) await entry.transport.close();\n } catch {\n // ignore\n }\n }),\n );\n\n const toConnect = [...added, ...reconnected];\n if (toConnect.length > 0) {\n const needStdio = toConnect.some(\n (id) => (nextServers[id].type ?? \"stdio\") === \"stdio\",\n );\n const sdk = await this.loadSdk(needStdio);\n if (sdk) {\n await Promise.all(\n toConnect.map((id) => this.addServer(id, nextServers[id], sdk)),\n );\n }\n }\n\n // If the manager was never started (e.g. empty initial config) but now has\n // servers, mark it started so subsequent start() calls don't duplicate work.\n if (!this.started && Object.keys(nextServers).length > 0) {\n this.started = true;\n }\n\n this.emitChange();\n return { added, removed, unchanged, reconnected };\n }\n\n /** Flattened tool list across all connected servers. */\n getTools(): McpTool[] {\n if (!this.enabled) return [];\n const out: McpTool[] = [];\n for (const entry of this.servers.values()) {\n for (const tool of entry.tools) out.push(tool);\n }\n return out;\n }\n\n getTool(prefixedName: string): McpTool | null {\n const parsed = parseMcpToolName(prefixedName);\n if (!parsed) return null;\n const entry = this.servers.get(parsed.serverId);\n return entry?.tools.find((t) => t.name === prefixedName) ?? null;\n }\n\n getToolsForServer(serverId: string): McpTool[] {\n return [...(this.servers.get(serverId)?.tools ?? [])];\n }\n\n hasServer(serverId: string): boolean {\n const entry = this.servers.get(serverId);\n return !!entry?.client && !entry.error;\n }\n\n /**\n * Invoke an MCP tool by prefixed name. Routes to the owning server based on\n * the `mcp__<serverId>__` prefix.\n */\n async callTool(prefixedName: string, args: unknown): Promise<unknown> {\n const parsed = parseMcpToolName(prefixedName);\n if (!parsed) {\n throw new Error(\n `Tool name \"${prefixedName}\" does not look like an MCP tool (expected mcp__<server>__<tool>)`,\n );\n }\n const entry = this.servers.get(parsed.serverId);\n if (!entry || !entry.client) {\n throw new Error(\n `MCP server \"${parsed.serverId}\" is not connected${\n entry?.error ? `: ${entry.error}` : \"\"\n }`,\n );\n }\n // Look up the tool so we fail loud for unknown names instead of forwarding\n // garbage through to the server.\n const known = entry.tools.find((t) => t.name === prefixedName);\n if (!known) {\n throw new Error(\n `MCP server \"${parsed.serverId}\" does not expose tool \"${parsed.toolName}\"`,\n );\n }\n const result = await entry.client.callTool({\n name: parsed.toolName,\n arguments:\n args && typeof args === \"object\"\n ? (args as Record<string, unknown>)\n : {},\n });\n return result;\n }\n\n async readResource(serverId: string, uri: string): Promise<unknown> {\n if (!uri.startsWith(\"ui://\")) {\n throw new Error(`Only ui:// MCP App resources can be read by this host`);\n }\n const entry = this.servers.get(serverId);\n if (!entry || !entry.client) {\n throw new Error(\n `MCP server \"${serverId}\" is not connected${\n entry?.error ? `: ${entry.error}` : \"\"\n }`,\n );\n }\n if (typeof entry.client.readResource === \"function\") {\n return entry.client.readResource({ uri });\n }\n if (typeof entry.client.request === \"function\") {\n return entry.client.request({\n method: \"resources/read\",\n params: { uri },\n });\n }\n throw new Error(`MCP server \"${serverId}\" does not support resources/read`);\n }\n\n async readResourceForTool(\n prefixedName: string,\n uri: string,\n ): Promise<unknown> {\n const parsed = parseMcpToolName(prefixedName);\n if (!parsed) {\n throw new Error(\n `Tool name \"${prefixedName}\" does not look like an MCP tool (expected mcp__<server>__<tool>)`,\n );\n }\n return this.readResource(parsed.serverId, uri);\n }\n\n /** Cleanly close all MCP clients and child processes. */\n async stop(): Promise<void> {\n const entries = Array.from(this.servers.values());\n this.servers.clear();\n this.started = false;\n await Promise.all(\n entries.map(async (entry) => {\n try {\n if (entry.client?.close) await entry.client.close();\n } catch {\n // ignore\n }\n try {\n if (entry.transport?.close) await entry.transport.close();\n } catch {\n // ignore\n }\n }),\n );\n }\n\n /** Diagnostic snapshot used by `/_agent-native/mcp/status`. */\n getStatus(): {\n configuredServers: string[];\n connectedServers: string[];\n totalTools: number;\n tools: Array<{ source: string; name: string; description: string }>;\n errors: Record<string, string>;\n } {\n const tools = this.getTools().map((t) => ({\n source: t.source,\n name: t.name,\n description: t.description,\n }));\n const errors: Record<string, string> = {};\n for (const entry of this.servers.values()) {\n if (entry.error) errors[entry.id] = entry.error;\n }\n return {\n configuredServers: this.configuredServers,\n connectedServers: this.connectedServers,\n totalTools: tools.length,\n tools,\n errors,\n };\n }\n\n private shouldInjectFirstPartyIdentity(entry: ServerEntry): boolean {\n return this.firstPartyTrust(entry) !== null;\n }\n\n private firstPartyTrust(\n entry: ServerEntry,\n ): { orgId: string; appId: string; url: string } | null {\n if (entry.config.type !== \"http\" || entry.config.firstParty !== true) {\n return null;\n }\n const parsed = parseMergedKey(entry.id);\n if (parsed?.scope !== \"org\") return null;\n return {\n orgId: entry.config.firstPartyOrgId ?? parsed.owner,\n appId: entry.config.firstPartyAppId ?? parsed.name,\n url: entry.config.url,\n };\n }\n}\n\nfunction removeAuthorizationHeaders(headers: Record<string, string>): void {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === \"authorization\") delete headers[key];\n }\n}\n\nfunction headersToRecord(value: unknown): Record<string, string> {\n if (!value) return {};\n if (typeof Headers !== \"undefined\" && value instanceof Headers) {\n return Object.fromEntries(value.entries());\n }\n if (Array.isArray(value)) {\n return Object.fromEntries(\n value\n .filter((entry) => Array.isArray(entry) && entry.length >= 2)\n .map(([key, headerValue]) => [String(key), String(headerValue)]),\n );\n }\n if (typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(\n ([key, headerValue]) => [key, String(headerValue)],\n ),\n );\n }\n return {};\n}\n\nasync function buildFirstPartyRequestInit(\n staticHeaders: Record<string, string>,\n rawInit: unknown,\n trust: { orgId: string; appId: string; url: string } | null,\n): Promise<RequestInit> {\n const init =\n rawInit && typeof rawInit === \"object\" ? (rawInit as RequestInit) : {};\n const headers = {\n ...headersToRecord(staticHeaders),\n ...headersToRecord(init.headers),\n };\n removeAuthorizationHeaders(headers);\n const token = await mintFirstPartyMcpIdentityToken(trust).catch(() => null);\n if (token) headers.Authorization = `Bearer ${token}`;\n headers[\"x-agent-native-mcp-inline-apps\"] = \"1\";\n return { ...init, headers };\n}\n\nfunction randomJti(): string {\n return (\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n );\n}\n\nconst FIRST_PARTY_TRUST_TTL_MS = 60_000;\nconst FIRST_PARTY_TRUST_FAILURE_TTL_MS = 10_000;\nconst ORG_SIGNING_CONTEXT_TTL_MS = 60_000;\n\nconst firstPartyTrustCache = new Map<\n string,\n { ok: boolean; expiresAt: number }\n>();\nconst orgSigningContextCache = new Map<\n string,\n { orgDomain?: string; orgSecret?: string; expiresAt: number }\n>();\n\nasync function isFirstPartyTrustCached(trust: {\n orgId: string;\n appId: string;\n url: string;\n}): Promise<boolean> {\n const key = `${trust.orgId}\\n${trust.appId}\\n${trust.url}`;\n const cached = firstPartyTrustCache.get(key);\n if (cached && cached.expiresAt > Date.now()) return cached.ok;\n const result = await isFirstPartyRemoteEndpointTrusted(\n trust.orgId,\n trust.appId,\n trust.url,\n );\n const ok = result.ok === true;\n firstPartyTrustCache.set(key, {\n ok,\n expiresAt:\n Date.now() +\n (ok ? FIRST_PARTY_TRUST_TTL_MS : FIRST_PARTY_TRUST_FAILURE_TTL_MS),\n });\n return ok;\n}\n\nasync function resolveOrgSigningContext(orgId: string): Promise<{\n orgDomain?: string;\n orgSecret?: string;\n}> {\n const cached = orgSigningContextCache.get(orgId);\n if (cached && cached.expiresAt > Date.now()) {\n return { orgDomain: cached.orgDomain, orgSecret: cached.orgSecret };\n }\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(orgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {\n // Global A2A_SECRET remains the hosted/common path.\n }\n orgSigningContextCache.set(orgId, {\n orgDomain,\n orgSecret,\n expiresAt: Date.now() + ORG_SIGNING_CONTEXT_TTL_MS,\n });\n return { orgDomain, orgSecret };\n}\n\nasync function mintFirstPartyMcpIdentityToken(\n trust: { orgId: string; appId: string; url: string } | null,\n): Promise<string | null> {\n if (!trust) return null;\n const [{ getRequestOrgId, getRequestUserEmail }, { signA2AToken }] =\n await Promise.all([\n import(\"../server/request-context.js\"),\n import(\"../a2a/client.js\"),\n ]);\n const userEmail = getRequestUserEmail();\n const requestOrgId = getRequestOrgId();\n if (requestOrgId && requestOrgId !== trust.orgId) {\n return null;\n }\n const orgId = requestOrgId ?? trust.orgId;\n if (!orgId) return null;\n if (!(await isFirstPartyTrustCached({ ...trust, orgId }))) return null;\n\n const { orgDomain, orgSecret } = await resolveOrgSigningContext(orgId);\n const subject =\n userEmail && requestOrgId\n ? userEmail\n : (await import(\"../mcp/connect-store.js\")).serviceIdentityEmail(\n \"mcp-client\",\n orgId,\n );\n\n return signA2AToken(subject, orgDomain, orgSecret, {\n expiresIn: \"5m\",\n audience: firstPartyMcpAudienceForUrl(trust.url),\n preferGlobalSecret: !orgSecret,\n extraClaims: {\n jti: randomJti(),\n scope: \"mcp-connect\",\n org_id: orgId,\n agent_native_first_party_mcp: true,\n },\n });\n}\n\nfunction firstPartyMcpAudienceForUrl(rawUrl: string): string | undefined {\n try {\n const url = new URL(rawUrl);\n const pathname = url.pathname.replace(/\\/+$/, \"\");\n if (pathname.endsWith(\"/_agent-native/mcp\")) {\n url.pathname = `${pathname.slice(0, -\"/_agent-native/mcp\".length)}/mcp`;\n } else {\n url.pathname = pathname.endsWith(\"/mcp\") ? pathname : `${pathname}/mcp`;\n }\n url.search = \"\";\n url.hash = \"\";\n return url.toString().replace(/\\/+$/, \"\");\n } catch {\n return undefined;\n }\n}\n"]}
|