@agent-native/core 0.98.17 → 0.99.1
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 +25 -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/agent/production-agent.ts +21 -0
- 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/pr-visual-recap-workflow.ts +1 -1
- 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/analytics.ts +13 -0
- 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/action-filters-a2a.ts +13 -0
- package/corpus/core/src/server/agent-chat-plugin.ts +42 -9
- package/corpus/core/src/server/agent-teams.ts +17 -0
- 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 +12 -2
- 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/assets/replay-cursor.svg +17 -0
- package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +4 -3
- package/corpus/templates/analytics/app/global.css +71 -4
- package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/DashboardFilterBar.tsx +32 -4
- package/corpus/templates/analytics/app/pages/monitoring/errors/IssueDetail.tsx +1 -1
- package/corpus/templates/analytics/app/pages/sessions/SessionDetailPage.tsx +49 -11
- package/corpus/templates/analytics/app/pages/sessions/SessionsPage.tsx +4 -6
- package/corpus/templates/analytics/changelog/2026-07-13-all-time-dashboard-filters-no-longer-send-invalid-dates-to-b.md +6 -0
- 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-error-issue-titles-wrap-instead-of-overflowing.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-13-saving-a-new-dashboard-view-no-longer-fails-with-a-server-er.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-13-session-replay-cursors-stay-hidden-until-their-first-recorde.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-13-session-replay-links-now-support-cmd-click-and-middle-click-.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/lib/dashboards-store.ts +43 -4
- package/corpus/templates/analytics/server/lib/error-capture.ts +24 -5
- package/corpus/templates/analytics/server/plugins/agent-chat.ts +5 -0
- 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/library/recording-card.tsx +27 -26
- package/corpus/templates/clips/app/components/library/space-card.tsx +4 -6
- 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/app/components/sidebar/DocumentSidebar.tsx +18 -16
- 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/agent/production-agent.d.ts +9 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +12 -0
- package/dist/agent/production-agent.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/pr-visual-recap-workflow.d.ts +1 -1
- package/dist/cli/pr-visual-recap-workflow.d.ts.map +1 -1
- package/dist/cli/pr-visual-recap-workflow.js +1 -1
- package/dist/cli/pr-visual-recap-workflow.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/analytics.d.ts.map +1 -1
- package/dist/client/analytics.js +11 -0
- package/dist/client/analytics.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/routes.d.ts +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 +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 +2 -2
- package/dist/server/agent-chat/action-filters-a2a.d.ts.map +1 -1
- package/dist/server/agent-chat/action-filters-a2a.js +11 -1
- package/dist/server/agent-chat/action-filters-a2a.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +43 -11
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/agent-teams.d.ts.map +1 -1
- package/dist/server/agent-teams.js +15 -1
- package/dist/server/agent-teams.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 +11 -2
- 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/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 +2 -2
- 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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-route.js","sourceRoot":"","sources":["../../src/mcp/oauth-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGtE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAEvE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,gBAAgB,EAChB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAO1B,SAAS,IAAI,CAAC,IAAa,EAAE,MAAM,GAAG,GAAG;IACvC,OAAO,IAAI,QAAQ,CAAC,IAAI,CA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AAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC7D,IAAI,CAAC;QACH,IAAI,IAAI,KAAK,WAAW;YAAE,OAAO,MAAM,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACvE,IAAI,IAAI,KAAK,OAAO;YAAE,OAAO,MAAM,WAAW,CAAC,KAAK,CAAC,CAAC;QACtD,IAAI,IAAI,KAAK,UAAU;YAAE,OAAO,MAAM,cAAc,CAAC,KAAK,CAAC,CAAC;QAC5D,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAC9B,OAAO,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,GAAG,CAAC,CAAC;IAC3C,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,OAAO,UAAU,CACf,cAAc,EACd,GAAG,EAAE,OAAO,IAAI,sBAAsB,EACtC,GAAG,CACJ,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Standard remote MCP OAuth 2.1 endpoints.\n *\n * These routes let MCP hosts such as Claude Code and ChatGPT authenticate\n * through their native remote-MCP OAuth flow instead of pasting bearer tokens.\n * The issued access tokens are audience-bound to `/_agent-native/mcp`, carry\n * the same user/org identity as the existing connect flow, and are mediated by\n * `verifyAuth` before any MCP tool/resource request runs.\n */\n\nimport { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type { H3Event } from \"h3\";\nimport { getHeader, getMethod, getQuery, setResponseStatus } from \"h3\";\n\nimport { getOrgDomain } from \"../org/context.js\";\nimport { getConfiguredLoginHtml, getSession } from \"../server/auth.js\";\nimport { getAuthSecret } from \"../server/better-auth-instance.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n createOAuthCode,\n createOAuthRefreshToken,\n consumeOAuthCode,\n generateOpaqueToken,\n getOAuthClient,\n getOAuthCode,\n getOAuthRefreshToken,\n registerOAuthClient,\n touchOAuthRefreshToken,\n} from \"./oauth-store.js\";\nimport {\n MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,\n MCP_OAUTH_DEFAULT_SCOPE,\n MCP_OAUTH_SCOPES,\n normalizeOAuthScope,\n signMcpOAuthAccessToken,\n} from \"./oauth-token.js\";\n\nexport interface McpOAuthRouteOptions {\n appId?: string;\n appName?: string;\n}\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\",\n },\n });\n}\n\nfunction html(body: string, status = 200): Response {\n return new Response(body, {\n status,\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nfunction redirect(location: string): Response {\n return new Response(null, {\n status: 302,\n headers: { Location: location, \"Cache-Control\": \"no-store\" },\n });\n}\n\nfunction isSameOriginPost(event: H3Event): boolean {\n const origin = getHeader(event, \"origin\");\n if (!origin) return true;\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer) return false;\n try {\n return new URL(origin).origin === new URL(issuer).origin;\n } catch {\n return false;\n }\n}\n\nfunction oauthError(\n error: string,\n description: string,\n status = 400,\n): Response {\n return json({ error, error_description: description }, status);\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\nfunction normalizeBasePath(raw: string | undefined): string {\n const trimmed = (raw ?? \"\").trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n const withSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n return withSlash.replace(/\\/+$/, \"\");\n}\n\nfunction configuredBasePath(): string {\n return normalizeBasePath(\n process.env.APP_BASE_PATH || process.env.VITE_APP_BASE_PATH,\n );\n}\n\nfunction stripTrailingSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction configuredPublicBaseUrl(): string | undefined {\n for (const key of [\n \"WORKSPACE_OAUTH_ORIGIN\",\n \"VITE_WORKSPACE_OAUTH_ORIGIN\",\n \"APP_URL\",\n \"VITE_APP_URL\",\n \"BETTER_AUTH_URL\",\n \"VITE_BETTER_AUTH_URL\",\n ]) {\n const raw = process.env[key]?.trim();\n if (!raw) continue;\n try {\n const url = new URL(raw);\n url.search = \"\";\n url.hash = \"\";\n return stripTrailingSlash(`${url.origin}${url.pathname}`);\n } catch {\n // Ignore invalid operator-provided URL values and fall back to headers.\n }\n }\n return undefined;\n}\n\nfunction appendConfiguredBasePath(baseUrl: string): string {\n const basePath = configuredBasePath();\n if (!basePath) return stripTrailingSlash(baseUrl);\n try {\n const url = new URL(baseUrl);\n const pathname = normalizeBasePath(url.pathname);\n if (pathname === basePath || pathname.endsWith(`${basePath}`)) {\n return stripTrailingSlash(`${url.origin}${pathname}`);\n }\n return stripTrailingSlash(`${url.origin}${pathname}${basePath}`);\n } catch {\n return `${stripTrailingSlash(baseUrl)}${basePath}`;\n }\n}\n\nfunction deriveOrigin(event: H3Event): string {\n const forwardedProto = getHeader(event, \"x-forwarded-proto\");\n const host = getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:|$)/.test(host)\n ? \"http\"\n : \"https\");\n return host ? `${proto}://${host}` : \"\";\n}\n\nexport function getMcpOAuthIssuer(event: H3Event): string | undefined {\n const baseUrl = configuredPublicBaseUrl() || deriveOrigin(event);\n if (!baseUrl) return undefined;\n return appendConfiguredBasePath(baseUrl);\n}\n\nexport function getMcpOAuthResource(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer) return undefined;\n return `${issuer}/_agent-native/mcp`;\n}\n\n/**\n * All plausible MCP OAuth resource audiences for the given request, deduped.\n *\n * When a configured public base URL differs from the request-derived origin\n * (e.g. during Netlify deploy-preview or behind a reverse proxy), a token\n * minted against the configured URL must still verify against the request-\n * derived URL and vice-versa. Returns both so `verifyMcpOAuthAccessToken`\n * accepts either without issuing a 401.\n */\nexport function getMcpOAuthAudiences(event: H3Event): string[] {\n const derived = getMcpOAuthResource(event);\n const configured = (() => {\n const base = configuredPublicBaseUrl();\n if (!base) return undefined;\n // Re-apply base path if present so the configured resource is also\n // base-path-aware, consistent with how getMcpOAuthResource computes it.\n const withPath = appendConfiguredBasePath(base);\n return `${withPath}/_agent-native/mcp`;\n })();\n const seen = new Set<string>();\n const out: string[] = [];\n for (const r of [derived, configured]) {\n const n = r?.replace(/\\/+$/, \"\");\n if (n && !seen.has(n)) {\n seen.add(n);\n out.push(n);\n }\n }\n return out;\n}\n\nexport function getMcpOAuthProtectedResourceMetadataUrl(\n event: H3Event,\n): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer) return undefined;\n return `${issuer}/.well-known/oauth-protected-resource`;\n}\n\nexport function buildMcpOAuthChallenge(event: H3Event): string {\n const metadata = getMcpOAuthProtectedResourceMetadataUrl(event);\n const scope = MCP_OAUTH_DEFAULT_SCOPE;\n return metadata\n ? `Bearer resource_metadata=\"${metadata}\", scope=\"${scope}\"`\n : `Bearer scope=\"${scope}\"`;\n}\n\nfunction authorizationEndpoint(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n return issuer ? `${issuer}/_agent-native/mcp/oauth/authorize` : undefined;\n}\n\nfunction tokenEndpoint(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n return issuer ? `${issuer}/_agent-native/mcp/oauth/token` : undefined;\n}\n\nfunction registrationEndpoint(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n return issuer ? `${issuer}/_agent-native/mcp/oauth/register` : undefined;\n}\n\nexport function handleMcpOAuthProtectedResourceMetadata(\n event: H3Event,\n): Response {\n if (getMethod(event) !== \"GET\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const resource = getMcpOAuthResource(event);\n const issuer = getMcpOAuthIssuer(event);\n if (!resource || !issuer) {\n return oauthError(\"server_error\", \"Unable to derive MCP resource\", 500);\n }\n return json({\n resource,\n authorization_servers: [issuer],\n scopes_supported: MCP_OAUTH_SCOPES,\n resource_documentation: issuer,\n });\n}\n\nexport function handleMcpOAuthAuthorizationServerMetadata(\n event: H3Event,\n): Response {\n if (getMethod(event) !== \"GET\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const issuer = getMcpOAuthIssuer(event);\n const authorize = authorizationEndpoint(event);\n const token = tokenEndpoint(event);\n const register = registrationEndpoint(event);\n if (!issuer || !authorize || !token || !register) {\n return oauthError(\"server_error\", \"Unable to derive OAuth endpoints\", 500);\n }\n return json({\n issuer,\n authorization_endpoint: authorize,\n token_endpoint: token,\n registration_endpoint: register,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"none\"],\n scopes_supported: MCP_OAUTH_SCOPES,\n });\n}\n\n// Schemes that must never be accepted as a redirect target: they can execute\n// script or read local resources if a redirect is ever rendered in a browser\n// or webview context.\nconst DISALLOWED_REDIRECT_SCHEMES = new Set([\n \"javascript:\",\n \"data:\",\n \"vbscript:\",\n \"file:\",\n \"blob:\",\n \"about:\",\n]);\n\n// Native/desktop IDE clients (Cursor, VS Code, …) register a private-use URI\n// scheme callback such as `cursor://` or `vscode://` (RFC 8252 §7.1) instead of\n// an https/loopback URL. The authorization code is bound by PKCE (S256), so\n// delivering it through a client-registered app scheme is safe.\nfunction isPrivateUseRedirectScheme(protocol: string): boolean {\n if (DISALLOWED_REDIRECT_SCHEMES.has(protocol)) return false;\n // RFC 3986 scheme grammar: ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" ), with a\n // trailing \":\" from URL.protocol. Require a non-http(s) custom scheme here;\n // http/https are handled explicitly above.\n return /^[a-z][a-z0-9+.-]*:$/.test(protocol);\n}\n\nfunction isAllowedRedirectUri(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 2048) return false;\n try {\n const url = new URL(value);\n if (url.hash) return false;\n if (url.username || url.password) return false;\n if (url.protocol === \"https:\") return true;\n if (url.protocol === \"http:\") {\n return (\n url.hostname === \"localhost\" ||\n url.hostname === \"127.0.0.1\" ||\n url.hostname === \"::1\" ||\n url.hostname === \"[::1]\"\n );\n }\n return isPrivateUseRedirectScheme(url.protocol);\n } catch {\n return false;\n }\n}\n\nfunction parseStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === \"string\")\n : [];\n}\n\nasync function handleRegister(event: H3Event): Promise<Response> {\n if (getMethod(event) !== \"POST\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const body = ((await readBody(event).catch(() => ({}))) ?? {}) as Record<\n string,\n unknown\n >;\n const redirectUris = parseStringArray(body.redirect_uris);\n if (\n redirectUris.length === 0 ||\n redirectUris.length > 20 ||\n !redirectUris.every(isAllowedRedirectUri)\n ) {\n return oauthError(\n \"invalid_client_metadata\",\n \"redirect_uris must contain valid HTTPS or localhost callback URLs\",\n );\n }\n\n const grantTypes = parseStringArray(body.grant_types);\n if (\n grantTypes.length &&\n !grantTypes.every(\n (g) => g === \"authorization_code\" || g === \"refresh_token\",\n )\n ) {\n return oauthError(\"invalid_client_metadata\", \"Unsupported grant_type\");\n }\n const responseTypes = parseStringArray(body.response_types);\n if (responseTypes.length && !responseTypes.every((r) => r === \"code\")) {\n return oauthError(\"invalid_client_metadata\", \"Unsupported response_type\");\n }\n const method =\n typeof body.token_endpoint_auth_method === \"string\"\n ? body.token_endpoint_auth_method\n : \"none\";\n if (method !== \"none\") {\n return oauthError(\n \"invalid_client_metadata\",\n \"Only public OAuth clients are supported\",\n );\n }\n\n const clientName =\n typeof body.client_name === \"string\"\n ? body.client_name.trim().slice(0, 120)\n : null;\n let client;\n try {\n client = await registerOAuthClient({\n clientName,\n redirectUris: [...new Set(redirectUris)],\n grantTypes: grantTypes.length ? grantTypes : undefined,\n responseTypes: responseTypes.length ? responseTypes : undefined,\n tokenEndpointAuthMethod: method,\n });\n } catch (err: any) {\n if (err?.message === \"RATE_LIMITED\") {\n return oauthError(\"slow_down\", \"Too many client registrations\", 429);\n }\n throw err;\n }\n return json(\n {\n client_id: client.clientId,\n client_id_issued_at: Math.floor((client.createdAt ?? Date.now()) / 1000),\n client_name: client.clientName ?? undefined,\n redirect_uris: client.redirectUris,\n grant_types: client.grantTypes,\n response_types: client.responseTypes,\n token_endpoint_auth_method: client.tokenEndpointAuthMethod,\n },\n 201,\n );\n}\n\nfunction redirectWithOAuthError(params: {\n redirectUri: string;\n state?: string;\n error: string;\n description?: string;\n}): Response {\n const url = new URL(params.redirectUri);\n url.searchParams.set(\"error\", params.error);\n if (params.description) {\n url.searchParams.set(\"error_description\", params.description);\n }\n if (params.state) url.searchParams.set(\"state\", params.state);\n return redirect(url.toString());\n}\n\nfunction buildCodeRedirectUrl(params: {\n redirectUri: string;\n code: string;\n state?: string;\n}): string {\n const url = new URL(params.redirectUri);\n url.searchParams.set(\"code\", params.code);\n if (params.state) url.searchParams.set(\"state\", params.state);\n return url.toString();\n}\n\nfunction redirectWithCode(params: {\n redirectUri: string;\n code: string;\n state?: string;\n}): Response {\n return redirect(buildCodeRedirectUrl(params));\n}\n\nfunction codeChallengeForVerifier(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const aa = Buffer.from(a);\n const bb = Buffer.from(b);\n return aa.length === bb.length && timingSafeEqual(aa, bb);\n}\n\nfunction base64UrlEncode(value: Buffer | string): string {\n const buf = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : value;\n return buf.toString(\"base64url\");\n}\n\nfunction base64UrlDecode(value: string): Buffer {\n return Buffer.from(value, \"base64url\");\n}\n\nfunction consentSigningKey(): string {\n return process.env.A2A_SECRET?.trim() || getAuthSecret();\n}\n\nfunction consentPayload(params: {\n email: string;\n clientId: string;\n redirectUri: string;\n resource: string;\n scope: string;\n codeChallenge: string;\n}): string {\n return JSON.stringify({\n ...params,\n exp: Math.floor(Date.now() / 1000) + 10 * 60,\n });\n}\n\nfunction signConsentToken(params: {\n email: string;\n clientId: string;\n redirectUri: string;\n resource: string;\n scope: string;\n codeChallenge: string;\n}): string {\n const payload = base64UrlEncode(consentPayload(params));\n const sig = base64UrlEncode(\n createHmac(\"sha256\", consentSigningKey()).update(payload).digest(),\n );\n return `${payload}.${sig}`;\n}\n\nfunction verifyConsentToken(\n token: string | undefined,\n expected: {\n email: string;\n clientId: string;\n redirectUri: string;\n resource: string;\n scope: string;\n codeChallenge: string;\n },\n): boolean {\n if (!token || !token.includes(\".\")) return false;\n const [payload, sig] = token.split(\".\", 2);\n if (!payload || !sig) return false;\n const expectedSig = base64UrlEncode(\n createHmac(\"sha256\", consentSigningKey()).update(payload).digest(),\n );\n if (!safeEqual(sig, expectedSig)) return false;\n try {\n const parsed = JSON.parse(base64UrlDecode(payload).toString(\"utf8\"));\n return (\n parsed.email === expected.email &&\n parsed.clientId === expected.clientId &&\n parsed.redirectUri === expected.redirectUri &&\n parsed.resource === expected.resource &&\n parsed.scope === expected.scope &&\n parsed.codeChallenge === expected.codeChallenge &&\n typeof parsed.exp === \"number\" &&\n parsed.exp * 1000 >= Date.now()\n );\n } catch {\n return false;\n }\n}\n\nfunction isValidCodeVerifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length >= 43 &&\n value.length <= 128 &&\n /^[A-Za-z0-9._~-]+$/.test(value)\n );\n}\n\n// Shared styling for the browser-facing OAuth pages (consent + post-authorize\n// confirmation) so they read as one coherent dark surface.\nconst OAUTH_PAGE_BASE_STYLE = `\n :root { color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; background: #09090b; color: #f4f4f5; }\n body { min-height: 100vh; display: grid; place-items: center; margin: 0; padding: 24px; }\n main { width: min(520px, 100%); border: 1px solid #27272a; border-radius: 8px; background: #111113; padding: 24px; box-shadow: 0 24px 80px rgba(0,0,0,.35); }\n h1 { font-size: 22px; line-height: 1.2; margin: 0 0 10px; }\n p { color: #a1a1aa; line-height: 1.5; margin: 0 0 18px; }\n .actions { display: flex; gap: 10px; justify-content: flex-end; }\n button, .btn { border: 0; border-radius: 6px; padding: 10px 14px; font: inherit; font-weight: 650; cursor: pointer; text-decoration: none; display: inline-block; }\n .primary { background: #f4f4f5; color: #09090b; }\n .secondary { background: #27272a; color: #f4f4f5; }`;\n\nfunction renderConsentPage(params: {\n appName: string;\n email: string;\n clientName: string;\n scopes: string[];\n fields: Record<string, string>;\n}): string {\n const hidden = Object.entries(params.fields)\n .map(\n ([key, value]) =>\n `<input type=\"hidden\" name=\"${escapeHtml(key)}\" value=\"${escapeHtml(value)}\">`,\n )\n .join(\"\\n\");\n const scopes = params.scopes\n .map((scope) => `<li><code>${escapeHtml(scope)}</code></li>`)\n .join(\"\");\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Authorize ${escapeHtml(params.appName)}</title>\n<style>${OAUTH_PAGE_BASE_STYLE}\n ul { margin: 0 0 22px; padding-left: 22px; color: #d4d4d8; }\n code { color: #67e8f9; }\n</style>\n</head>\n<body>\n<main>\n <h1>Authorize ${escapeHtml(params.clientName)}</h1>\n <p>${escapeHtml(params.appName)} will let this MCP client act as ${escapeHtml(params.email)} for these scopes:</p>\n <ul>${scopes}</ul>\n <form method=\"post\">\n ${hidden}\n <div class=\"actions\">\n <button class=\"secondary\" type=\"submit\" name=\"decision\" value=\"deny\">Deny</button>\n <button class=\"primary\" type=\"submit\" name=\"decision\" value=\"approve\">Authorize</button>\n </div>\n </form>\n</main>\n</body>\n</html>`;\n}\n\n// Shown after the user approves a native/desktop client (cursor://, vscode://, …)\n// whose redirect is a private-use scheme. A bare 302 to a custom scheme hands the\n// code to the OS app but leaves the browser tab dangling on a blank/error page, so\n// we render a friendly confirmation that also re-fires the deep link (so the client\n// still receives the code) and tells the user they can return to their agent.\nfunction renderAuthorizedPage(params: {\n appName: string;\n clientName: string | null;\n redirectUrl: string;\n}): string {\n const friendlyClient = params.clientName?.trim() || null;\n const returnTarget = friendlyClient ?? \"your agent\";\n const openLabel = friendlyClient\n ? `Open ${escapeHtml(friendlyClient)}`\n : \"Return to your agent\";\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Authorized</title>\n<style>${OAUTH_PAGE_BASE_STYLE}\n main.success { text-align: center; }\n .check { width: 56px; height: 56px; margin: 4px auto 16px; display: grid; place-items: center; border-radius: 999px; background: rgba(34,197,94,.12); }\n .check svg { width: 30px; height: 30px; }\n .success .actions { justify-content: center; margin-top: 4px; }\n .hint { color: #71717a; font-size: 13px; margin: 18px 0 0; }\n</style>\n</head>\n<body>\n<main class=\"success\">\n <div class=\"check\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">\n <path d=\"M20 6 9 17l-5-5\"></path>\n </svg>\n </div>\n <h1>You're all set</h1>\n <p>${escapeHtml(params.appName)} has authorized ${escapeHtml(returnTarget)}. You can return to ${escapeHtml(returnTarget)} to continue.</p>\n <div class=\"actions\">\n <a class=\"btn primary\" id=\"return-link\" href=\"${escapeHtml(params.redirectUrl)}\">${openLabel}</a>\n </div>\n <p class=\"hint\">You can close this tab.</p>\n</main>\n<script>\n (function () {\n var link = document.getElementById(\"return-link\");\n if (link && link.href) {\n try { window.location.href = link.href; } catch (e) {}\n }\n })();\n</script>\n</body>\n</html>`;\n}\n\nasync function resolveOrgDomain(\n orgId: string | undefined,\n): Promise<string | undefined> {\n if (!orgId) return undefined;\n try {\n return (await getOrgDomain(orgId)) ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function readOAuthParams(\n event: H3Event,\n): Promise<Record<string, string>> {\n if (getMethod(event) === \"GET\") {\n const query = getQuery(event);\n return Object.fromEntries(\n Object.entries(query).flatMap(([key, value]) =>\n typeof value === \"string\" ? [[key, value]] : [],\n ),\n );\n }\n const body = await readBody(event).catch(() => ({}));\n if (typeof body === \"string\") {\n return Object.fromEntries(new URLSearchParams(body));\n }\n if (body && typeof body === \"object\") {\n return Object.fromEntries(\n Object.entries(body as Record<string, unknown>).flatMap(([key, value]) =>\n typeof value === \"string\" ? [[key, value]] : [],\n ),\n );\n }\n return {};\n}\n\nasync function handleAuthorize(\n event: H3Event,\n options: McpOAuthRouteOptions,\n): Promise<Response> {\n const method = getMethod(event);\n if (method !== \"GET\" && method !== \"POST\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n if (method === \"POST\" && !isSameOriginPost(event)) {\n return oauthError(\n \"invalid_request\",\n \"Cross-origin authorize POST rejected\",\n 403,\n );\n }\n const params = await readOAuthParams(event);\n const state = params.state;\n const clientId = params.client_id;\n const redirectUri = params.redirect_uri;\n const resource = params.resource || getMcpOAuthResource(event);\n const expectedResource = getMcpOAuthResource(event);\n\n if (params.response_type !== \"code\") {\n return oauthError(\n \"unsupported_response_type\",\n \"response_type must be code\",\n );\n }\n if (!clientId || !redirectUri || !resource || resource !== expectedResource) {\n return oauthError(\"invalid_request\", \"Invalid OAuth authorization request\");\n }\n if (params.code_challenge_method !== \"S256\" || !params.code_challenge) {\n return oauthError(\"invalid_request\", \"PKCE S256 is required\");\n }\n\n const client = await getOAuthClient(clientId);\n if (!client || !client.redirectUris.includes(redirectUri)) {\n return oauthError(\"invalid_client\", \"Unknown client or redirect_uri\");\n }\n\n const session = await getSession(event);\n if (!session?.email) {\n if (params.prompt === \"none\") {\n return redirectWithOAuthError({\n redirectUri,\n state,\n error: \"login_required\",\n });\n }\n const loginHtml = getConfiguredLoginHtml(event);\n return loginHtml\n ? html(loginHtml, 200)\n : oauthError(\"login_required\", \"Sign in required\", 401);\n }\n\n const scope = normalizeOAuthScope(params.scope);\n if (!scope) {\n return redirectWithOAuthError({\n redirectUri,\n state,\n error: \"invalid_scope\",\n });\n }\n if (method === \"GET\") {\n return html(\n renderConsentPage({\n appName: options.appName || options.appId || \"Agent Native\",\n email: session.email,\n clientName: client.clientName || client.clientId,\n scopes: scope.split(/\\s+/),\n fields: {\n response_type: \"code\",\n client_id: clientId,\n redirect_uri: redirectUri,\n resource,\n scope,\n state: state ?? \"\",\n code_challenge: params.code_challenge,\n code_challenge_method: \"S256\",\n consent_token: signConsentToken({\n email: session.email,\n clientId,\n redirectUri,\n resource,\n scope,\n codeChallenge: params.code_challenge,\n }),\n },\n }),\n );\n }\n\n if (\n !verifyConsentToken(params.consent_token, {\n email: session.email,\n clientId,\n redirectUri,\n resource,\n scope,\n codeChallenge: params.code_challenge,\n })\n ) {\n return oauthError(\"invalid_request\", \"Invalid authorization consent token\");\n }\n\n if (params.decision !== \"approve\") {\n return redirectWithOAuthError({\n redirectUri,\n state,\n error: \"access_denied\",\n });\n }\n\n const orgDomain = await resolveOrgDomain(session.orgId);\n const code = await createOAuthCode({\n clientId,\n redirectUri,\n codeChallenge: params.code_challenge,\n codeChallengeMethod: \"S256\",\n ownerEmail: session.email,\n orgId: session.orgId ?? null,\n orgDomain: orgDomain ?? null,\n scope,\n resource,\n });\n\n // Native/desktop clients register a private-use scheme (cursor://, vscode://, …).\n // A 302 to that scheme opens the app but leaves the browser tab dangling, so we\n // render a friendly confirmation page that re-fires the deep link instead. For\n // https/loopback callbacks the client (or its local server) renders its own page,\n // so keep the standard redirect there.\n let isDeepLinkRedirect = false;\n try {\n const protocol = new URL(redirectUri).protocol;\n isDeepLinkRedirect =\n protocol !== \"http:\" &&\n protocol !== \"https:\" &&\n isPrivateUseRedirectScheme(protocol);\n } catch {\n isDeepLinkRedirect = false;\n }\n if (isDeepLinkRedirect) {\n return html(\n renderAuthorizedPage({\n appName: options.appName || options.appId || \"Agent Native\",\n clientName: client.clientName ?? null,\n redirectUrl: buildCodeRedirectUrl({\n redirectUri,\n state,\n code: code.code,\n }),\n }),\n );\n }\n return redirectWithCode({ redirectUri, state, code: code.code });\n}\n\nasync function issueTokenSet(params: {\n ownerEmail: string;\n orgId?: string | null;\n orgDomain?: string | null;\n clientId: string;\n scope: string;\n resource: string;\n issuer: string;\n}): Promise<Record<string, unknown>> {\n const refreshToken = generateOpaqueToken();\n await createOAuthRefreshToken({\n refreshToken,\n clientId: params.clientId,\n ownerEmail: params.ownerEmail,\n orgId: params.orgId ?? null,\n orgDomain: params.orgDomain ?? null,\n scope: params.scope,\n resource: params.resource,\n });\n const accessToken = await signMcpOAuthAccessToken(params);\n return {\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,\n refresh_token: refreshToken,\n scope: params.scope,\n };\n}\n\nasync function handleAuthorizationCodeGrant(\n event: H3Event,\n body: Record<string, string>,\n): Promise<Response> {\n const code = body.code;\n const clientId = body.client_id;\n const redirectUri = body.redirect_uri;\n const verifier = body.code_verifier;\n if (!code || !clientId || !redirectUri || !isValidCodeVerifier(verifier)) {\n return oauthError(\"invalid_request\", \"Missing authorization-code fields\");\n }\n const row = await getOAuthCode(code);\n if (!row) return oauthError(\"invalid_grant\", \"Invalid or expired code\");\n if (row.clientId !== clientId || row.redirectUri !== redirectUri) {\n return oauthError(\"invalid_grant\", \"Code was issued to another client\");\n }\n const expectedChallenge = codeChallengeForVerifier(verifier);\n if (!safeEqual(expectedChallenge, row.codeChallenge)) {\n return oauthError(\"invalid_grant\", \"PKCE verification failed\");\n }\n const consumed = await consumeOAuthCode(code);\n if (!consumed) return oauthError(\"invalid_grant\", \"Invalid or expired code\");\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer)\n return oauthError(\"server_error\", \"Unable to derive issuer\", 500);\n return json(\n await issueTokenSet({\n ownerEmail: row.ownerEmail,\n orgId: row.orgId,\n orgDomain: row.orgDomain,\n clientId,\n scope: row.scope,\n resource: row.resource,\n issuer,\n }),\n );\n}\n\nasync function handleRefreshTokenGrant(\n event: H3Event,\n body: Record<string, string>,\n): Promise<Response> {\n const refreshToken = body.refresh_token;\n const clientId = body.client_id;\n if (!refreshToken) {\n return oauthError(\"invalid_request\", \"refresh_token is required\");\n }\n if (!clientId) {\n return oauthError(\"invalid_request\", \"client_id is required\");\n }\n const existing = await getOAuthRefreshToken(refreshToken);\n if (!existing) return oauthError(\"invalid_grant\", \"Invalid refresh token\");\n if (existing.clientId !== clientId) {\n return oauthError(\n \"invalid_grant\",\n \"Refresh token belongs to another client\",\n );\n }\n await touchOAuthRefreshToken(refreshToken).catch(() => undefined);\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer)\n return oauthError(\"server_error\", \"Unable to derive issuer\", 500);\n const accessToken = await signMcpOAuthAccessToken({\n ownerEmail: existing.ownerEmail,\n orgId: existing.orgId,\n orgDomain: existing.orgDomain,\n clientId: existing.clientId,\n scope: existing.scope,\n resource: existing.resource,\n issuer,\n });\n return json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,\n refresh_token: refreshToken,\n scope: existing.scope,\n });\n}\n\nasync function handleToken(event: H3Event): Promise<Response> {\n if (getMethod(event) !== \"POST\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const body = await readOAuthParams(event);\n switch (body.grant_type) {\n case \"authorization_code\":\n return handleAuthorizationCodeGrant(event, body);\n case \"refresh_token\":\n return handleRefreshTokenGrant(event, body);\n default:\n return oauthError(\"unsupported_grant_type\", \"Unsupported grant_type\");\n }\n}\n\nexport async function handleMcpOAuth(\n event: H3Event,\n subpath: string,\n options: McpOAuthRouteOptions = {},\n): Promise<Response> {\n const path = subpath.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n try {\n if (path === \"authorize\") return await handleAuthorize(event, options);\n if (path === \"token\") return await handleToken(event);\n if (path === \"register\") return await handleRegister(event);\n setResponseStatus(event, 404);\n return json({ error: \"Not found\" }, 404);\n } catch (err: any) {\n return oauthError(\n \"server_error\",\n err?.message || \"OAuth request failed\",\n 500,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"oauth-route.js","sourceRoot":"","sources":["../../src/mcp/oauth-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGtE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AAEvE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,gBAAgB,EAChB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAO/E,SAAS,IAAI,CAAC,IAAa,EAAE,MAAM,GAAG,GAAG;IACvC,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;QACxC,MAAM;QACN,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,eAAe,EAAE,UAAU;YAC3B,MAAM,EAAE,UAAU;SACnB;KACF,CAAC,CAAC;AACL,CAAC;AAED,SA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,CAAC;QACnD,KAAK,eAAe;YAClB,OAAO,uBAAuB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAC9C;YACE,OAAO,UAAU,CAAC,wBAAwB,EAAE,wBAAwB,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,KAAc,EACd,OAAe,EACf,OAAO,GAAyB,EAAE;IAElC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC7D,IAAI,CAAC;QACH,IAAI,IAAI,KAAK,WAAW;YAAE,OAAO,MAAM,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACvE,IAAI,IAAI,KAAK,OAAO;YAAE,OAAO,MAAM,WAAW,CAAC,KAAK,CAAC,CAAC;QACtD,IAAI,IAAI,KAAK,UAAU;YAAE,OAAO,MAAM,cAAc,CAAC,KAAK,CAAC,CAAC;QAC5D,iBAAiB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAC9B,OAAO,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,GAAG,CAAC,CAAC;IAC3C,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,OAAO,UAAU,CACf,cAAc,EACd,GAAG,EAAE,OAAO,IAAI,sBAAsB,EACtC,GAAG,CACJ,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["/**\n * Standard remote MCP OAuth 2.1 endpoints.\n *\n * These routes let MCP hosts such as Claude Code and ChatGPT authenticate\n * through their native remote-MCP OAuth flow instead of pasting bearer tokens.\n * The issued access tokens are audience-bound to `/mcp`, carry\n * the same user/org identity as the existing connect flow, and are mediated by\n * `verifyAuth` before any MCP tool/resource request runs.\n */\n\nimport { createHash, createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type { H3Event } from \"h3\";\nimport { getHeader, getMethod, getQuery, setResponseStatus } from \"h3\";\n\nimport { getOrgDomain } from \"../org/context.js\";\nimport { getConfiguredLoginHtml, getSession } from \"../server/auth.js\";\nimport { getAuthSecret } from \"../server/better-auth-instance.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n createOAuthCode,\n createOAuthRefreshToken,\n consumeOAuthCode,\n generateOpaqueToken,\n getOAuthClient,\n getOAuthCode,\n getOAuthRefreshToken,\n registerOAuthClient,\n touchOAuthRefreshToken,\n} from \"./oauth-store.js\";\nimport {\n MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,\n MCP_OAUTH_DEFAULT_SCOPE,\n MCP_OAUTH_SCOPES,\n normalizeOAuthScope,\n signMcpOAuthAccessToken,\n} from \"./oauth-token.js\";\nimport { MCP_PUBLIC_ROUTE_PREFIX, MCP_ROUTE_PREFIXES } from \"./route-paths.js\";\n\nexport interface McpOAuthRouteOptions {\n appId?: string;\n appName?: string;\n}\n\nfunction json(body: unknown, status = 200): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store\",\n Pragma: \"no-cache\",\n },\n });\n}\n\nfunction html(body: string, status = 200): Response {\n return new Response(body, {\n status,\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"Cache-Control\": \"no-store\",\n },\n });\n}\n\nfunction redirect(location: string): Response {\n return new Response(null, {\n status: 302,\n headers: { Location: location, \"Cache-Control\": \"no-store\" },\n });\n}\n\nfunction isSameOriginPost(event: H3Event): boolean {\n const origin = getHeader(event, \"origin\");\n if (!origin) return true;\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer) return false;\n try {\n return new URL(origin).origin === new URL(issuer).origin;\n } catch {\n return false;\n }\n}\n\nfunction oauthError(\n error: string,\n description: string,\n status = 400,\n): Response {\n return json({ error, error_description: description }, status);\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\nfunction normalizeBasePath(raw: string | undefined): string {\n const trimmed = (raw ?? \"\").trim();\n if (!trimmed || trimmed === \"/\") return \"\";\n const withSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n return withSlash.replace(/\\/+$/, \"\");\n}\n\nfunction configuredBasePath(): string {\n return normalizeBasePath(\n process.env.APP_BASE_PATH || process.env.VITE_APP_BASE_PATH,\n );\n}\n\nfunction stripTrailingSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nfunction configuredPublicBaseUrl(): string | undefined {\n for (const key of [\n \"WORKSPACE_OAUTH_ORIGIN\",\n \"VITE_WORKSPACE_OAUTH_ORIGIN\",\n \"APP_URL\",\n \"VITE_APP_URL\",\n \"BETTER_AUTH_URL\",\n \"VITE_BETTER_AUTH_URL\",\n ]) {\n const raw = process.env[key]?.trim();\n if (!raw) continue;\n try {\n const url = new URL(raw);\n url.search = \"\";\n url.hash = \"\";\n return stripTrailingSlash(`${url.origin}${url.pathname}`);\n } catch {\n // Ignore invalid operator-provided URL values and fall back to headers.\n }\n }\n return undefined;\n}\n\nfunction appendConfiguredBasePath(baseUrl: string): string {\n const basePath = configuredBasePath();\n if (!basePath) return stripTrailingSlash(baseUrl);\n try {\n const url = new URL(baseUrl);\n const pathname = normalizeBasePath(url.pathname);\n if (pathname === basePath || pathname.endsWith(`${basePath}`)) {\n return stripTrailingSlash(`${url.origin}${pathname}`);\n }\n return stripTrailingSlash(`${url.origin}${pathname}${basePath}`);\n } catch {\n return `${stripTrailingSlash(baseUrl)}${basePath}`;\n }\n}\n\nfunction deriveOrigin(event: H3Event): string {\n const forwardedProto = getHeader(event, \"x-forwarded-proto\");\n const host = getHeader(event, \"x-forwarded-host\") || getHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:|$)/.test(host)\n ? \"http\"\n : \"https\");\n return host ? `${proto}://${host}` : \"\";\n}\n\nexport function getMcpOAuthIssuer(event: H3Event): string | undefined {\n const baseUrl = configuredPublicBaseUrl() || deriveOrigin(event);\n if (!baseUrl) return undefined;\n return appendConfiguredBasePath(baseUrl);\n}\n\nexport function getMcpOAuthResource(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer) return undefined;\n return `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}`;\n}\n\nfunction mcpResourcesForIssuer(issuer: string): string[] {\n return [\n MCP_PUBLIC_ROUTE_PREFIX,\n ...MCP_ROUTE_PREFIXES.filter(\n (prefix) => prefix !== MCP_PUBLIC_ROUTE_PREFIX,\n ),\n ].map((prefix) => `${issuer}${prefix}`);\n}\n\n/**\n * All plausible MCP OAuth resource audiences for the given request, deduped.\n *\n * When a configured public base URL differs from the request-derived origin\n * (e.g. during Netlify deploy-preview or behind a reverse proxy), a token\n * minted against the configured URL must still verify against the request-\n * derived URL and vice-versa. Returns both so `verifyMcpOAuthAccessToken`\n * accepts either without issuing a 401.\n */\nexport function getMcpOAuthAudiences(event: H3Event): string[] {\n const configuredIssuer = (() => {\n const base = configuredPublicBaseUrl();\n if (!base) return undefined;\n // Re-apply base path if present so the configured resource is also\n // base-path-aware, consistent with how getMcpOAuthResource computes it.\n return appendConfiguredBasePath(base);\n })();\n const seen = new Set<string>();\n const out: string[] = [];\n for (const r of [\n ...(getMcpOAuthIssuer(event)\n ? mcpResourcesForIssuer(getMcpOAuthIssuer(event) as string)\n : []),\n ...(configuredIssuer ? mcpResourcesForIssuer(configuredIssuer) : []),\n ]) {\n const n = r?.replace(/\\/+$/, \"\");\n if (n && !seen.has(n)) {\n seen.add(n);\n out.push(n);\n }\n }\n return out;\n}\n\nexport function getMcpOAuthProtectedResourceMetadataUrl(\n event: H3Event,\n): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer) return undefined;\n return `${issuer}/.well-known/oauth-protected-resource`;\n}\n\nexport function buildMcpOAuthChallenge(event: H3Event): string {\n const metadata = getMcpOAuthProtectedResourceMetadataUrl(event);\n const scope = MCP_OAUTH_DEFAULT_SCOPE;\n return metadata\n ? `Bearer resource_metadata=\"${metadata}\", scope=\"${scope}\"`\n : `Bearer scope=\"${scope}\"`;\n}\n\nfunction authorizationEndpoint(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n return issuer\n ? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/authorize`\n : undefined;\n}\n\nfunction tokenEndpoint(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n return issuer ? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/token` : undefined;\n}\n\nfunction registrationEndpoint(event: H3Event): string | undefined {\n const issuer = getMcpOAuthIssuer(event);\n return issuer\n ? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/register`\n : undefined;\n}\n\nexport function handleMcpOAuthProtectedResourceMetadata(\n event: H3Event,\n): Response {\n if (getMethod(event) !== \"GET\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const resource = getMcpOAuthResource(event);\n const issuer = getMcpOAuthIssuer(event);\n if (!resource || !issuer) {\n return oauthError(\"server_error\", \"Unable to derive MCP resource\", 500);\n }\n return json({\n resource,\n authorization_servers: [issuer],\n scopes_supported: MCP_OAUTH_SCOPES,\n resource_documentation: issuer,\n });\n}\n\nexport function handleMcpOAuthAuthorizationServerMetadata(\n event: H3Event,\n): Response {\n if (getMethod(event) !== \"GET\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const issuer = getMcpOAuthIssuer(event);\n const authorize = authorizationEndpoint(event);\n const token = tokenEndpoint(event);\n const register = registrationEndpoint(event);\n if (!issuer || !authorize || !token || !register) {\n return oauthError(\"server_error\", \"Unable to derive OAuth endpoints\", 500);\n }\n return json({\n issuer,\n authorization_endpoint: authorize,\n token_endpoint: token,\n registration_endpoint: register,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"none\"],\n scopes_supported: MCP_OAUTH_SCOPES,\n });\n}\n\n// Schemes that must never be accepted as a redirect target: they can execute\n// script or read local resources if a redirect is ever rendered in a browser\n// or webview context.\nconst DISALLOWED_REDIRECT_SCHEMES = new Set([\n \"javascript:\",\n \"data:\",\n \"vbscript:\",\n \"file:\",\n \"blob:\",\n \"about:\",\n]);\n\n// Native/desktop IDE clients (Cursor, VS Code, …) register a private-use URI\n// scheme callback such as `cursor://` or `vscode://` (RFC 8252 §7.1) instead of\n// an https/loopback URL. The authorization code is bound by PKCE (S256), so\n// delivering it through a client-registered app scheme is safe.\nfunction isPrivateUseRedirectScheme(protocol: string): boolean {\n if (DISALLOWED_REDIRECT_SCHEMES.has(protocol)) return false;\n // RFC 3986 scheme grammar: ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" ), with a\n // trailing \":\" from URL.protocol. Require a non-http(s) custom scheme here;\n // http/https are handled explicitly above.\n return /^[a-z][a-z0-9+.-]*:$/.test(protocol);\n}\n\nfunction isAllowedRedirectUri(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 2048) return false;\n try {\n const url = new URL(value);\n if (url.hash) return false;\n if (url.username || url.password) return false;\n if (url.protocol === \"https:\") return true;\n if (url.protocol === \"http:\") {\n return (\n url.hostname === \"localhost\" ||\n url.hostname === \"127.0.0.1\" ||\n url.hostname === \"::1\" ||\n url.hostname === \"[::1]\"\n );\n }\n return isPrivateUseRedirectScheme(url.protocol);\n } catch {\n return false;\n }\n}\n\nfunction parseStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === \"string\")\n : [];\n}\n\nasync function handleRegister(event: H3Event): Promise<Response> {\n if (getMethod(event) !== \"POST\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const body = ((await readBody(event).catch(() => ({}))) ?? {}) as Record<\n string,\n unknown\n >;\n const redirectUris = parseStringArray(body.redirect_uris);\n if (\n redirectUris.length === 0 ||\n redirectUris.length > 20 ||\n !redirectUris.every(isAllowedRedirectUri)\n ) {\n return oauthError(\n \"invalid_client_metadata\",\n \"redirect_uris must contain valid HTTPS or localhost callback URLs\",\n );\n }\n\n const grantTypes = parseStringArray(body.grant_types);\n if (\n grantTypes.length &&\n !grantTypes.every(\n (g) => g === \"authorization_code\" || g === \"refresh_token\",\n )\n ) {\n return oauthError(\"invalid_client_metadata\", \"Unsupported grant_type\");\n }\n const responseTypes = parseStringArray(body.response_types);\n if (responseTypes.length && !responseTypes.every((r) => r === \"code\")) {\n return oauthError(\"invalid_client_metadata\", \"Unsupported response_type\");\n }\n const method =\n typeof body.token_endpoint_auth_method === \"string\"\n ? body.token_endpoint_auth_method\n : \"none\";\n if (method !== \"none\") {\n return oauthError(\n \"invalid_client_metadata\",\n \"Only public OAuth clients are supported\",\n );\n }\n\n const clientName =\n typeof body.client_name === \"string\"\n ? body.client_name.trim().slice(0, 120)\n : null;\n let client;\n try {\n client = await registerOAuthClient({\n clientName,\n redirectUris: [...new Set(redirectUris)],\n grantTypes: grantTypes.length ? grantTypes : undefined,\n responseTypes: responseTypes.length ? responseTypes : undefined,\n tokenEndpointAuthMethod: method,\n });\n } catch (err: any) {\n if (err?.message === \"RATE_LIMITED\") {\n return oauthError(\"slow_down\", \"Too many client registrations\", 429);\n }\n throw err;\n }\n return json(\n {\n client_id: client.clientId,\n client_id_issued_at: Math.floor((client.createdAt ?? Date.now()) / 1000),\n client_name: client.clientName ?? undefined,\n redirect_uris: client.redirectUris,\n grant_types: client.grantTypes,\n response_types: client.responseTypes,\n token_endpoint_auth_method: client.tokenEndpointAuthMethod,\n },\n 201,\n );\n}\n\nfunction redirectWithOAuthError(params: {\n redirectUri: string;\n state?: string;\n error: string;\n description?: string;\n}): Response {\n const url = new URL(params.redirectUri);\n url.searchParams.set(\"error\", params.error);\n if (params.description) {\n url.searchParams.set(\"error_description\", params.description);\n }\n if (params.state) url.searchParams.set(\"state\", params.state);\n return redirect(url.toString());\n}\n\nfunction buildCodeRedirectUrl(params: {\n redirectUri: string;\n code: string;\n state?: string;\n}): string {\n const url = new URL(params.redirectUri);\n url.searchParams.set(\"code\", params.code);\n if (params.state) url.searchParams.set(\"state\", params.state);\n return url.toString();\n}\n\nfunction redirectWithCode(params: {\n redirectUri: string;\n code: string;\n state?: string;\n}): Response {\n return redirect(buildCodeRedirectUrl(params));\n}\n\nfunction codeChallengeForVerifier(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const aa = Buffer.from(a);\n const bb = Buffer.from(b);\n return aa.length === bb.length && timingSafeEqual(aa, bb);\n}\n\nfunction base64UrlEncode(value: Buffer | string): string {\n const buf = typeof value === \"string\" ? Buffer.from(value, \"utf8\") : value;\n return buf.toString(\"base64url\");\n}\n\nfunction base64UrlDecode(value: string): Buffer {\n return Buffer.from(value, \"base64url\");\n}\n\nfunction consentSigningKey(): string {\n return process.env.A2A_SECRET?.trim() || getAuthSecret();\n}\n\nfunction consentPayload(params: {\n email: string;\n clientId: string;\n redirectUri: string;\n resource: string;\n scope: string;\n codeChallenge: string;\n}): string {\n return JSON.stringify({\n ...params,\n exp: Math.floor(Date.now() / 1000) + 10 * 60,\n });\n}\n\nfunction signConsentToken(params: {\n email: string;\n clientId: string;\n redirectUri: string;\n resource: string;\n scope: string;\n codeChallenge: string;\n}): string {\n const payload = base64UrlEncode(consentPayload(params));\n const sig = base64UrlEncode(\n createHmac(\"sha256\", consentSigningKey()).update(payload).digest(),\n );\n return `${payload}.${sig}`;\n}\n\nfunction verifyConsentToken(\n token: string | undefined,\n expected: {\n email: string;\n clientId: string;\n redirectUri: string;\n resource: string;\n scope: string;\n codeChallenge: string;\n },\n): boolean {\n if (!token || !token.includes(\".\")) return false;\n const [payload, sig] = token.split(\".\", 2);\n if (!payload || !sig) return false;\n const expectedSig = base64UrlEncode(\n createHmac(\"sha256\", consentSigningKey()).update(payload).digest(),\n );\n if (!safeEqual(sig, expectedSig)) return false;\n try {\n const parsed = JSON.parse(base64UrlDecode(payload).toString(\"utf8\"));\n return (\n parsed.email === expected.email &&\n parsed.clientId === expected.clientId &&\n parsed.redirectUri === expected.redirectUri &&\n parsed.resource === expected.resource &&\n parsed.scope === expected.scope &&\n parsed.codeChallenge === expected.codeChallenge &&\n typeof parsed.exp === \"number\" &&\n parsed.exp * 1000 >= Date.now()\n );\n } catch {\n return false;\n }\n}\n\nfunction isValidCodeVerifier(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length >= 43 &&\n value.length <= 128 &&\n /^[A-Za-z0-9._~-]+$/.test(value)\n );\n}\n\n// Shared styling for the browser-facing OAuth pages (consent + post-authorize\n// confirmation) so they read as one coherent dark surface.\nconst OAUTH_PAGE_BASE_STYLE = `\n :root { color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif; background: #09090b; color: #f4f4f5; }\n body { min-height: 100vh; display: grid; place-items: center; margin: 0; padding: 24px; }\n main { width: min(520px, 100%); border: 1px solid #27272a; border-radius: 8px; background: #111113; padding: 24px; box-shadow: 0 24px 80px rgba(0,0,0,.35); }\n h1 { font-size: 22px; line-height: 1.2; margin: 0 0 10px; }\n p { color: #a1a1aa; line-height: 1.5; margin: 0 0 18px; }\n .actions { display: flex; gap: 10px; justify-content: flex-end; }\n button, .btn { border: 0; border-radius: 6px; padding: 10px 14px; font: inherit; font-weight: 650; cursor: pointer; text-decoration: none; display: inline-block; }\n .primary { background: #f4f4f5; color: #09090b; }\n .secondary { background: #27272a; color: #f4f4f5; }`;\n\nfunction renderConsentPage(params: {\n appName: string;\n email: string;\n clientName: string;\n scopes: string[];\n fields: Record<string, string>;\n}): string {\n const hidden = Object.entries(params.fields)\n .map(\n ([key, value]) =>\n `<input type=\"hidden\" name=\"${escapeHtml(key)}\" value=\"${escapeHtml(value)}\">`,\n )\n .join(\"\\n\");\n const scopes = params.scopes\n .map((scope) => `<li><code>${escapeHtml(scope)}</code></li>`)\n .join(\"\");\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Authorize ${escapeHtml(params.appName)}</title>\n<style>${OAUTH_PAGE_BASE_STYLE}\n ul { margin: 0 0 22px; padding-left: 22px; color: #d4d4d8; }\n code { color: #67e8f9; }\n</style>\n</head>\n<body>\n<main>\n <h1>Authorize ${escapeHtml(params.clientName)}</h1>\n <p>${escapeHtml(params.appName)} will let this MCP client act as ${escapeHtml(params.email)} for these scopes:</p>\n <ul>${scopes}</ul>\n <form method=\"post\">\n ${hidden}\n <div class=\"actions\">\n <button class=\"secondary\" type=\"submit\" name=\"decision\" value=\"deny\">Deny</button>\n <button class=\"primary\" type=\"submit\" name=\"decision\" value=\"approve\">Authorize</button>\n </div>\n </form>\n</main>\n</body>\n</html>`;\n}\n\n// Shown after the user approves a native/desktop client (cursor://, vscode://, …)\n// whose redirect is a private-use scheme. A bare 302 to a custom scheme hands the\n// code to the OS app but leaves the browser tab dangling on a blank/error page, so\n// we render a friendly confirmation that also re-fires the deep link (so the client\n// still receives the code) and tells the user they can return to their agent.\nfunction renderAuthorizedPage(params: {\n appName: string;\n clientName: string | null;\n redirectUrl: string;\n}): string {\n const friendlyClient = params.clientName?.trim() || null;\n const returnTarget = friendlyClient ?? \"your agent\";\n const openLabel = friendlyClient\n ? `Open ${escapeHtml(friendlyClient)}`\n : \"Return to your agent\";\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Authorized</title>\n<style>${OAUTH_PAGE_BASE_STYLE}\n main.success { text-align: center; }\n .check { width: 56px; height: 56px; margin: 4px auto 16px; display: grid; place-items: center; border-radius: 999px; background: rgba(34,197,94,.12); }\n .check svg { width: 30px; height: 30px; }\n .success .actions { justify-content: center; margin-top: 4px; }\n .hint { color: #71717a; font-size: 13px; margin: 18px 0 0; }\n</style>\n</head>\n<body>\n<main class=\"success\">\n <div class=\"check\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#22c55e\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">\n <path d=\"M20 6 9 17l-5-5\"></path>\n </svg>\n </div>\n <h1>You're all set</h1>\n <p>${escapeHtml(params.appName)} has authorized ${escapeHtml(returnTarget)}. You can return to ${escapeHtml(returnTarget)} to continue.</p>\n <div class=\"actions\">\n <a class=\"btn primary\" id=\"return-link\" href=\"${escapeHtml(params.redirectUrl)}\">${openLabel}</a>\n </div>\n <p class=\"hint\">You can close this tab.</p>\n</main>\n<script>\n (function () {\n var link = document.getElementById(\"return-link\");\n if (link && link.href) {\n try { window.location.href = link.href; } catch (e) {}\n }\n })();\n</script>\n</body>\n</html>`;\n}\n\nasync function resolveOrgDomain(\n orgId: string | undefined,\n): Promise<string | undefined> {\n if (!orgId) return undefined;\n try {\n return (await getOrgDomain(orgId)) ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function readOAuthParams(\n event: H3Event,\n): Promise<Record<string, string>> {\n if (getMethod(event) === \"GET\") {\n const query = getQuery(event);\n return Object.fromEntries(\n Object.entries(query).flatMap(([key, value]) =>\n typeof value === \"string\" ? [[key, value]] : [],\n ),\n );\n }\n const body = await readBody(event).catch(() => ({}));\n if (typeof body === \"string\") {\n return Object.fromEntries(new URLSearchParams(body));\n }\n if (body && typeof body === \"object\") {\n return Object.fromEntries(\n Object.entries(body as Record<string, unknown>).flatMap(([key, value]) =>\n typeof value === \"string\" ? [[key, value]] : [],\n ),\n );\n }\n return {};\n}\n\nasync function handleAuthorize(\n event: H3Event,\n options: McpOAuthRouteOptions,\n): Promise<Response> {\n const method = getMethod(event);\n if (method !== \"GET\" && method !== \"POST\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n if (method === \"POST\" && !isSameOriginPost(event)) {\n return oauthError(\n \"invalid_request\",\n \"Cross-origin authorize POST rejected\",\n 403,\n );\n }\n const params = await readOAuthParams(event);\n const state = params.state;\n const clientId = params.client_id;\n const redirectUri = params.redirect_uri;\n const resource = (params.resource || getMcpOAuthResource(event))?.replace(\n /\\/+$/,\n \"\",\n );\n const expectedResources = getMcpOAuthAudiences(event);\n\n if (params.response_type !== \"code\") {\n return oauthError(\n \"unsupported_response_type\",\n \"response_type must be code\",\n );\n }\n if (\n !clientId ||\n !redirectUri ||\n !resource ||\n !expectedResources.includes(resource)\n ) {\n return oauthError(\"invalid_request\", \"Invalid OAuth authorization request\");\n }\n if (params.code_challenge_method !== \"S256\" || !params.code_challenge) {\n return oauthError(\"invalid_request\", \"PKCE S256 is required\");\n }\n\n const client = await getOAuthClient(clientId);\n if (!client || !client.redirectUris.includes(redirectUri)) {\n return oauthError(\"invalid_client\", \"Unknown client or redirect_uri\");\n }\n\n const session = await getSession(event);\n if (!session?.email) {\n if (params.prompt === \"none\") {\n return redirectWithOAuthError({\n redirectUri,\n state,\n error: \"login_required\",\n });\n }\n const loginHtml = getConfiguredLoginHtml(event);\n return loginHtml\n ? html(loginHtml, 200)\n : oauthError(\"login_required\", \"Sign in required\", 401);\n }\n\n const scope = normalizeOAuthScope(params.scope);\n if (!scope) {\n return redirectWithOAuthError({\n redirectUri,\n state,\n error: \"invalid_scope\",\n });\n }\n if (method === \"GET\") {\n return html(\n renderConsentPage({\n appName: options.appName || options.appId || \"Agent Native\",\n email: session.email,\n clientName: client.clientName || client.clientId,\n scopes: scope.split(/\\s+/),\n fields: {\n response_type: \"code\",\n client_id: clientId,\n redirect_uri: redirectUri,\n resource,\n scope,\n state: state ?? \"\",\n code_challenge: params.code_challenge,\n code_challenge_method: \"S256\",\n consent_token: signConsentToken({\n email: session.email,\n clientId,\n redirectUri,\n resource,\n scope,\n codeChallenge: params.code_challenge,\n }),\n },\n }),\n );\n }\n\n if (\n !verifyConsentToken(params.consent_token, {\n email: session.email,\n clientId,\n redirectUri,\n resource,\n scope,\n codeChallenge: params.code_challenge,\n })\n ) {\n return oauthError(\"invalid_request\", \"Invalid authorization consent token\");\n }\n\n if (params.decision !== \"approve\") {\n return redirectWithOAuthError({\n redirectUri,\n state,\n error: \"access_denied\",\n });\n }\n\n const orgDomain = await resolveOrgDomain(session.orgId);\n const code = await createOAuthCode({\n clientId,\n redirectUri,\n codeChallenge: params.code_challenge,\n codeChallengeMethod: \"S256\",\n ownerEmail: session.email,\n orgId: session.orgId ?? null,\n orgDomain: orgDomain ?? null,\n scope,\n resource,\n });\n\n // Native/desktop clients register a private-use scheme (cursor://, vscode://, …).\n // A 302 to that scheme opens the app but leaves the browser tab dangling, so we\n // render a friendly confirmation page that re-fires the deep link instead. For\n // https/loopback callbacks the client (or its local server) renders its own page,\n // so keep the standard redirect there.\n let isDeepLinkRedirect = false;\n try {\n const protocol = new URL(redirectUri).protocol;\n isDeepLinkRedirect =\n protocol !== \"http:\" &&\n protocol !== \"https:\" &&\n isPrivateUseRedirectScheme(protocol);\n } catch {\n isDeepLinkRedirect = false;\n }\n if (isDeepLinkRedirect) {\n return html(\n renderAuthorizedPage({\n appName: options.appName || options.appId || \"Agent Native\",\n clientName: client.clientName ?? null,\n redirectUrl: buildCodeRedirectUrl({\n redirectUri,\n state,\n code: code.code,\n }),\n }),\n );\n }\n return redirectWithCode({ redirectUri, state, code: code.code });\n}\n\nasync function issueTokenSet(params: {\n ownerEmail: string;\n orgId?: string | null;\n orgDomain?: string | null;\n clientId: string;\n scope: string;\n resource: string;\n issuer: string;\n}): Promise<Record<string, unknown>> {\n const refreshToken = generateOpaqueToken();\n await createOAuthRefreshToken({\n refreshToken,\n clientId: params.clientId,\n ownerEmail: params.ownerEmail,\n orgId: params.orgId ?? null,\n orgDomain: params.orgDomain ?? null,\n scope: params.scope,\n resource: params.resource,\n });\n const accessToken = await signMcpOAuthAccessToken(params);\n return {\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,\n refresh_token: refreshToken,\n scope: params.scope,\n };\n}\n\nasync function handleAuthorizationCodeGrant(\n event: H3Event,\n body: Record<string, string>,\n): Promise<Response> {\n const code = body.code;\n const clientId = body.client_id;\n const redirectUri = body.redirect_uri;\n const verifier = body.code_verifier;\n if (!code || !clientId || !redirectUri || !isValidCodeVerifier(verifier)) {\n return oauthError(\"invalid_request\", \"Missing authorization-code fields\");\n }\n const row = await getOAuthCode(code);\n if (!row) return oauthError(\"invalid_grant\", \"Invalid or expired code\");\n if (row.clientId !== clientId || row.redirectUri !== redirectUri) {\n return oauthError(\"invalid_grant\", \"Code was issued to another client\");\n }\n const expectedChallenge = codeChallengeForVerifier(verifier);\n if (!safeEqual(expectedChallenge, row.codeChallenge)) {\n return oauthError(\"invalid_grant\", \"PKCE verification failed\");\n }\n const consumed = await consumeOAuthCode(code);\n if (!consumed) return oauthError(\"invalid_grant\", \"Invalid or expired code\");\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer)\n return oauthError(\"server_error\", \"Unable to derive issuer\", 500);\n return json(\n await issueTokenSet({\n ownerEmail: row.ownerEmail,\n orgId: row.orgId,\n orgDomain: row.orgDomain,\n clientId,\n scope: row.scope,\n resource: row.resource,\n issuer,\n }),\n );\n}\n\nasync function handleRefreshTokenGrant(\n event: H3Event,\n body: Record<string, string>,\n): Promise<Response> {\n const refreshToken = body.refresh_token;\n const clientId = body.client_id;\n if (!refreshToken) {\n return oauthError(\"invalid_request\", \"refresh_token is required\");\n }\n if (!clientId) {\n return oauthError(\"invalid_request\", \"client_id is required\");\n }\n const existing = await getOAuthRefreshToken(refreshToken);\n if (!existing) return oauthError(\"invalid_grant\", \"Invalid refresh token\");\n if (existing.clientId !== clientId) {\n return oauthError(\n \"invalid_grant\",\n \"Refresh token belongs to another client\",\n );\n }\n await touchOAuthRefreshToken(refreshToken).catch(() => undefined);\n const issuer = getMcpOAuthIssuer(event);\n if (!issuer)\n return oauthError(\"server_error\", \"Unable to derive issuer\", 500);\n const accessToken = await signMcpOAuthAccessToken({\n ownerEmail: existing.ownerEmail,\n orgId: existing.orgId,\n orgDomain: existing.orgDomain,\n clientId: existing.clientId,\n scope: existing.scope,\n resource: existing.resource,\n issuer,\n });\n return json({\n access_token: accessToken,\n token_type: \"Bearer\",\n expires_in: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,\n refresh_token: refreshToken,\n scope: existing.scope,\n });\n}\n\nasync function handleToken(event: H3Event): Promise<Response> {\n if (getMethod(event) !== \"POST\") {\n return oauthError(\"invalid_request\", \"Method not allowed\", 405);\n }\n const body = await readOAuthParams(event);\n switch (body.grant_type) {\n case \"authorization_code\":\n return handleAuthorizationCodeGrant(event, body);\n case \"refresh_token\":\n return handleRefreshTokenGrant(event, body);\n default:\n return oauthError(\"unsupported_grant_type\", \"Unsupported grant_type\");\n }\n}\n\nexport async function handleMcpOAuth(\n event: H3Event,\n subpath: string,\n options: McpOAuthRouteOptions = {},\n): Promise<Response> {\n const path = subpath.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n try {\n if (path === \"authorize\") return await handleAuthorize(event, options);\n if (path === \"token\") return await handleToken(event);\n if (path === \"register\") return await handleRegister(event);\n setResponseStatus(event, 404);\n return json({ error: \"Not found\" }, 404);\n } catch (err: any) {\n return oauthError(\n \"server_error\",\n err?.message || \"OAuth request failed\",\n 500,\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP's public protocol path and the framework path kept for compatibility.
|
|
3
|
+
*
|
|
4
|
+
* Only the protocol and its OAuth/connect companions use the public alias.
|
|
5
|
+
* Other framework-owned MCP management routes remain under `/_agent-native`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const MCP_PUBLIC_ROUTE_PREFIX = "/mcp";
|
|
8
|
+
export declare const MCP_LEGACY_ROUTE_PREFIX = "/_agent-native/mcp";
|
|
9
|
+
export declare const MCP_ROUTE_PREFIXES: readonly ["/_agent-native/mcp", "/mcp"];
|
|
10
|
+
export declare function joinMcpRoute(prefix: string, suffix: string): string;
|
|
11
|
+
export declare function isMcpPublicPath(pathname: string): boolean;
|
|
12
|
+
export declare function isMcpProtocolPath(pathname: string): boolean;
|
|
13
|
+
//# sourceMappingURL=route-paths.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route-paths.d.ts","sourceRoot":"","sources":["../../src/mcp/route-paths.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,SAAS,CAAC;AAC9C,eAAO,MAAM,uBAAuB,uBAAuB,CAAC;AAE5D,eAAO,MAAM,kBAAkB,yCAGrB,CAAC;AAEX,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAGnE;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAKzD;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAO3D"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP's public protocol path and the framework path kept for compatibility.
|
|
3
|
+
*
|
|
4
|
+
* Only the protocol and its OAuth/connect companions use the public alias.
|
|
5
|
+
* Other framework-owned MCP management routes remain under `/_agent-native`.
|
|
6
|
+
*/
|
|
7
|
+
export const MCP_PUBLIC_ROUTE_PREFIX = "/mcp";
|
|
8
|
+
export const MCP_LEGACY_ROUTE_PREFIX = "/_agent-native/mcp";
|
|
9
|
+
export const MCP_ROUTE_PREFIXES = [
|
|
10
|
+
MCP_LEGACY_ROUTE_PREFIX,
|
|
11
|
+
MCP_PUBLIC_ROUTE_PREFIX,
|
|
12
|
+
];
|
|
13
|
+
export function joinMcpRoute(prefix, suffix) {
|
|
14
|
+
const normalizedSuffix = suffix.startsWith("/") ? suffix : `/${suffix}`;
|
|
15
|
+
return `${prefix}${normalizedSuffix}` || normalizedSuffix;
|
|
16
|
+
}
|
|
17
|
+
export function isMcpPublicPath(pathname) {
|
|
18
|
+
return (pathname === MCP_PUBLIC_ROUTE_PREFIX ||
|
|
19
|
+
pathname.startsWith(`${MCP_PUBLIC_ROUTE_PREFIX}/`));
|
|
20
|
+
}
|
|
21
|
+
export function isMcpProtocolPath(pathname) {
|
|
22
|
+
return (pathname === MCP_PUBLIC_ROUTE_PREFIX ||
|
|
23
|
+
pathname === MCP_LEGACY_ROUTE_PREFIX ||
|
|
24
|
+
pathname === `${MCP_PUBLIC_ROUTE_PREFIX}/` ||
|
|
25
|
+
pathname === `${MCP_LEGACY_ROUTE_PREFIX}/`);
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=route-paths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route-paths.js","sourceRoot":"","sources":["../../src/mcp/route-paths.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAC9C,MAAM,CAAC,MAAM,uBAAuB,GAAG,oBAAoB,CAAC;AAE5D,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,uBAAuB;IACvB,uBAAuB;CACf,CAAC;AAEX,MAAM,UAAU,YAAY,CAAC,MAAc,EAAE,MAAc;IACzD,MAAM,gBAAgB,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC;IACxE,OAAO,GAAG,MAAM,GAAG,gBAAgB,EAAE,IAAI,gBAAgB,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,QAAgB;IAC9C,OAAO,CACL,QAAQ,KAAK,uBAAuB;QACpC,QAAQ,CAAC,UAAU,CAAC,GAAG,uBAAuB,GAAG,CAAC,CACnD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,QAAgB;IAChD,OAAO,CACL,QAAQ,KAAK,uBAAuB;QACpC,QAAQ,KAAK,uBAAuB;QACpC,QAAQ,KAAK,GAAG,uBAAuB,GAAG;QAC1C,QAAQ,KAAK,GAAG,uBAAuB,GAAG,CAC3C,CAAC;AACJ,CAAC","sourcesContent":["/**\n * MCP's public protocol path and the framework path kept for compatibility.\n *\n * Only the protocol and its OAuth/connect companions use the public alias.\n * Other framework-owned MCP management routes remain under `/_agent-native`.\n */\nexport const MCP_PUBLIC_ROUTE_PREFIX = \"/mcp\";\nexport const MCP_LEGACY_ROUTE_PREFIX = \"/_agent-native/mcp\";\n\nexport const MCP_ROUTE_PREFIXES = [\n MCP_LEGACY_ROUTE_PREFIX,\n MCP_PUBLIC_ROUTE_PREFIX,\n] as const;\n\nexport function joinMcpRoute(prefix: string, suffix: string): string {\n const normalizedSuffix = suffix.startsWith(\"/\") ? suffix : `/${suffix}`;\n return `${prefix}${normalizedSuffix}` || normalizedSuffix;\n}\n\nexport function isMcpPublicPath(pathname: string): boolean {\n return (\n pathname === MCP_PUBLIC_ROUTE_PREFIX ||\n pathname.startsWith(`${MCP_PUBLIC_ROUTE_PREFIX}/`)\n );\n}\n\nexport function isMcpProtocolPath(pathname: string): boolean {\n return (\n pathname === MCP_PUBLIC_ROUTE_PREFIX ||\n pathname === MCP_LEGACY_ROUTE_PREFIX ||\n pathname === `${MCP_PUBLIC_ROUTE_PREFIX}/` ||\n pathname === `${MCP_LEGACY_ROUTE_PREFIX}/`\n );\n}\n"]}
|
package/dist/mcp/server.d.ts
CHANGED
|
@@ -35,7 +35,8 @@ export declare function handleMcpRequest(event: H3Event, config: MCPConfig): Pro
|
|
|
35
35
|
/**
|
|
36
36
|
* Mount an MCP remote server on an H3/Nitro app.
|
|
37
37
|
*
|
|
38
|
-
*
|
|
38
|
+
* Endpoints: `/mcp` (public) and `/_agent-native/mcp` (compatibility).
|
|
39
|
+
* A custom route prefix only mounts that custom endpoint.
|
|
39
40
|
*
|
|
40
41
|
* Uses stateless Streamable HTTP transport — no in-memory sessions, JSON
|
|
41
42
|
* request/response (no SSE), and no standalone GET stream, so it survives
|
package/dist/mcp/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAalC,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAalC,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,mBAAmB,CAAC;AAiB3B,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AACF,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,cAAc,EAAE,CAAC;AA+M7D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,SAAS,GAChB,OAAO,CACR,QAAQ,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAC5E,CAuKA;AAMD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,QAAQ,CACtB,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,SAAS,EACjB,WAAW,SAAmB,GAC7B,IAAI,CAiBN"}
|
package/dist/mcp/server.js
CHANGED
|
@@ -5,6 +5,7 @@ import { getH3App } from "../server/framework-request-handler.js";
|
|
|
5
5
|
import { readBody } from "../server/h3-helpers.js";
|
|
6
6
|
import { createMCPServerForRequest, verifyAuth, getAccessTokens, resolveOrgIdFromDomain, buildLinkArtifacts, } from "./build-server.js";
|
|
7
7
|
import { buildMcpOAuthChallenge, getMcpOAuthAudiences, getMcpOAuthIssuer, getMcpOAuthProtectedResourceMetadataUrl, getMcpOAuthResource, } from "./oauth-route.js";
|
|
8
|
+
import { MCP_PUBLIC_ROUTE_PREFIX, MCP_ROUTE_PREFIXES, joinMcpRoute, } from "./route-paths.js";
|
|
8
9
|
// Re-export the shared MCP server builder + types so the stdio transport and
|
|
9
10
|
// any (future) external importer of `@agent-native/core/mcp` keep resolving
|
|
10
11
|
// against `./server.js` exactly as before this refactor.
|
|
@@ -124,7 +125,7 @@ function buildWebRequest(event, method) {
|
|
|
124
125
|
const proto = forwardedProto?.split(",")[0]?.trim() ||
|
|
125
126
|
(/^(localhost|127\.0\.0\.1)(:|$)/.test(host) ? "http" : "https");
|
|
126
127
|
const basePath = getConfiguredAppBasePath();
|
|
127
|
-
const url = `${proto}://${host}${basePath}
|
|
128
|
+
const url = `${proto}://${host}${basePath}${MCP_PUBLIC_ROUTE_PREFIX}`;
|
|
128
129
|
// No body here on purpose: the JSON-RPC payload is forwarded via the
|
|
129
130
|
// transport's `parsedBody` option (the same mechanism the Node transport
|
|
130
131
|
// uses), so the request stream is never read twice.
|
|
@@ -149,7 +150,7 @@ function buildUnauthorizedBody(event) {
|
|
|
149
150
|
? `npx @agent-native/core@latest connect ${issuer}`
|
|
150
151
|
: undefined;
|
|
151
152
|
const authorizeUrl = issuer
|
|
152
|
-
? `${issuer}/
|
|
153
|
+
? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/authorize`
|
|
153
154
|
: undefined;
|
|
154
155
|
const message = command
|
|
155
156
|
? `Authentication required. Run \`${command}\` to re-authenticate this ` +
|
|
@@ -347,7 +348,8 @@ export async function handleMcpRequest(event, config) {
|
|
|
347
348
|
/**
|
|
348
349
|
* Mount an MCP remote server on an H3/Nitro app.
|
|
349
350
|
*
|
|
350
|
-
*
|
|
351
|
+
* Endpoints: `/mcp` (public) and `/_agent-native/mcp` (compatibility).
|
|
352
|
+
* A custom route prefix only mounts that custom endpoint.
|
|
351
353
|
*
|
|
352
354
|
* Uses stateless Streamable HTTP transport — no in-memory sessions, JSON
|
|
353
355
|
* request/response (no SSE), and no standalone GET stream, so it survives
|
|
@@ -362,10 +364,16 @@ export async function handleMcpRequest(event, config) {
|
|
|
362
364
|
* No auth required when neither is configured (dev mode).
|
|
363
365
|
*/
|
|
364
366
|
export function mountMCP(nitroApp, config, routePrefix = "/_agent-native") {
|
|
365
|
-
|
|
367
|
+
const routePaths = routePrefix === "/_agent-native"
|
|
368
|
+
? [...MCP_ROUTE_PREFIXES]
|
|
369
|
+
: [joinMcpRoute(routePrefix, "/mcp")];
|
|
370
|
+
const handler = defineEventHandler(async (event) => {
|
|
366
371
|
return handleMcpRequest(event, config);
|
|
367
|
-
})
|
|
372
|
+
});
|
|
373
|
+
for (const routePath of routePaths) {
|
|
374
|
+
getH3App(nitroApp).use(routePath, handler);
|
|
375
|
+
}
|
|
368
376
|
if (process.env.DEBUG)
|
|
369
|
-
console.log(`[mcp] Mounted MCP server at ${
|
|
377
|
+
console.log(`[mcp] Mounted MCP server at ${routePaths.join(" and ")} (${Object.keys(config.actions).length} tools${config.askAgent ? " + ask-agent" : ""})`);
|
|
370
378
|
}
|
|
371
379
|
//# sourceMappingURL=server.js.map
|
package/dist/mcp/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAA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AM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,QAAQ,CACtB,QAAa,EACb,MAAiB,EACjB,WAAW,GAAG,gBAAgB;IAE9B,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CACpB,GAAG,WAAW,MAAM,EACpB,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjC,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CACH,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\n\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport {\n buildMcpOAuthChallenge,\n getMcpOAuthAudiences,\n getMcpOAuthIssuer,\n getMcpOAuthProtectedResourceMetadataUrl,\n getMcpOAuthResource,\n} from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const inlineAppsHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-inline-apps\",\n )?.toLowerCase();\n const inlineAppsRequested =\n inlineAppsHeader === \"1\" ||\n inlineAppsHeader === \"true\" ||\n inlineAppsHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n ...(inlineAppsRequested ? { inlineMcpApps: true } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}/_agent-native/mcp`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n/**\n * Build an actionable JSON body for the 401 response. OAuth-capable clients\n * follow the `WWW-Authenticate` header automatically, but the JSON body is what\n * a human or a coding agent reads when a tool call comes back unauthorized — so\n * spell out the exact remediation: the `agent-native connect <url>` command and\n * the authorize/metadata URL. Keeping the legacy `error: \"Unauthorized\"` field\n * means existing clients that only check that field still work.\n */\nfunction buildUnauthorizedBody(event: H3Event): {\n error: string;\n message: string;\n authenticate: {\n command?: string;\n firstTimeCommand?: string;\n authorizeUrl?: string;\n resourceMetadataUrl?: string;\n mcpUrl?: string;\n };\n} {\n const issuer = getMcpOAuthIssuer(event);\n const mcpUrl = getMcpOAuthResource(event);\n const resourceMetadataUrl = getMcpOAuthProtectedResourceMetadataUrl(event);\n const command = issuer\n ? `npx -y @agent-native/core@latest reconnect ${issuer}`\n : undefined;\n const firstTimeCommand = issuer\n ? `npx @agent-native/core@latest connect ${issuer}`\n : undefined;\n const authorizeUrl = issuer\n ? `${issuer}/_agent-native/mcp/oauth/authorize`\n : undefined;\n const message = command\n ? `Authentication required. Run \\`${command}\\` to re-authenticate this ` +\n `MCP connector without reinstalling it (or, in a Claude Code host, ` +\n `run /mcp and choose Authenticate), then retry. For first-time ` +\n `setup, run \\`${firstTimeCommand}\\`.`\n : \"Authentication required. Authenticate the MCP connector in your host, \" +\n \"then retry.\";\n return {\n error: \"Unauthorized\",\n message,\n authenticate: {\n ...(command ? { command } : {}),\n ...(firstTimeCommand ? { firstTimeCommand } : {}),\n ...(authorizeUrl ? { authorizeUrl } : {}),\n ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),\n ...(mcpUrl ? { mcpUrl } : {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<\n Response | string | { error: string } | Record<string, unknown> | undefined\n> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthAudiences(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return buildUnauthorizedBody(event);\n }\n\n // Stateless mode: only POST is meaningful. A stateless, per-request transport\n // on serverless cannot keep the standalone GET SSE stream (server->client\n // channel) alive across invocations — once the function returns and freezes,\n // that stream dies and the client reports \"session expired\" / \"not\n // connected\". The spec lets a server that offers no GET stream answer 405, so\n // the client falls back to plain POST request/response. Reject GET here\n // instead of letting the SDK open a doomed stream.\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Optional diagnostics for host capability negotiation. Keep disabled by\n // default because initialize payloads can include client-specific metadata.\n if (process.env.MCP_DEBUG_INIT && body) {\n const msgs = Array.isArray(body) ? body : [body];\n const init = msgs.find(\n (m): m is { params?: { capabilities?: unknown; clientInfo?: unknown } } =>\n typeof m === \"object\" &&\n m !== null &&\n (m as { method?: unknown }).method === \"initialize\",\n );\n if (init) {\n console.error(\n \"[MCP_DEBUG_INIT] clientInfo=\",\n JSON.stringify(init.params?.clientInfo),\n \"capabilities=\",\n JSON.stringify(init.params?.capabilities),\n );\n }\n }\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n inlineMcpApps:\n requestMeta.inlineMcpApps === true &&\n authResult.identity?.firstPartyMcp === true\n ? true\n : undefined,\n // When the caller minted their token with --full-catalog (catalog_scope:\n // \"full\" JWT claim), bypass the connector-catalog tier filter.\n ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n // Return JSON request/response instead of SSE. A stateless serverless\n // instance can freeze right after returning a streaming Response, before\n // the deferred SSE result event is flushed — the client then never gets\n // the tools/call result and reports \"session expired\". JSON mode awaits\n // the result inside the request lifecycle and returns it as one body.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n // JSON request/response (not SSE) — see the Node fast-path note above.\n // This is the serverless-safe framing: the result is computed and returned\n // within the request, never pushed onto a stream after the instance froze.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions, JSON\n * request/response (no SSE), and no standalone GET stream, so it survives\n * serverless instances that freeze between invocations (SSE framing there\n * drops the result and clients report \"session expired\"). Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AAEZ,OAAO,EAAE,wB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AM,SAAS,CAAC,aAAa,CAC5C,UAAU,EACV,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CACrD,CAAC;IACF,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,8EAA8E;AAC9E,+DAA+D;AAC/D,8EAA8E;AAE9E;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,QAAQ,CACtB,QAAa,EACb,MAAiB,EACjB,WAAW,GAAG,gBAAgB;IAE9B,MAAM,UAAU,GACd,WAAW,KAAK,gBAAgB;QAC9B,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAAC;QACzB,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC;IAC1C,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACjD,OAAO,gBAAgB,CAAC,KAAgB,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;IAEH,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,QAAQ,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC7C,CAAC;IAED,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;QACnB,OAAO,CAAC,GAAG,CACT,+BAA+B,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CAChJ,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\n\nimport { getConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport {\n buildMcpOAuthChallenge,\n getMcpOAuthAudiences,\n getMcpOAuthIssuer,\n getMcpOAuthProtectedResourceMetadataUrl,\n getMcpOAuthResource,\n} from \"./oauth-route.js\";\nimport {\n MCP_PUBLIC_ROUTE_PREFIX,\n MCP_ROUTE_PREFIXES,\n joinMcpRoute,\n} from \"./route-paths.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\nfunction shouldUseNodeFastPath(event: H3Event): boolean {\n if (process.env.AGENT_NATIVE_MCP_NODE_FAST_PATH !== \"1\") return false;\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n return Boolean(nodeReq && nodeRes);\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host =\n getRequestHeader(event, \"x-forwarded-host\") ||\n getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n const clientName = getRequestHeader(event, \"user-agent\")?.trim() || undefined;\n const clientHint =\n getRequestHeader(event, \"x-agent-native-mcp-client\")?.trim() || undefined;\n const fullCatalogHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-full-catalog\",\n )?.toLowerCase();\n const fullCatalog =\n fullCatalogHeader === \"1\" ||\n fullCatalogHeader === \"true\" ||\n fullCatalogHeader === \"yes\";\n const inlineAppsHeader = getRequestHeader(\n event,\n \"x-agent-native-mcp-inline-apps\",\n )?.toLowerCase();\n const inlineAppsRequested =\n inlineAppsHeader === \"1\" ||\n inlineAppsHeader === \"true\" ||\n inlineAppsHeader === \"yes\";\n const basePath = getConfiguredAppBasePath();\n return {\n origin,\n ...(basePath ? { basePath } : {}),\n target,\n clientName,\n clientHint,\n ...(fullCatalog ? { fullCatalog } : {}),\n ...(inlineAppsRequested ? { inlineMcpApps: true } : {}),\n };\n}\n\nfunction isLoopbackOrigin(origin: string | undefined): boolean {\n if (!origin) return false;\n try {\n const hostname = new URL(origin).hostname;\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"[::1]\" ||\n hostname.startsWith(\"127.\")\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host =\n headers.get(\"x-forwarded-host\") || headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const basePath = getConfiguredAppBasePath();\n const url = `${proto}://${host}${basePath}${MCP_PUBLIC_ROUTE_PREFIX}`;\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n/**\n * Build an actionable JSON body for the 401 response. OAuth-capable clients\n * follow the `WWW-Authenticate` header automatically, but the JSON body is what\n * a human or a coding agent reads when a tool call comes back unauthorized — so\n * spell out the exact remediation: the `agent-native connect <url>` command and\n * the authorize/metadata URL. Keeping the legacy `error: \"Unauthorized\"` field\n * means existing clients that only check that field still work.\n */\nfunction buildUnauthorizedBody(event: H3Event): {\n error: string;\n message: string;\n authenticate: {\n command?: string;\n firstTimeCommand?: string;\n authorizeUrl?: string;\n resourceMetadataUrl?: string;\n mcpUrl?: string;\n };\n} {\n const issuer = getMcpOAuthIssuer(event);\n const mcpUrl = getMcpOAuthResource(event);\n const resourceMetadataUrl = getMcpOAuthProtectedResourceMetadataUrl(event);\n const command = issuer\n ? `npx -y @agent-native/core@latest reconnect ${issuer}`\n : undefined;\n const firstTimeCommand = issuer\n ? `npx @agent-native/core@latest connect ${issuer}`\n : undefined;\n const authorizeUrl = issuer\n ? `${issuer}${MCP_PUBLIC_ROUTE_PREFIX}/oauth/authorize`\n : undefined;\n const message = command\n ? `Authentication required. Run \\`${command}\\` to re-authenticate this ` +\n `MCP connector without reinstalling it (or, in a Claude Code host, ` +\n `run /mcp and choose Authenticate), then retry. For first-time ` +\n `setup, run \\`${firstTimeCommand}\\`.`\n : \"Authentication required. Authenticate the MCP connector in your host, \" +\n \"then retry.\";\n return {\n error: \"Unauthorized\",\n message,\n authenticate: {\n ...(command ? { command } : {}),\n ...(firstTimeCommand ? { firstTimeCommand } : {}),\n ...(authorizeUrl ? { authorizeUrl } : {}),\n ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),\n ...(mcpUrl ? { mcpUrl } : {}),\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Default path:** build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value. This is used for Nitro local dev\n * too; the direct Node writer can otherwise race h3 and double-write.\n * - **Opt-in Node fast-path:** set `AGENT_NATIVE_MCP_NODE_FAST_PATH=1` to\n * delegate directly to the SDK's `StreamableHTTPServerTransport`.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<\n Response | string | { error: string } | Record<string, unknown> | undefined\n> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen:\n isLoopbackRequest(event) && isLoopbackOrigin(requestMeta.origin),\n resourceUrl: getMcpOAuthAudiences(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return buildUnauthorizedBody(event);\n }\n\n // Stateless mode: only POST is meaningful. A stateless, per-request transport\n // on serverless cannot keep the standalone GET SSE stream (server->client\n // channel) alive across invocations — once the function returns and freezes,\n // that stream dies and the client reports \"session expired\" / \"not\n // connected\". The spec lets a server that offers no GET stream answer 405, so\n // the client falls back to plain POST request/response. Reject GET here\n // instead of letting the SDK open a doomed stream.\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Optional diagnostics for host capability negotiation. Keep disabled by\n // default because initialize payloads can include client-specific metadata.\n if (process.env.MCP_DEBUG_INIT && body) {\n const msgs = Array.isArray(body) ? body : [body];\n const init = msgs.find(\n (m): m is { params?: { capabilities?: unknown; clientInfo?: unknown } } =>\n typeof m === \"object\" &&\n m !== null &&\n (m as { method?: unknown }).method === \"initialize\",\n );\n if (init) {\n console.error(\n \"[MCP_DEBUG_INIT] clientInfo=\",\n JSON.stringify(init.params?.clientInfo),\n \"capabilities=\",\n JSON.stringify(init.params?.capabilities),\n );\n }\n }\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n inlineMcpApps:\n requestMeta.inlineMcpApps === true &&\n authResult.identity?.firstPartyMcp === true\n ? true\n : undefined,\n // When the caller minted their token with --full-catalog (catalog_scope:\n // \"full\" JWT claim), bypass the connector-catalog tier filter.\n ...(authResult.fullCatalog === true ? { fullCatalog: true } : {}),\n });\n\n if (shouldUseNodeFastPath(event)) {\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n // ---- Opt-in Node fast-path ---------------------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n // Return JSON request/response instead of SSE. A stateless serverless\n // instance can freeze right after returning a streaming Response, before\n // the deferred SSE result event is flushed — the client then never gets\n // the tools/call result and reports \"session expired\". JSON mode awaits\n // the result inside the request lifecycle and returns it as one body.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard response path (Nitro local dev, Netlify web runtime, CF,\n // Deno, Bun) ---------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n // JSON request/response (not SSE) — see the Node fast-path note above.\n // This is the serverless-safe framing: the result is computed and returned\n // within the request, never pushed onto a stream after the instance froze.\n enableJsonResponse: true,\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoints: `/mcp` (public) and `/_agent-native/mcp` (compatibility).\n * A custom route prefix only mounts that custom endpoint.\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions, JSON\n * request/response (no SSE), and no standalone GET stream, so it survives\n * serverless instances that freeze between invocations (SSE framing there\n * drops the result and clients report \"session expired\"). Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n const routePaths =\n routePrefix === \"/_agent-native\"\n ? [...MCP_ROUTE_PREFIXES]\n : [joinMcpRoute(routePrefix, \"/mcp\")];\n const handler = defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n });\n\n for (const routePath of routePaths) {\n getH3App(nitroApp).use(routePath, handler);\n }\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePaths.join(\" and \")} (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
package/dist/mcp/stdio.d.ts
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)` +
|