Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(mcp): open OAuth authorization from a start link (#3087)
rkrkrkkbbffb89df22b
diff --git a/docs/plans/mcp-hub-oauth.md b/docs/plans/mcp-hub-oauth.mdindex 0e2279cf7..200a3ffdc 100644--- a/docs/plans/mcp-hub-oauth.md+++ b/docs/plans/mcp-hub-oauth.md@@ -202,11 +202,30 @@ vibe mcp suno --login-complete '<callback URL>'vibe mcp suno --logout```-API: `POST /api/mcp/{name}/oauth/start` (body carries nothing; origin from request) →-`{authorizeUrl, mode}`; `GET /api/mcp/oauth/callback` (session-exempt, §3); `POST /api/mcp/{name}/oauth/complete`+API: `GET /api/mcp/{name}/oauth/start` is Owner-only and starts the grant from `_current_origin()`+plus `ui.setup_port`. It is a GET because the Web login control is a plain link. CSRF: only+`Sec-Fetch-Site: same-origin` (in-app click) or `none` (desktop shell handing the URL to the+system browser) may start a pending login. A missing header is allowed only when `Referer`+is same-origin (plain HTTP LAN origins omit Fetch Metadata). `cross-site`, `same-site`, a+cross-origin Referer, and a missing header with no Referer return a 403 HTML page and+create no pending login. Success is 302 to the AS authorize URL;+failure is a small i18n HTML page (same shape as the callback page), not JSON. Runtime+`oauth_start` remains for CLI/IM. `GET /api/mcp` includes per-request `oauthMode: "direct"|"paste"`+from `redirect_mode(_current_origin(), port=setup_port)` so the UI does not re-derive the origin+rule. `GET /api/mcp/oauth/callback` (session-exempt, §3); `POST /api/mcp/{name}/oauth/complete``{callbackUrl}`; `POST /api/mcp/{name}/oauth/logout`. Summary gains `auth: none|needs_login|ok`.-UI: needs-login rows show a login action. Direct and paste both open the authorize URL in a **new tab** (preallocate `about:blank` synchronously on click, then `location.replace` after start returns — never `window.location.assign` on the Avibe tab, never raw `window.open` after `await`). Avibe stays in the original tab; the callback 302s the authorize tab back to Skills & MCP. Adding an HTTP server that returns `auth: needs_login` starts this login immediately. Paste mode still shows a dialog with a paste box. Strings via i18n.+UI: needs-login rows and the detail panel render Log in as+`<a href={origin}/api/mcp/{name}/oauth/start target="_blank" rel="noopener">`+styled as a button. No `window.open`, no `about:blank`, no await before opening. Avibe stays in+the original tab; the callback 302s the authorize tab to `/skills?mcp=…&oauth=success`, and the+original tab `load()`s on `focus`/`visibilitychange`. Paste mode also opens the existing paste+dialog in the original tab when the link is clicked. After add, among added/unchanged `needs_login` servers: exactly one, Web, `oauthMode=direct`,+not desktop shell, and no failures → close the dialog and `location.assign` the start URL in+the current tab (callback 302s back to `/skills?mcp=<name>&oauth=success`). Two or more, any+failures, paste mode, or desktop shell → result state: hide the paste box, list each+"<name> needs login → Go to authorization" start link, footer Done. Zero → close and toast.+Strings via i18n.Definition: accept Claude-format `oauth: {clientId?, scopes?}` on HTTP entries; other `oauth`keys ignored (not rejected), per native extras policy.diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex b17ec7e9e..3db3e79e8 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -642,10 +642,12 @@ scenarios:- tests/test_local_deps.py- ui/src/components/ui/avault-authorization-notice.test.tsx- id: AUTH-SETUP-135- name: MCP Hub HTTP OAuth login publishes needs_login then completes through the owner callback+ name: MCP Hub HTTP OAuth login publishes needs_login then completes through GET start and callbackstatus: coveredkind: happy_pathlayer: scenariobackend: sharedtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_mcp_hub_oauth_login_completes_through_owner_callback+ supporting_tests:+ - tests/test_mcp_hub_api.py::test_oauth_start_link_redirects_to_authorize_urlnext_priority: []diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 5b03b65ac..2f2fb624c 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -177,33 +177,61 @@ def test_auth_setup_catalog_priorities_reference_live_scenarios():assert set(catalog.get("next_priority", [])) <= live_ids-def test_mcp_hub_oauth_login_completes_through_owner_callback(tmp_path):- """Scenario: AUTH-SETUP-135 — add publishes needs_login, login grant completes, tools appear."""+def test_mcp_hub_oauth_login_completes_through_owner_callback(monkeypatch, tmp_path):+ """Scenario: AUTH-SETUP-135 — add publishes needs_login; GET start and callback complete the grant."""from tests.scenario_harness.core import BaseScenarioHarness, ScenarioExpect, ScenarioRunner- from tests.test_mcp_hub_oauth import _LoopbackOauth, _run+ from tests.test_mcp_hub_oauth import _LoopbackOauthfrom core.mcp_hub import repositoryfrom core.mcp_hub.runtime import McpRuntime- from tests.ui_server_test_helpers import save_config+ from tests.ui_server_test_helpers import csrf_headers, save_config+ from vibe import internal_clientsave_config(tmp_path).save()loopback = _LoopbackOauth()loopback.start()runtime = McpRuntime()++ async def forward(operation, payload, **_kwargs):+ status, body = await runtime.submit(operation, payload)+ assert status == 200+ return json.loads(body)++ monkeypatch.setattr(internal_client, "mcp_request", forward)harness = BaseScenarioHarness()runner = ScenarioRunner(harness)+ client = app.test_client()+ headers = csrf_headers(client)started = {}def start(_h):- added = _run(runtime, "add", {"servers": [{"name": "suno", "server": {"url": f"{loopback.origin}/mcp"}}]})- assert added["ok"] and added["added"][0]["auth"] == "needs_login"+ added = client.post(+ "/api/mcp",+ json={"text": json.dumps({"mcpServers": {"suno": {"url": f"{loopback.origin}/mcp"}}})},+ headers=headers,+ )+ body = added.get_json()+ assert added.status_code == 200 and body["ok"] and body["added"][0]["auth"] == "needs_login"assert repository.list_packages()[0]["auth"] == "needs_login"- started.update(_run(runtime, "oauth_start", {"name": "suno", "origin": "http://127.0.0.1:5123", "port": 5123}))- assert started["ok"] and started["mode"] == "direct"+ response = client.get("/api/mcp/suno/oauth/start", headers={"Sec-Fetch-Site": "same-origin"})+ assert response.status_code == 302+ location = response.headers["Location"]+ assert location.startswith(f"{loopback.origin}/authorize?")+ started["authorizeUrl"] = locationdef complete(_h):query = urllib.parse.parse_qs(urllib.parse.urlparse(started["authorizeUrl"]).query)- done = _run(runtime, "oauth_callback", {"state": query["state"][0], "code": "code-1", "iss": loopback.origin})- assert done["ok"]+ done = client.get(+ "/api/mcp/oauth/callback?"+ + urllib.parse.urlencode(+ {+ "state": query["state"][0],+ "code": "code-1",+ "iss": loopback.origin,+ }+ ),+ )+ assert done.status_code == 302+ assert "/skills?mcp=suno&oauth=success" in done.headers["Location"]listed = repository.list_packages()[0]assert listed["auth"] == "ok" and listed["toolCount"] == 1diff --git a/tests/test_mcp_hub_api.py b/tests/test_mcp_hub_api.pyindex b75d276cc..d4fa958fe 100644--- a/tests/test_mcp_hub_api.py+++ b/tests/test_mcp_hub_api.py@@ -166,10 +166,93 @@ def test_malformed_json_add_returns_top_level_error_without_batch_arrays(owner):("POST", "/api/mcp/discover", "owner"),("POST", "/api/mcp/echo/refresh", "owner"),("DELETE", "/api/mcp/echo", "owner"),- ("POST", "/api/mcp/echo/oauth/start", "owner"),+ ("GET", "/api/mcp/echo/oauth/start", "owner"),("POST", "/api/mcp/echo/oauth/complete", "owner"),("POST", "/api/mcp/echo/oauth/logout", "owner"),],)def test_route_roles(method, path, role):assert http_authorization_policy(method, path).minimum_role == role+++def oauth_server(owner):+ from tests.test_mcp_hub_oauth import _LoopbackOauth++ server = _LoopbackOauth()+ server.start()+ try:+ status, _ = __import__("asyncio").run(+ owner.submit("add", {"servers": [{"name": "suno", "server": {"url": f"{server.origin}/mcp"}}]})+ )+ assert status == 200+ yield server+ finally:+ server.stop()++[email protected]("fetch_site", ["same-origin", "none"])+def test_oauth_start_link_redirects_to_authorize_url(owner, oauth_server, fetch_site):+ response = app.test_client().get("/api/mcp/suno/oauth/start", headers={"Sec-Fetch-Site": fetch_site})+ assert response.status_code == 302+ assert response.headers["Location"].startswith(f"{oauth_server.origin}/authorize?")+ assert len(owner._pending_logins) == 1++[email protected]("fetch_site", ["cross-site", "same-site"])+def test_oauth_start_link_rejects_cross_site_without_pending_login(owner, oauth_server, fetch_site):+ response = app.test_client().get("/api/mcp/suno/oauth/start", headers={"Sec-Fetch-Site": fetch_site})+ assert response.status_code == 403+ assert response.headers["Content-Type"].startswith("text/html")+ assert owner._pending_logins == {}+++def test_oauth_start_link_allows_missing_fetch_site_with_same_origin_referer(owner, oauth_server):+ response = app.test_client().get(+ "/api/mcp/suno/oauth/start",+ headers={"Referer": "http://127.0.0.1/skills"},+ )+ assert response.status_code == 302+ assert len(owner._pending_logins) == 1+++def test_oauth_start_link_rejects_missing_fetch_site_without_same_origin_referer(owner, oauth_server):+ foreign = app.test_client().get(+ "/api/mcp/suno/oauth/start",+ headers={"Referer": "https://evil.example/skills"},+ )+ assert foreign.status_code == 403+ assert owner._pending_logins == {}++ missing = app.test_client().get("/api/mcp/suno/oauth/start")+ assert missing.status_code == 403+ assert owner._pending_logins == {}++ scheme_mismatch = app.test_client().get(+ "/api/mcp/suno/oauth/start",+ headers={"Referer": "https://127.0.0.1/skills"},+ )+ assert scheme_mismatch.status_code == 403+ assert owner._pending_logins == {}+++def test_list_reports_oauth_mode_for_request_origin(owner):+ from vibe import mcp_api++ assert app.test_client().get("/api/mcp").get_json()["oauthMode"] == "direct"+ modes = {+ origin: __import__("asyncio").run(mcp_api.list_servers(origin, 5123))["oauthMode"]+ for origin in ("http://127.0.0.1:5123", "https://avibe.example", "http://192.168.1.20:5123")+ }+ assert modes == {+ "http://127.0.0.1:5123": "direct",+ "https://avibe.example": "direct",+ "http://192.168.1.20:5123": "paste",+ }+++def test_oauth_start_unknown_server_renders_html_error(owner):+ response = app.test_client().get("/api/mcp/missing/oauth/start", headers={"Sec-Fetch-Site": "same-origin"})+ assert response.status_code == 400+ assert response.headers["Content-Type"].startswith("text/html")+ assert owner._pending_logins == {}diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex d043c669f..14aefa6ce 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -98,7 +98,7 @@ _RETAINED_OWNER_ROUTES = {("POST", "/api/mcp/discover"),("POST", "/api/mcp/{name}/refresh"),("DELETE", "/api/mcp/{name}"),- ("POST", "/api/mcp/{name}/oauth/start"),+ ("GET", "/api/mcp/{name}/oauth/start"),("POST", "/api/mcp/{name}/oauth/complete"),("POST", "/api/mcp/{name}/oauth/logout"),("PUT", "/api/permissions/authorized-users"),diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsxindex 313723843..7a4cca712 100644--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx@@ -20,7 +20,6 @@ import {type ViewportPoint,} from '../../lib/showPageLaunch';import { isDesktopShell } from '../../lib/desktopShell';-import { navigatePreparedTab, openPreparedTab } from '../../lib/pwaNavigation';import { isDesktopViewport } from '../../lib/useIsDesktop';import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import { Button } from '../ui/button';@@ -124,13 +123,18 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({if (!linkHref) return;// Open synchronously inside the click gesture, then navigate after ensure;// otherwise popup blockers reject window.open after the awaited request.- const tab = openPreparedTab();+ const tab = window.open('about:blank', '_blank');if (!tab) return;+ try {+ tab.opener = null;+ } catch {+ // Some browser WindowProxy implementations expose a read-only opener.+ }if (!(await prepare())) {tab.close();return;}- navigatePreparedTab(tab, linkHref);+ if (!tab.closed) tab.location.replace(linkHref);}, [clearHoverTimer, linkHref, prepare]);const pinToDock = useCallback(async () => {diff --git a/ui/src/components/workbench/skills/McpHubSection.add.test.tsx b/ui/src/components/workbench/skills/McpHubSection.add.test.tsxnew file mode 100644index 000000000..a80f72e4e--- /dev/null+++ b/ui/src/components/workbench/skills/McpHubSection.add.test.tsx@@ -0,0 +1,191 @@+/* @vitest-environment jsdom */++import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { createInstance } from 'i18next';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ToastProvider } from '../../../context/ToastProvider';+import en from '../../../i18n/en.json';+import { RouteSurfaceActiveContext } from '../../../lib/routeSurfaceActivity';+import { OWNER_INSTANCE_CAPABILITIES } from '../../../lib/sessionInfo';+import { McpHubSection } from './McpHubSection';++const listMcpServers = vi.fn();+const addMcp = vi.fn();+const assign = vi.fn();+const replaceState = vi.fn();++vi.mock('../../../context/ApiContext', async (original) => ({+ ...(await original<typeof import('../../../context/ApiContext')>()),+ useApi: () => ({+ listMcpServers,+ addMcp,+ discoverMcp: vi.fn(),+ refreshMcp: vi.fn(),+ removeMcp: vi.fn(),+ completeMcpLogin: vi.fn(),+ }),+}));++vi.mock('../../../context/InstanceAuthorizationContext', async (original) => ({+ ...(await original<typeof import('../../../context/InstanceAuthorizationContext')>()),+ useInstanceAuthorization: () => ({ capabilities: OWNER_INSTANCE_CAPABILITIES }),+}));++vi.mock('../../../lib/desktopShell', () => ({ isDesktopShell: () => false }));++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++function renderHub() {+ return render(+ <MemoryRouter>+ <RouteSurfaceActiveContext.Provider value={true}>+ <I18nextProvider i18n={i18n}>+ <ToastProvider>+ <McpHubSection />+ </ToastProvider>+ </I18nextProvider>+ </RouteSurfaceActiveContext.Provider>+ </MemoryRouter>,+ );+}++async function submitPaste(text: string) {+ await screen.findByText('echo');+ fireEvent.click(screen.getByRole('button', { name: en.mcpHub.add }));+ const dialog = await screen.findByRole('dialog');+ fireEvent.change(within(dialog).getByPlaceholderText((value) => value.includes('mcpServers')), {+ target: { value: text },+ });+ fireEvent.click(within(dialog).getByRole('button', { name: en.mcpHub.add }));+ return dialog;+}++beforeEach(() => {+ listMcpServers.mockReset();+ addMcp.mockReset();+ assign.mockReset();+ replaceState.mockReset();+ listMcpServers.mockResolvedValue({+ ok: true,+ oauthMode: 'direct',+ servers: [{ name: 'echo', auth: 'ok', source: 'avibe', transport: 'stdio', toolCount: 1 }],+ });+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: {+ origin: 'http://127.0.0.1:5123',+ pathname: '/skills',+ search: '',+ href: 'http://127.0.0.1:5123/skills',+ assign,+ },+ });+ vi.spyOn(window.history, 'replaceState').mockImplementation(replaceState);+});++afterEach(() => {+ cleanup();+});++describe('McpHubSection add OAuth', () => {+ it('assigns the current tab to the start URL for one direct needs_login add', async () => {+ addMcp.mockResolvedValue({+ ok: true,+ added: [{ name: 'suno', auth: 'needs_login' }],+ unchanged: [],+ failed: [],+ });+ renderHub();+ await submitPaste('{"mcpServers":{"suno":{"url":"https://api.suno.com/mcp"}}}');+ await waitFor(() => {+ expect(assign).toHaveBeenCalledWith('http://127.0.0.1:5123/api/mcp/suno/oauth/start');+ });+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('keeps a result list of start links when two servers need login', async () => {+ addMcp.mockResolvedValue({+ ok: true,+ added: [+ { name: 'suno', auth: 'needs_login' },+ { name: 'github', auth: 'needs_login' },+ ],+ unchanged: [],+ failed: [],+ });+ renderHub();+ const dialog = await submitPaste('{"mcpServers":{}}');+ await within(dialog).findByText(en.mcpHub.needsLoginAfterAdd.replace('{{name}}', 'suno'));+ expect(assign).not.toHaveBeenCalled();+ expect(within(dialog).queryByPlaceholderText((value) => value.includes('mcpServers'))).toBeNull();+ expect(within(dialog).queryByRole('button', { name: en.mcpHub.add })).toBeNull();+ const links = within(dialog).getAllByRole('link', { name: en.mcpHub.goAuthorize });+ expect(links.map((node) => node.getAttribute('href'))).toEqual([+ 'http://127.0.0.1:5123/api/mcp/suno/oauth/start',+ 'http://127.0.0.1:5123/api/mcp/github/oauth/start',+ ]);+ fireEvent.click(within(dialog).getByRole('button', { name: en.common.done }));+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());+ expect(listMcpServers.mock.calls.length).toBeGreaterThan(1);+ });++ it('renders the row login control as a start-link with href, target, and rel', async () => {+ listMcpServers.mockResolvedValue({+ ok: true,+ oauthMode: 'direct',+ servers: [{ name: 'suno', auth: 'needs_login', source: 'avibe', transport: 'http', toolCount: 0, url: 'https://api.suno.com/mcp' }],+ });+ renderHub();+ const rowLogin = await screen.findByRole('link', { name: en.mcpHub.login });+ expect(rowLogin.getAttribute('href')).toBe('http://127.0.0.1:5123/api/mcp/suno/oauth/start');+ expect(rowLogin.getAttribute('target')).toBe('_blank');+ expect(rowLogin.getAttribute('rel')).toBe('noopener');+ fireEvent.click(screen.getByRole('button', { name: /suno/ }));+ const logins = screen.getAllByRole('link', { name: en.mcpHub.login });+ expect(logins).toHaveLength(2);+ for (const login of logins) {+ expect(login.getAttribute('href')).toBe('http://127.0.0.1:5123/api/mcp/suno/oauth/start');+ expect(login.getAttribute('target')).toBe('_blank');+ expect(login.getAttribute('rel')).toBe('noopener');+ }+ });++ it('selects the returned server once then lets another click take over', async () => {+ listMcpServers.mockResolvedValue({+ ok: true,+ oauthMode: 'direct',+ servers: [+ { name: 'suno', auth: 'ok', source: 'avibe', transport: 'http', toolCount: 1 },+ { name: 'echo', auth: 'ok', source: 'avibe', transport: 'stdio', toolCount: 1 },+ ],+ });+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: {+ origin: 'http://127.0.0.1:5123',+ pathname: '/skills',+ search: '?mcp=suno&oauth=success',+ href: 'http://127.0.0.1:5123/skills?mcp=suno&oauth=success',+ assign,+ },+ });+ renderHub();+ const suno = await screen.findByRole('button', { name: /suno/ });+ await waitFor(() => {+ expect(suno.className).toContain('border-mint');+ expect(replaceState).toHaveBeenCalledWith({}, '', '/skills');+ });+ fireEvent.click(screen.getByRole('button', { name: /echo/ }));+ expect(screen.getByRole('button', { name: /echo/ }).className).toContain('border-mint');+ expect(suno.className).not.toContain('border-mint');+ });+});diff --git a/ui/src/components/workbench/skills/McpHubSection.test.ts b/ui/src/components/workbench/skills/McpHubSection.test.tsnew file mode 100644index 000000000..e10e47913--- /dev/null+++ b/ui/src/components/workbench/skills/McpHubSection.test.ts@@ -0,0 +1,20 @@+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++const source = readFileSync(fileURLToPath(new URL('./McpHubSection.tsx', import.meta.url)), 'utf8');++describe('McpHubSection OAuth start link', () => {+ it('does not preallocate a blank tab or call window.open', () => {+ expect(source).not.toMatch(/window\.open/);+ expect(source).not.toMatch(/about:blank/);+ });++ it('keeps the add result copy and go-authorize start links', () => {+ expect(source).toMatch(/mcpHub\.goAuthorize/);+ expect(source).toMatch(/mcpHub\.needsLoginAfterAdd/);+ expect(source).toMatch(/mcpHub\.addResultHint/);+ expect(source).toMatch(/common\.done/);+ });+});diff --git a/ui/src/components/workbench/skills/McpHubSection.tsx b/ui/src/components/workbench/skills/McpHubSection.tsxindex f70ac3d11..0c050f943 100644--- a/ui/src/components/workbench/skills/McpHubSection.tsx+++ b/ui/src/components/workbench/skills/McpHubSection.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { ChevronDown, ChevronRight, Globe, Loader2, Plus, RefreshCw, Search, Terminal, Trash2, X } from 'lucide-react';import clsx from 'clsx';@@ -7,12 +7,41 @@ import { useApi } from '../../../context/ApiContext';import type { McpError, McpServerSummary } from '../../../context/ApiContext';import { useToast } from '../../../context/ToastContext';import { useInstanceAuthorization } from '../../../context/InstanceAuthorizationContext';+import { isDesktopShell } from '../../../lib/desktopShell';+import { mcpAddOauthAction } from '../../../lib/mcpAddOauth';import { Badge } from '../../ui/badge';import { Button } from '../../ui/button';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogTitle } from '../../ui/dialog';import { Textarea } from '../../ui/textarea';-import { pasteMayNeedOAuthLogin, preparedTabNeedsAuthorizeFallback } from '../../../lib/mcpPaste';-import { navigatePreparedTab, openLinkInNewContext, openPreparedTab } from '../../../lib/pwaNavigation';+import { buttonVariants } from '../../ui/button-variants';++function oauthStartHref(name: string): string {+ return `${window.location.origin}/api/mcp/${encodeURIComponent(name)}/oauth/start`;+}++function LoginLink({+ name,+ className,+ children,+ onActivate,+}: {+ name: string;+ className?: string;+ children: ReactNode;+ onActivate: (name: string) => void;+}) {+ return (+ <a+ href={oauthStartHref(name)}+ target="_blank"+ rel="noopener"+ className={className}+ onClick={() => onActivate(name)}+ >+ {children}+ </a>+ );+}const SOURCE_CHIP: Record<string, string> = {avibe: 'border-gold/40 bg-gold/[0.12] text-gold-ink',@@ -83,6 +112,8 @@ export const McpHubSection: React.FC = () => {const { capabilities } = useInstanceAuthorization();const canManage = capabilities.is_instance_owner;const [servers, setServers] = useState<McpServerSummary[]>([]);+ const [oauthMode, setOauthMode] = useState<'direct' | 'paste'>('direct');+ const [addResult, setAddResult] = useState<{ names: string[]; failedLines: string[] } | null>(null);const [search, setSearch] = useState('');const [selected, setSelected] = useState<string | null>(() => new URLSearchParams(window.location.search).get('mcp'));const [expandedFor, setExpandedFor] = useState<string | null>(null);@@ -92,7 +123,6 @@ export const McpHubSection: React.FC = () => {const [addText, setAddText] = useState('');const [addError, setAddError] = useState<string | null>(null);const [loginFor, setLoginFor] = useState<{ name: string } | null>(null);- const [authorizeUrl, setAuthorizeUrl] = useState<string | null>(null);const [callbackText, setCallbackText] = useState('');const [confirmDelete, setConfirmDelete] = useState<McpServerSummary | null>(null);const loginInFlight = useRef(false);@@ -119,7 +149,10 @@ export const McpHubSection: React.FC = () => {const load = useCallback(async () => {try {const res = await api.listMcpServers();- if (res.ok) setServers(res.servers ?? []);+ if (res.ok) {+ setServers(res.servers ?? []);+ if (res.oauthMode === 'direct' || res.oauthMode === 'paste') setOauthMode(res.oauthMode);+ }else showToast(describe(res.error), 'error');} catch {showToast(t('mcpHub.failed'), 'error');@@ -130,6 +163,8 @@ export const McpHubSection: React.FC = () => {const params = new URLSearchParams(window.location.search);if (params.get('oauth') === 'success') {showToast(t('mcpHub.loginComplete'), 'success');+ }+ if (params.has('mcp') || params.has('oauth')) {window.history.replaceState({}, '', window.location.pathname);}}, [load, showToast, t]);@@ -174,46 +209,9 @@ export const McpHubSection: React.FC = () => {}};- const startLogin = async (server: Pick<McpServerSummary, 'name'>, tab: Window | null) => {- setBusy(`login:${server.name}`);+ const onActivateLogin = (name: string) => {loginInFlight.current = true;- try {- const res = await api.loginMcp(server.name);- if (!res.ok) {- navigatePreparedTab(tab, null);- showToast(describe(res.error), 'error');- loginInFlight.current = false;- return;- }- const authorize = res.authorizeUrl ?? null;- if (authorize && !preparedTabNeedsAuthorizeFallback(tab)) {- navigatePreparedTab(tab, authorize);- } else {- navigatePreparedTab(tab, null);- }- if (authorize && preparedTabNeedsAuthorizeFallback(tab)) {- setLoginFor({ name: server.name });- setAuthorizeUrl(authorize);- showToast(t('mcpHub.authorizeFallback'), 'error', {- label: t('mcpHub.openAuthorize'),- onClick: () => openLinkInNewContext(authorize, 'noopener,noreferrer'),- });- } else if (res.mode !== 'direct') {- setLoginFor({ name: server.name });- setAuthorizeUrl(authorize);- }- } catch {- navigatePreparedTab(tab, null);- showToast(t('mcpHub.failed'), 'error');- loginInFlight.current = false;- } finally {- setBusy(null);- }- };-- const onLogin = (server: McpServerSummary) => {- const tab = openPreparedTab();- void startLogin(server, tab);+ if (oauthMode === 'paste') setLoginFor({ name });};useEffect(() => {@@ -236,14 +234,21 @@ export const McpHubSection: React.FC = () => {try {const res = await api.completeMcpLogin(loginFor.name, callbackText);if (!res.ok) { showToast(describe(res.error), 'error'); return; }- setLoginFor(null); setAuthorizeUrl(null); setCallbackText(''); await load();+ setLoginFor(null); setCallbackText(''); await load();showToast(t('mcpHub.loginComplete'), 'success');} finally { setBusy(null); }};+ const closeAdd = () => {+ setShowAdd(false);+ setAddText('');+ setAddError(null);+ setAddResult(null);+ };+const onAdd = async () => {- const tab = pasteMayNeedOAuthLogin(addText) ? openPreparedTab() : null;setBusy('add');setAddError(null);+ setAddResult(null);try {const res = await api.addMcp(addText);const added = res.added ?? [];@@ -261,30 +266,38 @@ export const McpHubSection: React.FC = () => {failed.length ? t('mcpHub.failedCount', { count: failed.length }) : null,...failedLines,].filter(Boolean).join('\n');- const toast = inline;const hasBatch = Boolean(res.added || res.unchanged || res.failed);if (!succeeded) {- navigatePreparedTab(tab, null);setAddError(hasBatch ? inline : describe(res.error));return;}- setShowAdd(false);- setAddText('');+ const names = [...added, ...unchanged]+ .filter((item) => item.auth === 'needs_login')+ .map((item) => item.name);+ const action = mcpAddOauthAction({+ names,+ failedCount: failed.length,+ oauthMode,+ desktopShell: isDesktopShell(),+ });+ if (action.kind === 'assign') {+ closeAdd();+ window.location.assign(oauthStartHref(action.name));+ return;+ }if (failed.length) {- showToast(toast, 'error', { label: t('common.close'), onClick: () => undefined });+ showToast(inline, 'error', { label: t('common.close'), onClick: () => undefined });} else {showToast(t('mcpHub.succeededCount', { count: succeeded }), 'success');}- const needsLogin = [...added, ...unchanged].find((item) => item.auth === 'needs_login');- if (needsLogin) {- await startLogin(needsLogin, tab);+ if (action.kind === 'list') {+ setAddResult({ names: action.names, failedLines });await load();return;}- navigatePreparedTab(tab, null);+ closeAdd();await load();} catch {- navigatePreparedTab(tab, null);showToast(t('mcpHub.failed'), 'error');} finally {setBusy(null);@@ -330,7 +343,7 @@ export const McpHubSection: React.FC = () => {{busy === 'discover' ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}{t('mcpHub.refreshAll')}</Button>- <Button type="button" variant="brand" size="xs" onClick={() => { setShowAdd(true); setAddError(null); }}>+ <Button type="button" variant="brand" size="xs" onClick={() => { setShowAdd(true); setAddError(null); setAddResult(null); }}><Plus className="size-3.5" />{t('mcpHub.add')}</Button>@@ -381,20 +394,14 @@ export const McpHubSection: React.FC = () => {</span></span>{server.auth === 'needs_login' ? (- <span- role="button"- tabIndex={0}+ <span onClick={(event) => event.stopPropagation()}>+ <LoginLink+ name={server.name}className="inline-flex h-6 items-center rounded-md border border-border bg-surface px-2 font-mono text-[10px] font-semibold uppercase text-foreground hover:bg-surface-2"- onClick={(event) => { event.stopPropagation(); void onLogin(server); }}- onKeyDown={(event) => {- if (event.key === 'Enter' || event.key === ' ') {- event.preventDefault();- event.stopPropagation();- void onLogin(server);- }- }}+ onActivate={onActivateLogin}>{t('mcpHub.login')}+ </LoginLink></span>) : null}<ChevronRight className="size-3.5 text-muted" />@@ -448,7 +455,7 @@ export const McpHubSection: React.FC = () => {? t('mcpHub.serverVersion', { version: current.serverVersion }): null}</div>- {current.auth === 'needs_login' ? <Button type="button" variant="brand" size="sm" onClick={() => void onLogin(current)}>{t('mcpHub.login')}</Button> : null}+ {current.auth === 'needs_login' ? <LoginLink name={current.name} className={buttonVariants({ variant: 'brand', size: 'sm' })} onActivate={onActivateLogin}>{t('mcpHub.login')}</LoginLink> : null}{canManage ? (<div className="flex items-center gap-2 pt-1"><Button type="button" variant="outline" size="xs" disabled={busy !== null} onClick={() => void onRefreshOne(current.name)}>@@ -469,25 +476,49 @@ export const McpHubSection: React.FC = () => {<DialogContent className="max-w-lg" closeLabel={t('common.close')}><DialogTitle>{t('mcpHub.loginTitle')}</DialogTitle><DialogDescription>{t('mcpHub.loginHint')}</DialogDescription>- {authorizeUrl ? <Button type="button" variant="outline" onClick={() => openLinkInNewContext(authorizeUrl, 'noopener,noreferrer')}>{t('mcpHub.openAuthorize')}</Button> : null}+ {loginFor ? <LoginLink name={loginFor.name} className={buttonVariants({ variant: 'outline' })} onActivate={onActivateLogin}>{t('mcpHub.openAuthorize')}</LoginLink> : null}<Textarea value={callbackText} onChange={(event) => setCallbackText(event.target.value)} className="min-h-20 font-mono text-[12px]" placeholder={t('mcpHub.callbackPlaceholder')} /><DialogFooter><Button type="button" variant="outline" onClick={() => setLoginFor(null)}>{t('common.cancel')}</Button><Button type="button" disabled={!callbackText.trim() || busy !== null} onClick={() => void onCompleteLogin()}>{t('mcpHub.completeLogin')}</Button></DialogFooter></DialogContent></Dialog>- <Dialog open={showAdd} onOpenChange={(open) => (!open ? setShowAdd(false) : undefined)}>+ <Dialog open={showAdd} onOpenChange={(open) => (!open ? closeAdd() : undefined)}><DialogContent className="max-w-lg" closeLabel={t('common.close')}><DialogTitle>{t('mcpHub.addTitle')}</DialogTitle>- <DialogDescription>{t('mcpHub.addSubtitle')}</DialogDescription>- <Textarea value={addText} onChange={(event) => setAddText(event.target.value)} className="min-h-40 font-mono text-[12px]" placeholder={t('mcpHub.pastePlaceholder')} />- <p className="text-[11px] text-muted">{t('mcpHub.pasteHint')}</p>- {addError ? <div className="whitespace-pre-wrap text-[12px] text-destructive-ink">{addError}</div> : null}+ <DialogDescription>{addResult ? t('mcpHub.addResultHint') : t('mcpHub.addSubtitle')}</DialogDescription>+ {addResult ? (+ <div className="flex flex-col gap-2">+ {addResult.names.map((name) => (+ <p key={name} className="flex items-center gap-2 text-[12px] text-foreground">+ <span>{t('mcpHub.needsLoginAfterAdd', { name })}</span>+ <LoginLink name={name} className={buttonVariants({ variant: 'brand', size: 'xs' })} onActivate={onActivateLogin}>+ {t('mcpHub.goAuthorize')}+ </LoginLink>+ </p>+ ))}+ {addResult.failedLines.map((line) => (+ <div key={line} className="text-[12px] text-destructive-ink">{line}</div>+ ))}+ </div>+ ) : (+ <>+ <Textarea value={addText} onChange={(event) => setAddText(event.target.value)} className="min-h-40 font-mono text-[12px]" placeholder={t('mcpHub.pastePlaceholder')} />+ <p className="text-[11px] text-muted">{t('mcpHub.pasteHint')}</p>+ {addError ? <div className="whitespace-pre-wrap text-[12px] text-destructive-ink">{addError}</div> : null}+ </>+ )}<DialogFooter>- <Button type="button" variant="outline" onClick={() => setShowAdd(false)}>{t('common.cancel')}</Button>- <Button type="button" disabled={busy !== null || !addText.trim()} onClick={() => void onAdd()}>- {busy === 'add' ? <Loader2 className="size-3.5 animate-spin" /> : null}- {t('mcpHub.add')}- </Button>+ {addResult ? (+ <Button type="button" variant="brand" onClick={() => { closeAdd(); void load(); }}>{t('common.done')}</Button>+ ) : (+ <>+ <Button type="button" variant="outline" onClick={closeAdd}>{t('common.cancel')}</Button>+ <Button type="button" disabled={busy !== null || !addText.trim()} onClick={() => void onAdd()}>+ {busy === 'add' ? <Loader2 className="size-3.5 animate-spin" /> : null}+ {t('mcpHub.add')}+ </Button>+ </>+ )}</DialogFooter></DialogContent></Dialog>diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 35f504c3d..1b05da60d 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -600,7 +600,6 @@ export interface McpDefinition {};}export interface McpResult { ok: boolean; error?: McpError }-export type McpOAuthStartResult = McpResult & { authorizeUrl?: string; mode?: 'direct' | 'paste' };export type McpOAuthMutationResult = McpResult & { name?: string };export interface McpTool { name: string; description?: string; inputSchema?: unknown; flags: { flag: string; kind: string; required: boolean }[] }@@ -952,7 +951,7 @@ export type ApiContextType = {importVibeAgents: (payload: { from?: NativeCliBackend; name?: string; all?: boolean; file?: string; backend?: string }) => Promise<{ ok: boolean; imported?: any[]; skipped?: any[]; error?: string; code?: string; message?: string }>;// Agent Skills — thin shells over the askill CLI (see /api/skills*).listSkills: (params?: { scope?: SkillScope | 'all'; projectId?: string; backends?: string[] }) => Promise<SkillsListResult>;- listMcpServers: () => Promise<McpResult & { servers?: McpServerSummary[] }>;+ listMcpServers: () => Promise<McpResult & { servers?: McpServerSummary[]; oauthMode?: 'direct' | 'paste' }>;addMcp: (text: string) => Promise<McpResult & {saved?: string[];name?: string;@@ -964,7 +963,6 @@ export type ApiContextType = {discoverMcp: () => Promise<McpResult & { results?: { name: string; status: string; error?: string; toolCount?: number }[] }>;refreshMcp: (name: string) => Promise<McpResult & { name?: string; toolCount?: number }>;removeMcp: (name: string) => Promise<McpResult>;- loginMcp: (name: string) => Promise<McpOAuthStartResult>;completeMcpLogin: (name: string, callbackUrl: string) => Promise<McpOAuthMutationResult>;getMcpServer: (name: string) => Promise<McpResult & { server?: McpServerSummary; tools?: McpTool[] }>;previewSkillSource: (source: string, params?: { projectId?: string }) => Promise<SkillsPreviewResult>;@@ -4370,7 +4368,6 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrendiscoverMcp: () => postJson('/api/mcp/discover', {}, { handleError: false }),refreshMcp: (name) => postJson(`/api/mcp/${encodeURIComponent(name)}/refresh`, {}, { handleError: false }),removeMcp: (name) => deleteJson(`/api/mcp/${encodeURIComponent(name)}`, undefined, { handleError: false }),- loginMcp: (name) => postJson(`/api/mcp/${encodeURIComponent(name)}/oauth/start`, {}, { handleError: false }),completeMcpLogin: (name, callbackUrl) => postJson(`/api/mcp/${encodeURIComponent(name)}/oauth/complete`, { callbackUrl }, { handleError: false }),getMcpServer: (name) => getJson(`/api/mcp/${encodeURIComponent(name)}`, { handleError: false }),previewSkillSource: (source, params) =>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex e39c2923d..153606005 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -6549,9 +6549,11 @@"loginTitle": "Log in to MCP server","loginHint": "Authorize in the new tab, then paste the callback URL here when needed.","openAuthorize": "Open authorization",- "authorizeFallback": "The authorization tab could not be opened. Use Open authorization to continue.","callbackPlaceholder": "Paste the callback URL","completeLogin": "Complete login",+ "needsLoginAfterAdd": "{{name}} needs login",+ "goAuthorize": "Go to authorization",+ "addResultHint": "These servers need login before their tools are available.","loginComplete": "MCP login completed"}}diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex ec45d1710..8e3653846 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -6549,9 +6549,11 @@"loginTitle": "登录 MCP 服务器","loginHint": "在新标签页中授权;如有需要,将回调 URL 粘贴到这里。","openAuthorize": "打开授权页面",- "authorizeFallback": "无法打开授权标签页。请点击「打开授权页面」继续。","callbackPlaceholder": "粘贴回调 URL","completeLogin": "完成登录",+ "needsLoginAfterAdd": "{{name}} 需要登录",+ "goAuthorize": "前往授权",+ "addResultHint": "这些服务器需要登录后才能提供工具。","loginComplete": "MCP 登录完成"}}diff --git a/ui/src/lib/mcpAddOauth.test.ts b/ui/src/lib/mcpAddOauth.test.tsnew file mode 100644index 000000000..4abb57458--- /dev/null+++ b/ui/src/lib/mcpAddOauth.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import { mcpAddOauthAction } from './mcpAddOauth';++describe('mcpAddOauthAction', () => {+ it('assigns the current tab to the start URL for one direct Web login', () => {+ expect(+ mcpAddOauthAction({ names: ['suno'], failedCount: 0, oauthMode: 'direct', desktopShell: false }),+ ).toEqual({ kind: 'assign', name: 'suno' });+ });++ it('lists login links when more than one server needs login', () => {+ expect(+ mcpAddOauthAction({+ names: ['suno', 'github'],+ failedCount: 0,+ oauthMode: 'direct',+ desktopShell: false,+ }),+ ).toEqual({ kind: 'list', names: ['suno', 'github'] });+ });++ it('lists login links when any add failed, even for a single needs_login server', () => {+ expect(+ mcpAddOauthAction({ names: ['suno'], failedCount: 1, oauthMode: 'direct', desktopShell: false }),+ ).toEqual({ kind: 'list', names: ['suno'] });+ });++ it('does not assign in paste mode or the desktop shell', () => {+ expect(+ mcpAddOauthAction({ names: ['suno'], failedCount: 0, oauthMode: 'paste', desktopShell: false }),+ ).toEqual({ kind: 'list', names: ['suno'] });+ expect(+ mcpAddOauthAction({ names: ['suno'], failedCount: 0, oauthMode: 'direct', desktopShell: true }),+ ).toEqual({ kind: 'list', names: ['suno'] });+ });++ it('does nothing when no added server needs login', () => {+ expect(+ mcpAddOauthAction({ names: [], failedCount: 0, oauthMode: 'direct', desktopShell: false }),+ ).toEqual({ kind: 'none' });+ });+});diff --git a/ui/src/lib/mcpAddOauth.ts b/ui/src/lib/mcpAddOauth.tsnew file mode 100644index 000000000..bef7c05bb--- /dev/null+++ b/ui/src/lib/mcpAddOauth.ts@@ -0,0 +1,21 @@+export type McpOauthMode = 'direct' | 'paste';++export type McpAddOauthAction =+ | { kind: 'assign'; name: string }+ | { kind: 'list'; names: string[] }+ | { kind: 'none' };++/** After a successful add, decide same-tab start vs a result list of login links. */+export function mcpAddOauthAction(input: {+ names: string[];+ failedCount: number;+ oauthMode: McpOauthMode;+ desktopShell: boolean;+}): McpAddOauthAction {+ const names = input.names.filter(Boolean);+ if (names.length === 0) return { kind: 'none' };+ if (names.length === 1 && input.failedCount === 0 && input.oauthMode === 'direct' && !input.desktopShell) {+ return { kind: 'assign', name: names[0] };+ }+ return { kind: 'list', names };+}diff --git a/ui/src/lib/mcpPaste.test.ts b/ui/src/lib/mcpPaste.test.tsdeleted file mode 100644index b4f5508d5..000000000--- a/ui/src/lib/mcpPaste.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, expect, it } from 'vitest';--import { pasteMayNeedOAuthLogin, preparedTabNeedsAuthorizeFallback } from './mcpPaste';--describe('pasteMayNeedOAuthLogin', () => {- it('is true for an HTTP URL server without Authorization', () => {- expect(- pasteMayNeedOAuthLogin(- JSON.stringify({ mcpServers: { suno: { url: 'https://api.example/mcp' } } }),- ),- ).toBe(true);- });-- it('is false for stdio command servers', () => {- expect(- pasteMayNeedOAuthLogin(- JSON.stringify({ mcpServers: { echo: { command: 'npx', args: ['-y', 'echo'] } } }),- ),- ).toBe(false);- });-- it('is false when Authorization is already set', () => {- expect(- pasteMayNeedOAuthLogin(- JSON.stringify({- mcpServers: {- github: {- url: 'https://api.githubcopilot.com/mcp/',- headers: { Authorization: 'Bearer tok' },- },- },- }),- ),- ).toBe(false);- });-- it('treats authorization header names case-insensitively', () => {- expect(- pasteMayNeedOAuthLogin(- JSON.stringify({- mcpServers: { github: { url: 'https://api.example/mcp', headers: { authorization: 'Bearer tok' } } },- }),- ),- ).toBe(false);- });-- it('is true when a batch mixes stdio with one OAuth-eligible URL server', () => {- expect(- pasteMayNeedOAuthLogin(- JSON.stringify({- mcpServers: {- echo: { command: 'npx' },- suno: { url: 'https://api.example/mcp' },- },- }),- ),- ).toBe(true);- });-- it('is false when JSON cannot be parsed', () => {- expect(pasteMayNeedOAuthLogin('{not json')).toBe(false);- });-});--describe('preparedTabNeedsAuthorizeFallback', () => {- it('falls back when the popup was blocked', () => {- expect(preparedTabNeedsAuthorizeFallback(null)).toBe(true);- });-- it('falls back when the prepared tab was closed before navigation', () => {- expect(preparedTabNeedsAuthorizeFallback({ closed: true } as Window)).toBe(true);- });-- it('does not fall back for an open prepared tab', () => {- expect(preparedTabNeedsAuthorizeFallback({ closed: false } as Window)).toBe(false);- });-});diff --git a/ui/src/lib/mcpPaste.ts b/ui/src/lib/mcpPaste.tsdeleted file mode 100644index f5e33e4a0..000000000--- a/ui/src/lib/mcpPaste.ts+++ /dev/null@@ -1,29 +0,0 @@-/** True when paste includes an HTTP MCP server that Hub can OAuth-login. */-export function pasteMayNeedOAuthLogin(text: string): boolean {- try {- const parsed: unknown = JSON.parse(text);- if (!parsed || typeof parsed !== 'object') return false;- const servers = (parsed as { mcpServers?: unknown }).mcpServers;- const entries =- servers && typeof servers === 'object' && !Array.isArray(servers)- ? Object.values(servers as Record<string, unknown>)- : [parsed];- return entries.some(isOAuthEligiblePasteServer);- } catch {- return false;- }-}--function isOAuthEligiblePasteServer(value: unknown): boolean {- if (!value || typeof value !== 'object') return false;- const server = value as Record<string, unknown>;- const url = typeof server.url === 'string' && server.url.trim();- if (!url || server.command) return false;- const headers = server.headers;- if (!headers || typeof headers !== 'object' || Array.isArray(headers)) return true;- return !Object.keys(headers as Record<string, unknown>).some((key) => key.toLowerCase() === 'authorization');-}--export function preparedTabNeedsAuthorizeFallback(tab: Window | null): boolean {- return tab == null || tab.closed;-}diff --git a/ui/src/lib/pwaNavigation.test.ts b/ui/src/lib/pwaNavigation.test.tsindex 77c473272..3dcce006d 100644--- a/ui/src/lib/pwaNavigation.test.ts+++ b/ui/src/lib/pwaNavigation.test.ts@@ -6,9 +6,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';import {internalPwaLinkTarget,- navigatePreparedTab,openLinkInNewContext,- openPreparedTab,shouldBlockPwaLoopbackLink,} from './pwaNavigation';@@ -248,26 +246,10 @@ describe('programmatic PWA navigation', () => {.sort((left, right) => left.path.localeCompare(right.path));expect(directCalls).toEqual([- { path: 'lib/pwaNavigation.ts', count: 2 },+ { path: 'components/workbench/ShowPageLaunchControl.tsx', count: 1 },+ { path: 'lib/pwaNavigation.ts', count: 1 },]);- });-- it('does not navigate the Avibe tab for MCP OAuth', () => {- const text = readFileSync(new URL('../components/workbench/skills/McpHubSection.tsx', import.meta.url), 'utf8');- expect(text).not.toMatch(/location\.assign/);- });- it('preallocates a blank tab and severs opener before later navigation', () => {- const tab = { opener: {} as Window, closed: false, close: vi.fn(), location: { replace: vi.fn() } };- const nativeOpen = vi.fn(() => tab);- vi.stubGlobal('window', { open: nativeOpen });- expect(openPreparedTab()).toBe(tab);- expect(nativeOpen).toHaveBeenCalledWith('about:blank', '_blank');- expect(tab.opener).toBeNull();- navigatePreparedTab(tab as unknown as Window, 'https://as.example/authorize');- expect(tab.location.replace).toHaveBeenCalledWith('https://as.example/authorize');- navigatePreparedTab(tab as unknown as Window, null);- expect(tab.close).toHaveBeenCalled();});it('severs the opener of every preallocated blank tab', () => {diff --git a/ui/src/lib/pwaNavigation.ts b/ui/src/lib/pwaNavigation.tsindex eccf8b04c..e3ce064f5 100644--- a/ui/src/lib/pwaNavigation.ts+++ b/ui/src/lib/pwaNavigation.ts@@ -82,28 +82,3 @@ export function openLinkInNewContext(href: string, features?: string): Window |if (window.__AVIBE_PWA_NAVIGATE_SAME_ORIGIN__?.(href)) return null;return window.open(href, '_blank', features);}--/**- * Open a blank tab inside the click gesture so a later awaited request can- * still navigate it. Popup blockers reject `window.open` after `await`.- */-export function openPreparedTab(): Window | null {- if (typeof window === 'undefined') return null;- const tab = window.open('about:blank', '_blank');- if (!tab) return null;- try {- tab.opener = null;- } catch {- // Some WindowProxy implementations expose a read-only opener.- }- return tab;-}--export function navigatePreparedTab(tab: Window | null, href: string | null | undefined): void {- if (!tab || tab.closed) return;- if (!href) {- tab.close();- return;- }- tab.location.replace(href);-}diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 8dce407f6..b1b5d122e 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1798,5 +1798,7 @@}},"mcp_oauth_callback_success": "MCP OAuth login completed. You can close this tab.",- "mcp_oauth_callback_failure": "MCP OAuth login could not be completed. Return to Avibe and try again."+ "mcp_oauth_callback_failure": "MCP OAuth login could not be completed. Return to Avibe and try again.",+ "mcp_oauth_start_failure": "MCP OAuth login could not be started. Return to Avibe and try again.",+ "mcp_oauth_start_rejected": "This MCP OAuth link must be opened from Avibe."}diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 5a7512d1a..9eab56a26 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1798,5 +1798,7 @@}},"mcp_oauth_callback_success": "MCP OAuth 登录已完成,可以关闭此标签页。",- "mcp_oauth_callback_failure": "MCP OAuth 登录未完成,请返回 Avibe 重试。"+ "mcp_oauth_callback_failure": "MCP OAuth 登录未完成,请返回 Avibe 重试。",+ "mcp_oauth_start_failure": "MCP OAuth 登录无法开始,请返回 Avibe 重试。",+ "mcp_oauth_start_rejected": "请从 Avibe 中打开此 MCP OAuth 链接。"}diff --git a/vibe/mcp_api.py b/vibe/mcp_api.pyindex aadc50011..9040554e5 100644--- a/vibe/mcp_api.py+++ b/vibe/mcp_api.py@@ -53,8 +53,15 @@ async def run(handler, *args) -> tuple[dict[str, Any], int]:return _error(McpHubError("internal", str(exc) or "Unexpected MCP Hub error."))-async def list_servers() -> dict[str, Any]:- return {"ok": True, "servers": await asyncio.to_thread(repository.list_packages)}+async def list_servers(origin: str | None = None, port: int | None = None) -> dict[str, Any]:+ from core.mcp_hub.oauth import redirect_mode++ body: dict[str, Any] = {"ok": True, "servers": await asyncio.to_thread(repository.list_packages)}+ try:+ body["oauthMode"] = redirect_mode(origin, port=port)[0]+ except McpHubError:+ body["oauthMode"] = "paste"+ return bodyasync def add(body: dict[str, Any]) -> dict[str, Any]:@@ -99,6 +106,8 @@ async def refresh(name: str) -> dict[str, Any]:async def remove(name: str) -> dict[str, Any]:return await _owner("remove", {"name": name})++async def oauth_start(name: str, body: dict[str, Any], origin: str | None = None) -> dict[str, Any]:payload: dict[str, Any] = {"name": name, "origin": origin}if body.get("port") is not None:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 01f49fc2b..4f1d37be0 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -9521,7 +9521,7 @@ async def _mcp_route(starlette_request: FastAPIRequest, handler, *args):async def mcp_list(starlette_request: FastAPIRequest):from vibe import mcp_api- return await _mcp_route(starlette_request, mcp_api.list_servers)+ return await _mcp_route(starlette_request, lambda: mcp_api.list_servers(_current_origin(), _mcp_setup_port()))@app.post("/api/mcp", include_in_schema=False)@@ -9558,15 +9558,57 @@ async def mcp_remove(name: str, starlette_request: FastAPIRequest):return await _mcp_route(starlette_request, mcp_api.remove, name)[email protected]("/api/mcp/{name}/oauth/start", include_in_schema=False)+def _mcp_setup_port() -> int:+ from config.v2_config import V2Config++ return int(V2Config.load().ui.setup_port)+++def _mcp_oauth_page(message_key: str, status: int) -> Response:+ from vibe.i18n import t as i18n_t++ message = html.escape(i18n_t(message_key))+ return Response(content=f"<!doctype html><title>MCP OAuth</title><main><p>{message}</p></main>", status_code=status, media_type="text/html")+++# The Web login button is a plain link, so this GET starts a grant. Only a+# same-origin navigation or one with no initiator (the desktop shell handing the+# link to the system browser) may start it; cross-site requests are CSRF.+# Fetch Metadata is omitted on non-trustworthy HTTP origins (LAN paste mode);+# those navigations still send a same-origin Referer.+_MCP_OAUTH_START_FETCH_SITES = {"same-origin", "none"}+++def _mcp_oauth_start_allowed(starlette_request: FastAPIRequest) -> bool:+ site = (starlette_request.headers.get("Sec-Fetch-Site") or "").lower()+ if site in _MCP_OAUTH_START_FETCH_SITES:+ return True+ if site:+ return False+ referer = starlette_request.headers.get("Referer") or ""+ try:+ parsed = urlparse(referer)+ origin = f"{parsed.scheme}://{parsed.netloc}"+ return bool(parsed.scheme and parsed.netloc) and origin == _current_origin()+ except ValueError:+ return False++[email protected]("/api/mcp/{name}/oauth/start", include_in_schema=False)async def mcp_oauth_start(name: str, starlette_request: FastAPIRequest):- from vibe import mcp_api- def start():- body = _mcp_body()- from config.v2_config import V2Config- body["port"] = int(V2Config.load().ui.setup_port)- return mcp_api.oauth_start(name, body, _current_origin())- return await _mcp_route(starlette_request, start)+ async def start():+ from starlette.responses import RedirectResponse++ from vibe import mcp_api++ if not _mcp_oauth_start_allowed(starlette_request):+ return _mcp_oauth_page("mcp_oauth_start_rejected", 403)+ body, _status = await mcp_api.run(mcp_api.oauth_start, name, {"port": _mcp_setup_port()}, _current_origin())+ if body.get("ok") and body.get("authorizeUrl"):+ return RedirectResponse(body["authorizeUrl"], status_code=302)+ return _mcp_oauth_page("mcp_oauth_start_failure", 400)++ return await _dispatch_native_ui_request(starlette_request, start)@app.get("/api/mcp/oauth/callback", include_in_schema=False)@@ -9577,9 +9619,7 @@ async def mcp_oauth_callback(starlette_request: FastAPIRequest):if body.get("redirect"):from starlette.responses import RedirectResponsereturn RedirectResponse(body["redirect"], status_code=302)- from vibe.i18n import t as i18n_t- message = i18n_t("mcp_oauth_callback_success" if body.get("ok") else "mcp_oauth_callback_failure")- return Response(content=f"<!doctype html><title>MCP OAuth</title><main><p>{message}</p></main>", status_code=status, media_type="text/html")+ return _mcp_oauth_page("mcp_oauth_callback_success" if body.get("ok") else "mcp_oauth_callback_failure", status)@app.post("/api/mcp/{name}/oauth/complete", include_in_schema=False)