Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(connectors): renew a token without an expiry, and open sign-in with noopener
trohitgd734beacf2a5
diff --git a/CLAUDE.md b/CLAUDE.mdindex 00b74c8e..4256290e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -33,7 +33,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers || **[Browser](./docs-internal/browser.md)** | Current `browser` node: installed Chrome/Edge/Chromium in a dedicated profile rendered inside the workspace by default (`BROWSER_RUNTIME=system`, `BROWSER_HEADLESS=true`) and pinned browser-use CLI. Chrome for Testing requires explicit `BROWSER_RUNTIME=testing`. System mode retains the native user agent and OS password-store/keychain integration; basic/mock keychain flags are restricted to testing mode. Includes persistent employee/shared profiles (the Credentials / Connectors "Web browser" panel adds, deletes and imports logins from a session file; the node's profile dropdown lists only the caller's profiles, via `current_load_options_principal()`), session leases, agent/user handoff, network policy, screenshots as workspace FileRefs and authenticated `/ws/browser` live viewing. Plugin-owned installation is lazy (`_install_chrome.py`, `_install_bu.py`); importing or shutting down the plugin never installs it. Replaces the former agent-browser and separate `browserHarness` implementations. || **[Browser Workspace](./docs-internal/browser_workspace.md)** | Home and Dev share `WorkspaceTabs` and `BrowserWorkspace`: Browser / Canvas / Mobile, capability-based discovery, binary JPEG frames, bounded frame credit and decoding, Take control / Hand back, the agent's cursor (`agent_action`: where each click, hover, type or select happened, beside the agent's result and never during a protected login), visibility cleanup and payload-free opt-in diagnostics. The Browser node's parameter panel shows the same viewer, and the Dev dock opens on its Browser tab when an agent in the open workflow asks for help (`browser_updated`). Mobile shows the managed local Android phone. |-| **[MCP Connectors](./docs-internal/mcp_connectors.md)** | Custom connectors: the owner adds an outside MCP server from Connectors → Add (URL, name, sign-in: none, bearer, one header, or OAuth), and OpenCompany is its MCP *client* (`server/nodes/mcp/`, official `mcp` SDK; unrelated to the CLI agents' `/mcp/ide` server). The server reads the tools before keeping anything: streamable HTTP, then SSE; our own httpx client with redirects off; host and resolved addresses of every request (an OAuth sign-in's to its authorization server too) checked against `services/netpolicy.py` (shared with the Browser node: never cloud metadata or OpenCompany's own ports, plain http only on the owner's network), within `DISCOVER_S` (45 s, under the app's 60 s probe wait). Kept as `mcp:<slug>` (sign-in, encrypted; plain `model_params._mcp`: tools as accepted, per-tool `{enabled, ask}`, a waiting refresh) and `mcp:<slug>_proxy` (URL). A tool no model could call is kept with the reason, never renamed. Each connector is its own card through the generic `Credential.catalogue_entries` hook and the `_mcp_connector` template. Commands `mcp_connector_add` / `_sign_in` / `_test` / `_refresh` / `_review` / `_set_tool` / `_remove`; Refresh holds every change for Accept. Client: `AddConnectorForm.tsx` and `panels/McpConnectorPanel.tsx`. The `mcpConnector` node on an agent's Tools gives one tool per tool that is on (`ToolNode.tool_bindings`, named `<slug>__<tool>`, run with its binding's locked `mcp_tool` / `mcp_ask` / labels; arguments checked with jsonschema, a `$ref` followed only inside its schema: a tool whose inputs refer to another document is unusable, and a call goes as a plain `tools/call`, so the SDK never checks a result against an output schema the server sends; Ask first per tool through the node's `approval` spec); CLI agents leave it out and RLM refuses it. OAuth (`_oauth.py`) is the SDK's `OAuthClientProvider`: Add or Sign in again answers `sign_in_url`, the sign-in finishes in the background through `/api/mcp/oauth/callback`, tokens go to the OAuth token store under `mcp:<slug>` with their expiry (`store_oauth_tokens(..., expiry=)`), and each connection restores the expiry (read uncached with `get_stored_oauth_tokens`) and the endpoints before first use, so the SDK refreshes instead of opening a sign-in; a refused refresh says Sign in again. Each connector is also an app a hire can use: `connector_apps`, registered with `services/employees/apps.register_app_source`, is read by `Connections.apps` with `employee_apps.json`'s apps (a saved one counts as connected), `mcpConnector` is on the hire allowlist, and the employee's card reads the connector from the node's `app_field` (`mcp_connector`). |+| **[MCP Connectors](./docs-internal/mcp_connectors.md)** | Custom connectors: the owner adds an outside MCP server from Connectors → Add (URL, name, sign-in: none, bearer, one header, or OAuth), and OpenCompany is its MCP *client* (`server/nodes/mcp/`, official `mcp` SDK; unrelated to the CLI agents' `/mcp/ide` server). The server reads the tools before keeping anything: streamable HTTP, then SSE; our own httpx client with redirects off; host and resolved addresses of every request (an OAuth sign-in's to its authorization server too) checked against `services/netpolicy.py` (shared with the Browser node: never cloud metadata or OpenCompany's own ports, plain http only on the owner's network), within `DISCOVER_S` (45 s, under the app's 60 s probe wait). Kept as `mcp:<slug>` (sign-in, encrypted; plain `model_params._mcp`: tools as accepted, per-tool `{enabled, ask}`, a waiting refresh) and `mcp:<slug>_proxy` (URL). A tool no model could call is kept with the reason, never renamed. Each connector is its own card through the generic `Credential.catalogue_entries` hook and the `_mcp_connector` template. Commands `mcp_connector_add` / `_sign_in` / `_test` / `_refresh` / `_review` / `_set_tool` / `_remove`; Refresh holds every change for Accept. Client: `AddConnectorForm.tsx` and `panels/McpConnectorPanel.tsx`. The `mcpConnector` node on an agent's Tools gives one tool per tool that is on (`ToolNode.tool_bindings`, named `<slug>__<tool>`, run with its binding's locked `mcp_tool` / `mcp_ask` / labels; arguments checked with jsonschema, a `$ref` followed only inside its schema: a tool whose inputs refer to another document is unusable, and a call goes as a plain `tools/call`, so the SDK never checks a result against an output schema the server sends; Ask first per tool through the node's `approval` spec); CLI agents leave it out and RLM refuses it. OAuth (`_oauth.py`) is the SDK's `OAuthClientProvider`: Add or Sign in again answers `sign_in_url`, the sign-in finishes in the background through `/api/mcp/oauth/callback`, tokens go to the OAuth token store under `mcp:<slug>` with their expiry (`store_oauth_tokens(..., expiry=)`), and each connection restores the expiry (read uncached with `get_stored_oauth_tokens`) and the endpoints before first use, so the SDK refreshes instead of opening a sign-in; a token issued without an expiry is renewed once the server refuses it (`_oauth.connect`); a refused refresh says Sign in again. Each connector is also an app a hire can use: `connector_apps`, registered with `services/employees/apps.register_app_source`, is read by `Connections.apps` with `employee_apps.json`'s apps (a saved one counts as connected), `mcpConnector` is on the hire allowlist, and the employee's card reads the connector from the node's `app_field` (`mcp_connector`). || **[WhatsApp Business Service](./docs-internal/whatsapp_business_service.md)** | Official Meta Cloud API plugin in [`server/nodes/whatsapp_business/`](./server/nodes/whatsapp_business/) — **distinct from `nodes/whatsapp/`**, which is a personal account over an unofficial Go bridge; they share no node type, credential or palette group. Four nodes: `whatsappBusinessSend` (10 ops — Meta models message type as a *field* on one `/messages` endpoint, so text / media / template / interactive are operations, not nodes), `whatsappBusinessMedia` (the one genuinely separate endpoint family), and the `Receive` / `Status` triggers (kept separate because a canary trigger registers exactly one CloudEvents type). `phone_number_id` is deliberately **absent from Params** and comes from the credential only, because it selects the sending identity — `server_controlled_fields` would keep a model-set value out on every tool path, but an ActionNode's tool schema is its whole `Params` (`ToolInput` is ToolNode-only), so a declared field would still appear in the schema the model sees. Webhook via `register_webhook_source` on the shared catch-all, `X-Hub-Signature-256` HMAC failing closed, composite `wamid:status` dedup ids so `sent→delivered→read` don't collapse. || **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger, on a canvas Run and deployed: every Stripe event travels under one CloudEvents type, `com.opencompany.stripe.event.received`, with the Stripe type in `subject` and `data.event_type`, where the node's own `build_filter` reads it; the source shapes the payload once, wakes the in-process waiter through `WebhookSource.handle` and reaches deployed listeners through `dispatch.emit`; deploying starts `stripe listen` through the generic `TriggerNode.prepare_deployment` hook, at Start and at the boot re-arm). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. || **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). `bun add` into the shared packages tree (pinned version, via `core/js_runtime.add_package`; the CLI runs on bun). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |diff --git a/client/src/components/credentials/AddConnectorForm.tsx b/client/src/components/credentials/AddConnectorForm.tsxindex 855c0a58..ce3c5cd8 100644--- a/client/src/components/credentials/AddConnectorForm.tsx+++ b/client/src/components/credentials/AddConnectorForm.tsx@@ -63,7 +63,7 @@ export function AddConnectorForm({ close, onAdded }: AddConnectorFormProps) {if (result.success === false || !result.ref) throw new Error(result.error || FAILED);close();if (result.sign_in_url) {- window.open(result.sign_in_url, '_blank');+ window.open(result.sign_in_url, '_blank', 'noopener,noreferrer');toast.info('Sign in on the page that opened. The connector shows here once you have.');return;}diff --git a/client/src/components/credentials/__tests__/ConnectionKinds.test.tsx b/client/src/components/credentials/__tests__/ConnectionKinds.test.tsxindex a4bc7296..de84ea31 100644--- a/client/src/components/credentials/__tests__/ConnectionKinds.test.tsx+++ b/client/src/components/credentials/__tests__/ConnectionKinds.test.tsx@@ -124,7 +124,7 @@ describe.each([false, true])('connection forms with technical sections %s', (shoexpect(mocks.sendRequest).not.toHaveBeenCalled();await user.click(login);expect(mocks.sendRequest).toHaveBeenCalledWith('provider_login', {});- expect(openWindow).toHaveBeenCalledWith('https://example.com/device', '_blank');+ expect(openWindow).toHaveBeenCalledWith('https://example.com/device', '_blank', 'noopener,noreferrer');expect(await screen.findByText('ABCD-1234')).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Save Credentials' })).not.toBeInTheDocument();openWindow.mockRestore();diff --git a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsxindex 658ea1b3..4bf00e44 100644--- a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx+++ b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx@@ -99,7 +99,7 @@ describe('CredentialsBrowser', () => {fireEvent.change(form.getByLabelText('Server URL'), { target: { value: 'https://orders.example.com/mcp' } });fireEvent.click(form.getByRole('radio', { name: 'OAuth' }));fireEvent.click(form.getByRole('button', { name: 'Add' }));- await waitFor(() => expect(open).toHaveBeenCalledWith('https://auth.example.com/authorize?state=s', '_blank'));+ await waitFor(() => expect(open).toHaveBeenCalledWith('https://auth.example.com/authorize?state=s', '_blank', 'noopener,noreferrer'));expect(sendRequest).toHaveBeenCalledWith('mcp_connector_add', { name: '', url: 'https://orders.example.com/mcp', sign_in: { kind: 'oauth' } }, 60_000);expect(toast.info).toHaveBeenCalledWith('Sign in on the page that opened. The connector shows here once you have.');// Nothing is kept yet, so there is no page to open.diff --git a/client/src/components/credentials/panels/McpConnectorPanel.tsx b/client/src/components/credentials/panels/McpConnectorPanel.tsxindex be4daca7..6cd12026 100644--- a/client/src/components/credentials/panels/McpConnectorPanel.tsx+++ b/client/src/components/credentials/panels/McpConnectorPanel.tsx@@ -105,7 +105,7 @@ export default function McpConnectorPanel({ config, showTechnicalSections = falsconst signIn = async () => {const result = await run<Result & { sign_in_url?: string }>('sign_in', 'mcp_connector_sign_in');if (!result?.sign_in_url) return;- window.open(result.sign_in_url, '_blank');+ window.open(result.sign_in_url, '_blank', 'noopener,noreferrer');setNotice({ ok: true, text: 'Sign in on the page that opened.' });};diff --git a/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx b/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsxindex 641b1667..d4c64b22 100644--- a/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx+++ b/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx@@ -127,7 +127,7 @@ describe('McpConnectorPanel', () => {expect(screen.getByText('OAuth')).toBeInTheDocument();await user.click(screen.getByRole('button', { name: 'Sign in again' }));expect(mocks.sendRequest).toHaveBeenCalledWith('mcp_connector_sign_in', { ref: 'mcp:orders' }, 60_000);- await waitFor(() => expect(open).toHaveBeenCalledWith('https://auth.example.com/authorize?state=s', '_blank'));+ await waitFor(() => expect(open).toHaveBeenCalledWith('https://auth.example.com/authorize?state=s', '_blank', 'noopener,noreferrer'));expect(await screen.findByRole('status')).toHaveTextContent('Sign in on the page that opened.');open.mockRestore();});diff --git a/client/src/components/credentials/useCredentialPanel.ts b/client/src/components/credentials/useCredentialPanel.tsindex d61fb958..609c9ff1 100644--- a/client/src/components/credentials/useCredentialPanel.ts+++ b/client/src/components/credentials/useCredentialPanel.ts@@ -220,7 +220,7 @@ export function useCredentialPanel(config: ProviderConfig, visible: boolean) {oauthLogin: () => execute('login', async () => {const res = await sendRequest(config.ws!.login, {});setVerificationCode(res.success ? (res.verification_code ?? null) : null);- if (res.success && res.url) window.open(res.url, '_blank');+ if (res.success && res.url) window.open(res.url, '_blank', 'noopener,noreferrer');return res;}),oauthLogout: () => execute('logout', async () => {diff --git a/docs-internal/mcp_connectors.md b/docs-internal/mcp_connectors.mdindex ac7682f5..13a74d26 100644--- a/docs-internal/mcp_connectors.md+++ b/docs-internal/mcp_connectors.md@@ -155,8 +155,9 @@ background, since the owner finishes it in their browser:with 401. It is not sent inside an MCP session, whose 30 s read timeoutwould cut the owner off. The provider registers a client and hands overthe sign-in page's address. The command answers with it within- `DISCOVER_S`, and the app opens it in a new tab. A server that does not- answer 401 is refused: "didn't ask to sign in".+ `DISCOVER_S`, and the app opens it in a new tab with `noopener`, so the+ server's page cannot reach back into the app's own tab. A server that+ does not answer 401 is refused: "didn't ask to sign in".2. The authorization server sends the owner's browser back to`/api/mcp/oauth/callback` (`register_oauth_callback_path("mcp", ...)`;the redirect URI is this app's own address,@@ -169,18 +170,24 @@ background, since the owner finishes it in their browser:**What is kept.** The tokens go to the OAuth token store,`AuthService.store_oauth_tokens(provider="mcp:<slug>", ..., expiry=...)`. A-refresh that sends no refresh token keeps the one it had. The connector's+refresh that sends no refresh token keeps the one it had; a sign-in keeps+only its own, since it registered a new client. The connector'sencrypted sign-in (`SignIn.oauth`) keeps the client it registered, with itssecret if it got one, and the endpoints it found: the authorization server'smetadata, the server's resource metadata, and the scope.-**Connections** (`connection_auth`: Test, Refresh, and every tool call) build-a provider from those. Before first use they also set the token's expiry,-read with `AuthService.get_stored_oauth_tokens` (never cached, because-another process may have refreshed it), and the endpoints. The SDK itself-loads only the tokens and the client. Without the expiry it would send an-expired token and answer the 401 with a sign-in no one is there to finish.-With them, an expired token is refreshed and the new one kept at once.+**Connections** (`connect`, through `connection_auth`: Test, Refresh, and+every tool call) build a provider from those. Before first use they also set+the token's expiry, read with `AuthService.get_stored_oauth_tokens` (never+cached, because another process may have refreshed it), and the endpoints.+The SDK itself loads only the tokens and the client. Without the expiry it+would send an expired token and answer the 401 with a sign-in no one is+there to finish. With them, an expired token is refreshed and the new one+kept at once. A token the server gave no expiry for looks valid to the SDK+until the server refuses it, so when the server refuses one and a refresh+token is kept, `connect` opens the connection once more with the token+counted as expired, and the SDK refreshes it first. A refused request never+reached the tool, so the call is not made twice.**Sign in again.** When the refresh is refused, only the owner can sign inagain. The connection fails with `SignInNeeded`: "{name} needs you to sign indiff --git a/server/nodes/mcp/_client.py b/server/nodes/mcp/_client.pyindex a9ab31bc..073e0b50 100644--- a/server/nodes/mcp/_client.py+++ b/server/nodes/mcp/_client.py@@ -345,7 +345,7 @@ async def read_again(async with asyncio.timeout(DISCOVER_S):return await read_server(url, sign_in, transport, http_transport=http_transport, auth=auth)except Exception as exc: # noqa: BLE001 - described below, in words for the owner- raise ConnectorError(describe(exc, host)) from None+ raise failure(exc, host) from None@dataclass@@ -415,10 +415,19 @@ async def call_tool(request, types.CallToolResult, request_read_timeout_seconds=timedelta(seconds=CALL_TIMEOUT_S))except Exception as exc: # noqa: BLE001 - described below, in words for the owner- raise ConnectorError(describe(exc, host)) from None+ raise failure(exc, host) from Nonereturn CallResult(text=result_text(result), structured=result.structuredContent, is_error=bool(result.isError))+def failure(exc: BaseException, host: str) -> ConnectorError:+ """The error to raise for a failed connection: one of ours as it was+ raised (a sign-in only the owner can redo stays ``SignInNeeded``), any+ other in words for the owner."""+ while isinstance(exc, BaseExceptionGroup) and exc.exceptions:+ exc = exc.exceptions[0]+ return exc if isinstance(exc, ConnectorError) else ConnectorError(describe(exc, host))++def describe(exc: Optional[BaseException], host: str) -> str:"""A failure to reach or read a server, in words for the owner."""from mcp.shared.exceptions import McpError@@ -534,6 +543,7 @@ __all__ = ["check_server","describe","discover",+ "failure","http_client","open_session","read_again",diff --git a/server/nodes/mcp/_handlers.py b/server/nodes/mcp/_handlers.pyindex d994ae9f..cb8f09df 100644--- a/server/nodes/mcp/_handlers.py+++ b/server/nodes/mcp/_handlers.py@@ -37,7 +37,7 @@ from services.plugin.base import NodeUserErrorfrom services.plugin.ws import ws_responsefrom ._client import ConnectorError, SignIn, changes, discover, read_again, snapshots-from ._oauth import SignedIn, connection_auth, save_tokens, start_sign_in+from ._oauth import SignedIn, connect, save_tokens, start_sign_infrom ._store import (Connector,default_settings,@@ -84,8 +84,8 @@ def _redirect_uri(websocket: WebSocket) -> str:async def _read(connector: Connector):"""A saved connector's server, read again with its sign-in."""url, sign_in = await read_access(connector)- auth = await connection_auth(connector.ref, connector.name, url, sign_in)- return await read_again(url, sign_in, connector.meta.get("transport") or "streamable_http", auth=auth)+ transport = connector.meta.get("transport") or "streamable_http"+ return await connect(connector.ref, connector.name, url, sign_in, lambda auth: read_again(url, sign_in, transport, auth=auth))async def _add_signed_in(ref: str, slug: str, name: str, url: str, signed_in: SignedIn) -> str:diff --git a/server/nodes/mcp/_oauth.py b/server/nodes/mcp/_oauth.pyindex d801cdae..ee3370b0 100644--- a/server/nodes/mcp/_oauth.py+++ b/server/nodes/mcp/_oauth.py@@ -31,14 +31,19 @@ expired token and answer the 401 with a sign-in no one is there to finish.With them it refreshes an expired token, and the new one is kept. When therefresh is refused, only the owner can sign in again: the connection failswith ``SignInNeeded``.++A token the server gave no expiry for looks valid to the SDK until the+server refuses it, and a refusal makes it start a sign-in. So ``connect``+renews such a token once the server refused it, and tries again."""from __future__ import annotationsimport asyncio+import timefrom dataclasses import dataclassfrom datetime import datetime, timezone-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple, TypeVarfrom urllib.parse import parse_qs, urlsplitimport httpx@@ -53,6 +58,8 @@ if TYPE_CHECKING:logger = get_logger(__name__)+T = TypeVar("T")+CALLBACK_PATH = "/api/mcp/oauth/callback"#: How long a sign-in waits for the owner to finish it in their browser.SIGN_IN_S = 600.0@@ -118,7 +125,7 @@ class _Saved:return self.tokensasync def set_tokens(self, tokens: "OAuthToken") -> None:- await save_tokens(self.ref, tokens)+ await save_tokens(self.ref, tokens, refreshed=True)self.tokens = tokensasync def get_client_info(self) -> Optional["OAuthClientInformationFull"]:@@ -128,13 +135,14 @@ class _Saved:self.client = client_info-async def save_tokens(ref: str, tokens: "OAuthToken") -> None:+async def save_tokens(ref: str, tokens: "OAuthToken", *, refreshed: bool = False) -> None:"""Keep a connector's tokens with their expiry. A refresh that sends no- refresh token keeps the one it had."""+ refresh token keeps the one it had; a sign-in keeps only its own, since+ it registered a new client and the old token was issued to another."""from mcp.shared.auth_utils import calculate_token_expiryauth = _auth()- refresh = tokens.refresh_token or await auth.get_oauth_refresh_token(ref) or ""+ refresh = tokens.refresh_token or (await auth.get_oauth_refresh_token(ref) if refreshed else "") or ""expires = calculate_token_expiry(tokens.expires_in)kept = await auth.store_oauth_tokens(provider=ref,@@ -333,9 +341,10 @@ def _timestamp(value: Any) -> Optional[float]:return (value if value.tzinfo else value.replace(tzinfo=timezone.utc)).timestamp()-async def connection_auth(ref: str, name: str, url: str, sign_in: SignIn) -> Optional["OAuthClientProvider"]:+async def connection_auth(ref: str, name: str, url: str, sign_in: SignIn, *, renew: bool = False) -> Optional["OAuthClientProvider"]:"""How a saved connector's connection signs in with OAuth (None for any- other sign-in): the provider, with what its sign-in kept restored."""+ other sign-in): the provider, with what its sign-in kept restored.+ ``renew``: the token counts as expired, so it is refreshed first."""if sign_in.kind != "oauth":return Nonefrom mcp.client.auth import OAuthClientProvider@@ -364,18 +373,33 @@ async def connection_auth(ref: str, name: str, url: str, sign_in: SignIn) -> Optcallback_handler=refuse,)context = provider.context- context.token_expiry_time = _timestamp(stored.get("token_expiry")) if stored else None+ # A second ago: the SDK refreshes a token whose expiry has passed (no expiry means valid).+ context.token_expiry_time = time.time() - 1 if renew else (_timestamp(stored.get("token_expiry")) if stored else None)context.oauth_metadata = servercontext.protected_resource_metadata = resourcecontext.auth_server_url = kept.get("auth_server_url")return provider+async def connect(ref: str, name: str, url: str, sign_in: SignIn, use: Callable[[Optional["OAuthClientProvider"]], Awaitable[T]]) -> T:+ """``use`` a connection signed in the way the connector signs in. When the+ server refuses a token it gave no expiry for, the token is renewed and+ ``use`` runs once more; a refused request never reached the tool."""+ auth = await connection_auth(ref, name, url, sign_in)+ try:+ return await use(auth)+ except SignInNeeded:+ if auth is None or auth.context.token_expiry_time is not None or not auth.context.can_refresh_token():+ raise+ return await use(await connection_auth(ref, name, url, sign_in, renew=True))++__all__ = ["CALLBACK_PATH","SIGN_IN_S","SignInNeeded","SignedIn",+ "connect","connection_auth","finish","save_tokens",diff --git a/server/nodes/mcp/mcp_connector.py b/server/nodes/mcp/mcp_connector.pyindex 21b917a6..44464dcd 100644--- a/server/nodes/mcp/mcp_connector.py+++ b/server/nodes/mcp/mcp_connector.py@@ -27,7 +27,7 @@ from services.plugin.tool import ToolBinding, inline_schema_refsfrom ._client import ConnectorError, call_name, call_tool, check_argumentsfrom ._credentials import TEMPLATE, McpConnectorCredential-from ._oauth import connection_auth+from ._oauth import connectfrom ._store import get_connector, list_connectors, read_access, slug_of@@ -136,8 +136,10 @@ class McpConnectorNode(ToolNode):arguments = params.model_dump()check_arguments(tool["input_schema"], arguments)url, sign_in = await read_access(connector)- auth = await connection_auth(connector.ref, connector.name, url, sign_in)- result = await call_tool(url, sign_in, connector.meta.get("transport") or "streamable_http", tool["name"], arguments, auth=auth)+ transport = connector.meta.get("transport") or "streamable_http"+ result = await connect(+ connector.ref, connector.name, url, sign_in, lambda auth: call_tool(url, sign_in, transport, tool["name"], arguments, auth=auth)+ )except ConnectorError as exc:raise NodeUserError(str(exc)) from Noneif result.is_error:diff --git a/server/tests/nodes/test_mcp_connector.py b/server/tests/nodes/test_mcp_connector.pyindex 27750577..1b0a395f 100644--- a/server/tests/nodes/test_mcp_connector.py+++ b/server/tests/nodes/test_mcp_connector.py@@ -571,13 +571,21 @@ class SignsIn(httpx.AsyncBaseTransport):self.access: set = set()self.refresh: set = set()self.issued = self.refreshed = 0+ #: What its tokens come with: an expiry, and a refresh token.+ self.expires_in: int | None = 3600+ self.gives_refresh = Truedef _tokens(self, request: httpx.Request) -> httpx.Response:self.issued += 1access, refresh = f"access-{self.issued}", f"refresh-{self.issued}"self.access.add(access)- self.refresh.add(refresh)- return httpx.Response(200, json={"access_token": access, "token_type": "bearer", "expires_in": 3600, "refresh_token": refresh}, request=request)+ body: Dict[str, Any] = {"access_token": access, "token_type": "bearer"}+ if self.expires_in is not None:+ body["expires_in"] = self.expires_in+ if self.gives_refresh:+ self.refresh.add(refresh)+ body["refresh_token"] = refresh+ return httpx.Response(200, json=body, request=request)async def handle_async_request(self, request: httpx.Request) -> httpx.Response:await request.aread()@@ -669,6 +677,39 @@ class TestOAuth:await _handlers.handle_mcp_connector_remove({"ref": "mcp:orders"}, SOCKET)assert auth.oauth == {}+ async def test_a_token_without_an_expiry_is_renewed_once_the_server_refuses_it(self, auth, monkeypatch):+ context = NodeContext(node_id="n1", node_type="mcpConnector", raw={})+ async with behind_sign_in(monkeypatch, orders_server()) as gate:+ gate.expires_in = None+ await comes_back((await add(sign_in={"kind": "oauth"}))["sign_in_url"])+ assert auth.oauth["mcp:orders"]["token_expiry"] is None++ async def call() -> Dict[str, Any]:+ return await McpConnectorNode().execute_as_tool({"order": "A1"}, LOOKUP, context)++ assert (await call())["text"] == "Order A1: 2 books" and gate.refreshed == 0+ # The server stops taking the token; renewing it works.+ gate.access.clear()+ assert (await call())["text"] == "Order A1: 2 books"+ assert gate.refreshed == 1 and auth.oauth["mcp:orders"]["access_token"] == "access-2"+ gate.access.clear()+ assert (await _handlers.handle_mcp_connector_test({"ref": "mcp:orders"}, SOCKET))["ok"] is True+ assert gate.refreshed == 2+ # When renewing is refused too, only signing in again is left.+ gate.access.clear()+ gate.refresh.clear()+ assert await call() == {"error": "Orders needs you to sign in again: open it on the Connectors page and press Sign in again."}++ async def test_signing_in_again_keeps_no_refresh_token_from_before(self, auth, monkeypatch):+ async with behind_sign_in(monkeypatch, orders_server()) as gate:+ await comes_back((await add(sign_in={"kind": "oauth"}))["sign_in_url"])+ assert auth.oauth["mcp:orders"]["refresh_token"] == "refresh-1"+ # The new sign-in registers a new client; the old refresh token was not issued to it.+ gate.gives_refresh = False+ again = await _handlers.handle_mcp_connector_sign_in({"ref": "mcp:orders"}, SOCKET)+ assert "Orders is signed in again." in (await comes_back(again["sign_in_url"])).text+ assert (auth.oauth["mcp:orders"]["access_token"], auth.oauth["mcp:orders"]["refresh_token"]) == ("access-2", "")+async def test_a_refused_sign_in_keeps_nothing(self, auth, monkeypatch):async with behind_sign_in(monkeypatch, orders_server()):address = (await add(sign_in={"kind": "oauth"}))["sign_in_url"]