Skip to content

Self-improving AI Employees for everyone

feat(connectors): sign a custom connector in with OAuth

trohitg7166e24b87e2
diff --git a/CLAUDE.md b/CLAUDE.md
index 32ce477a..a3e4e3bf 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 or one header), 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 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` / `_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; Ask first per tool through the node's `approval` spec); CLI agents leave it out and RLM refuses it. 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; 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`). |
| **[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.tsx
index 505bef12..855c0a58 100644
--- a/client/src/components/credentials/AddConnectorForm.tsx
+++ b/client/src/components/credentials/AddConnectorForm.tsx
@@ -1,19 +1,23 @@
/**
* The Connectors page's form for a custom connector: an MCP server's URL, a
- * name, and how it signs in (none, a bearer token, or one header). The
- * server reads the server's tools before keeping anything
- * (`mcp_connector_add`, nodes/mcp/_handlers.py), so a wrong URL or a refused
- * sign-in comes back here in the server's words and nothing is saved.
+ * name, and how it signs in (none, a bearer token, one header, or OAuth on
+ * the server's own sign-in page). The server reads the server's tools before
+ * keeping anything (`mcp_connector_add`, nodes/mcp/_handlers.py), so a wrong
+ * URL or a refused sign-in comes back here in the server's words and nothing
+ * is saved. With OAuth it answers with the sign-in page, which opens in a new
+ * tab: the connector is kept, and its card shows, once the owner signed in
+ * there.
*/
import { useId, useState, type FormEvent } from 'react';
+import { toast } from 'sonner';
import { ActionButton } from '@/components/ui/action-button';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { CREDENTIAL_PROBE_REQUEST_TIMEOUT, useWebSocketActions } from '@/contexts/WebSocketContext';
-type SignInKind = 'none' | 'bearer' | 'header';
+type SignInKind = 'none' | 'bearer' | 'header' | 'oauth';
const FIELD = 'h-9.5 rounded-lg bg-bg-app text-row font-normal md:text-row dark:bg-bg-app';
const FAILED = "Couldn't add that connector. Try again.";
@@ -36,7 +40,8 @@ export function AddConnectorForm({ close, onAdded }: AddConnectorFormProps) {
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
- const signedIn = signIn === 'none' || (signIn === 'bearer' ? token.trim() !== '' : header.trim() !== '' && value.trim() !== '');
+ const signedIn =
+ signIn === 'none' || signIn === 'oauth' || (signIn === 'bearer' ? token.trim() !== '' : header.trim() !== '' && value.trim() !== '');
const ready = isReady && !saving && url.trim() !== '' && signedIn;
const submit = async (event: FormEvent) => {
@@ -45,17 +50,23 @@ export function AddConnectorForm({ close, onAdded }: AddConnectorFormProps) {
setSaving(true);
setError('');
try {
- const result = await sendRequest<{ success?: boolean; error?: string; ref?: string }>(
+ const result = await sendRequest<{ success?: boolean; error?: string; ref?: string; sign_in_url?: string }>(
'mcp_connector_add',
{
name,
url,
- sign_in: signIn === 'bearer' ? { kind: 'bearer', token } : signIn === 'header' ? { kind: 'header', header, value } : { kind: 'none' },
+ sign_in:
+ signIn === 'bearer' ? { kind: 'bearer', token } : signIn === 'header' ? { kind: 'header', header, value } : { kind: signIn },
},
CREDENTIAL_PROBE_REQUEST_TIMEOUT,
);
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');
+ toast.info('Sign in on the page that opened. The connector shows here once you have.');
+ return;
+ }
onAdded(result.ref);
} catch (cause) {
setError(cause instanceof Error && cause.message ? cause.message : FAILED);
@@ -104,6 +115,9 @@ export function AddConnectorForm({ close, onAdded }: AddConnectorFormProps) {
<ToggleGroupItem value="header" className="px-3 text-sm">
Header
</ToggleGroupItem>
+ <ToggleGroupItem value="oauth" className="px-3 text-sm">
+ OAuth
+ </ToggleGroupItem>
</ToggleGroup>
</div>
{signIn === 'bearer' && (
@@ -149,7 +163,7 @@ export function AddConnectorForm({ close, onAdded }: AddConnectorFormProps) {
Cancel
</Button>
<ActionButton intent="run" type="submit" disabled={!ready} className="h-7.5 rounded-lg px-3.5 text-meta">
- {saving ? 'Reading its tools…' : 'Add'}
+ {saving ? (signIn === 'oauth' ? 'Opening its sign-in…' : 'Reading its tools…') : 'Add'}
</ActionButton>
</div>
</form>
diff --git a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx
index e11b67f9..658ea1b3 100644
--- a/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx
+++ b/client/src/components/credentials/__tests__/CredentialsBrowser.test.tsx
@@ -89,6 +89,24 @@ describe('CredentialsBrowser', () => {
expect(screen.queryByRole('form', { name: 'Custom connector' })).not.toBeInTheDocument();
});
+ it('opens the server sign-in page for an OAuth connector; it shows once the owner signed in', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ const onConnect = vi.fn();
+ sendRequest.mockResolvedValue({ success: true, ref: 'mcp:orders', sign_in_url: 'https://auth.example.com/authorize?state=s' });
+ render(<ThemeProvider><CredentialsBrowser catalogue={catalogue()} onConnect={onConnect} /></ThemeProvider>);
+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));
+ const form = within(screen.getByRole('form', { name: 'Custom connector' }));
+ 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'));
+ 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.
+ expect(onConnect).not.toHaveBeenCalled();
+ open.mockRestore();
+ });
+
it('keeps the form and shows the server words when a connector cannot be added', async () => {
sendRequest.mockResolvedValue({ success: false, error: "Couldn't connect to orders.example.com. Check that the server is running." });
const onConnect = vi.fn();
diff --git a/client/src/components/credentials/panels/McpConnectorPanel.tsx b/client/src/components/credentials/panels/McpConnectorPanel.tsx
index 21077ab4..be4daca7 100644
--- a/client/src/components/credentials/panels/McpConnectorPanel.tsx
+++ b/client/src/components/credentials/panels/McpConnectorPanel.tsx
@@ -2,8 +2,9 @@
* McpConnectorPanel — a custom MCP connector (kind `mcp`): the server it
* reaches and how it signs in; Test, which asks the server again; Refresh,
* which reads its tools again and holds any change for Accept or Discard,
- * since a server can change what a tool says it does; Remove; and its tools,
- * each on or off for employees and set to ask first or not.
+ * since a server can change what a tool says it does; Sign in again, for
+ * one that signs in with OAuth (its sign-in page opens in a new tab); Remove;
+ * and its tools, each on or off for employees and set to ask first or not.
*
* Everything shown is the connector's card (`config.mcp`). Every change is
* the server's (nodes/mcp/_handlers.py): a command waits for the refetched
@@ -47,6 +48,7 @@ const FAILED = "That didn't work. Try again.";
function signInText(signIn: ServerMcpConnector['sign_in']): string {
if (signIn.kind === 'bearer') return 'Bearer token';
if (signIn.kind === 'header') return `Header ${signIn.header ?? ''}`.trim();
+ if (signIn.kind === 'oauth') return 'OAuth';
return 'None';
}
@@ -100,6 +102,13 @@ export default function McpConnectorPanel({ config, showTechnicalSections = fals
if (result && !result.changes) setNotice({ ok: true, text: 'Nothing changed: the tools are as you accepted them.' });
};
+ const 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');
+ setNotice({ ok: true, text: 'Sign in on the page that opened.' });
+ };
+
const setTool = async (tool: string, change: ToolChange) => {
setChanging({ tool, ...change });
await run('tool', 'mcp_connector_set_tool', { tool, ...change });
@@ -147,6 +156,11 @@ export default function McpConnectorPanel({ config, showTechnicalSections = fals
<ActionButton intent="config" disabled={locked} onClick={() => void refresh()}>
{busy === 'refresh' ? 'Reading tools…' : 'Refresh tools'}
</ActionButton>
+ {mcp.sign_in.kind === 'oauth' && (
+ <ActionButton intent="secret" disabled={locked} onClick={() => void signIn()}>
+ {busy === 'sign_in' ? 'Opening sign-in…' : 'Sign in again'}
+ </ActionButton>
+ )}
<ActionButton intent="stop" disabled={locked} onClick={() => setRemoving(true)} className="ml-auto">
Remove
</ActionButton>
diff --git a/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx b/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx
index a45c90fb..641b1667 100644
--- a/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx
+++ b/client/src/components/credentials/panels/__tests__/McpConnectorPanel.test.tsx
@@ -118,4 +118,22 @@ describe('McpConnectorPanel', () => {
await waitFor(() => expect(onLeave).toHaveBeenCalledTimes(1));
expect(mocks.sendRequest).toHaveBeenCalledWith('mcp_connector_remove', { ref: 'mcp:orders' }, 60_000);
});
+
+ it('signs an OAuth connector in again on its sign-in page; only OAuth has the button', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ mocks.sendRequest.mockResolvedValue({ success: true, sign_in_url: 'https://auth.example.com/authorize?state=s' });
+ const user = userEvent.setup();
+ mount({ mcp: { sign_in: { kind: 'oauth' } } });
+ 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'));
+ expect(await screen.findByRole('status')).toHaveTextContent('Sign in on the page that opened.');
+ open.mockRestore();
+ });
+
+ it('has no Sign in again for a connector that signs in with a header', () => {
+ mount();
+ expect(screen.queryByRole('button', { name: 'Sign in again' })).not.toBeInTheDocument();
+ });
});
diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.ts
index b6104d5d..9715e699 100644
--- a/client/src/hooks/useCatalogueQuery.ts
+++ b/client/src/hooks/useCatalogueQuery.ts
@@ -126,7 +126,7 @@ export interface ServerMcpConnector {
address: string;
transport: 'streamable_http' | 'sse';
/** How it signs in; never the token or header value. */
- sign_in: { kind: 'none' | 'bearer' | 'header'; header?: string };
+ sign_in: { kind: 'none' | 'bearer' | 'header' | 'oauth'; header?: string };
server: { name?: string; title?: string | null; version?: string };
tools: ServerMcpTool[];
/** What a refresh found, waiting for the owner to accept or discard. */
diff --git a/docs-internal/credentials_encryption.md b/docs-internal/credentials_encryption.md
index 1345225e..de20836a 100644
--- a/docs-internal/credentials_encryption.md
+++ b/docs-internal/credentials_encryption.md
@@ -126,8 +126,9 @@ For secrets the user enters manually in the Credentials modal (OpenAI API key, A
For tokens obtained via OAuth 2.0 flows (Google Workspace, Twitter/X, Claude.ai).
- Model / table: `EncryptedOAuthToken` (`oauth_tokens`)
-- Access: `AuthService.store_oauth_tokens(provider, access_token, refresh_token, ...)` and `AuthService.get_oauth_tokens(provider, customer_id="owner")`
+- Access: `AuthService.store_oauth_tokens(provider, access_token, refresh_token, ..., expiry=None)` and `AuthService.get_oauth_tokens(provider, customer_id="owner")`
- Cache: `AuthService._oauth_cache: Dict[str, Dict[str, Any]]`
+- A caller that refreshes its own tokens reads them with `AuthService.get_stored_oauth_tokens(provider, customer_id="owner")`: `access_token`, `refresh_token`, `token_expiry` and `scopes`, from the encrypted DB every time, since another process may have refreshed them. Custom MCP connectors keep their OAuth sign-in this way, under `mcp:<slug>` ([MCP Connectors](./mcp_connectors.md#oauth)).
### The Mistake to Avoid
diff --git a/docs-internal/mcp_connectors.md b/docs-internal/mcp_connectors.md
index d970dbb3..be55172c 100644
--- a/docs-internal/mcp_connectors.md
+++ b/docs-internal/mcp_connectors.md
@@ -16,6 +16,8 @@ thing: see [CLI Agent Framework](./cli_agent_framework.md).
| What is kept (two credential rows) | `server/nodes/mcp/_store.py` |
| One catalogue card per connector | `server/nodes/mcp/_credentials.py` |
| The Connectors page's commands | `server/nodes/mcp/_handlers.py` |
+| Signing in with OAuth, and the connections such a sign-in makes | `server/nodes/mcp/_oauth.py` |
+| Where an OAuth sign-in comes back to (`/api/mcp/oauth/callback`) | `server/nodes/mcp/_router.py` |
| The node that gives an agent the tools, and each connector as an app a hire can use | `server/nodes/mcp/mcp_connector.py` |
| The outbound address rules, shared with the Browser node | `server/services/netpolicy.py` |
| The cards' shared fields, and the `custom` categories | `server/config/credential_providers.json` (`_mcp_connector`) |
@@ -30,11 +32,14 @@ reads the server first and saves the connector only when it answered, so a
wrong URL or a refused sign-in comes back in words for the owner and nothing
is kept.
-- **Sign-in**: none, a bearer token, or one header of the owner's choosing.
- It is sent as a header. A header the transport sets itself (`Host`,
+- **Sign-in**: none, a bearer token, one header of the owner's choosing, or
+ OAuth on the server's own sign-in page ([OAuth](#oauth)). A token or header
+ is sent as a header. A header the transport sets itself (`Host`,
`Content-Type`, `Mcp-Session-Id`, `Mcp-Protocol-Version` and the like) is
refused, as is a line break in a value.
-- **Where it may connect** (`check_server`):
+- **Where it may connect** (`check_server`), checked before every request a
+ connector sends (an httpx request hook), so an OAuth sign-in's requests to
+ the authorization server the server names are checked too:
- The URL must be http or https and carry no user or password.
- The host and every address it resolves to are checked against
`services/netpolicy.py`. Cloud metadata, link-local addresses and
@@ -42,7 +47,7 @@ is kept.
allowed, so a local MCP server works.
- Plain http is allowed only to this machine or the owner's network: over
the internet it would carry the sign-in in clear.
- - The addresses are checked when connecting, not pinned for the connection.
+ - The addresses are checked per request, not pinned for the connection.
- **The connection**: our own httpx client with redirects off, so a server
cannot bounce the sign-in to another host. The transport is streamable
HTTP, then the older SSE transport for a server that refuses it (the MCP
@@ -75,6 +80,9 @@ kept:
- when the tools were read.
- `mcp:<slug>_proxy`: the URL, encrypted, since it may carry a key.
+An OAuth sign-in also keeps its tokens in the OAuth token store under
+`mcp:<slug>` ([OAuth](#oauth)). Remove deletes all three.
+
**Tools.** Up to 500. Each is kept as the server described it: name, title,
description (up to 4,000 characters), input schema, and the read-only hint.
A tool no model could call is kept with the reason and never renamed:
@@ -111,7 +119,8 @@ page refetches.
| Command | Sends | Returns |
|---|---|---|
-| `mcp_connector_add` | `{name?, url, sign_in}` | `{ref, tools}` |
+| `mcp_connector_add` | `{name?, url, sign_in}` | `{ref, tools}`; with OAuth `{ref, sign_in_url}`, and the connector is kept once the owner signed in |
+| `mcp_connector_sign_in` | `{ref}` | `{sign_in_url}`, for an OAuth connector |
| `mcp_connector_test` | `{ref}` | `{ok, message}`; saves nothing |
| `mcp_connector_refresh` | `{ref}` | `{changes}`, null when nothing changed |
| `mcp_connector_review` | `{ref, accept}` | `{accepted}` |
@@ -125,6 +134,54 @@ them with `mcp_connector_review`. Until then, the tools the owner accepted
stay as they were. Accepting keeps the owner's settings for tools already
set; new usable tools get the defaults.
+## OAuth
+
+A connector that signs in with OAuth uses the official SDK's
+`OAuthClientProvider` (`_oauth.py`). It finds the server's authorization
+server from the server's metadata, registers a client (dynamic client
+registration), signs in with an authorization code and PKCE, and refreshes
+the token.
+
+**Signing in** (`start_sign_in`, from Add or Sign in again) runs in the
+background, since the owner finishes it in their browser:
+
+1. A first request, an MCP `initialize` sent as a plain POST, is refused
+ with 401. It is not sent inside an MCP session, whose 30 s read timeout
+ would cut the owner off. The provider registers a client and hands over
+ the 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".
+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,
+ `services/oauth_utils.get_redirect_uri`). The route sits behind the app's
+ sign-in like the rest of `/api`. It hands the code to the sign-in waiting
+ under that `state`, and the provider exchanges it for tokens. A sign-in
+ waits up to `SIGN_IN_S` (600 s) for the owner.
+3. Add then reads the server's tools and keeps the connector; Sign in again
+ keeps the new sign-in. The callback page says how it went.
+
+**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
+encrypted sign-in (`SignIn.oauth`) keeps the client it registered, with its
+secret if it got one, and the endpoints it found: the authorization server's
+metadata, 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.
+
+**Sign in again.** When the refresh is refused, only the owner can sign in
+again. The connection fails with `SignInNeeded`: "{name} needs you to sign in
+again: open it on the Connectors page and press Sign in again." Each
+sign-in registers a new client, so a changed address of this app (another
+host or port) still works.
+
## The node
`mcpConnector` (Custom Connector) goes on an agent's Tools and names one
@@ -183,10 +240,14 @@ connector is no longer listed.
`AddConnectorForm`. After a save, the catalogue is refetched, then the new
connector's page opens. The Welcome guide's AI model step has no Add
(`customConnectors={false}`).
+- **Add** with Sign-in **OAuth** opens the server's sign-in page in a new
+ tab and closes the form with a note: the connector's card shows once the
+ owner signed in there.
- **`McpConnectorPanel`** shows:
- the server, its address, how it signs in (and, in Dev, the transport),
and when its tools were read;
- - Test, Refresh tools and Remove;
+ - Test, Refresh tools and Remove, and for an OAuth connector Sign in again,
+ which opens its sign-in page;
- a waiting change, with Accept and Discard;
- each tool with its Use and Ask first switches. A tool no model could call
shows why, and has no switches.
@@ -197,6 +258,10 @@ connector is no longer listed.
## Known gaps
-- No OAuth sign-in.
+- A sign-in page is opened after the command answers, not ahead of it, so
+ a browser may block the new tab.
+- Two connections that refresh the same expired token at once can both use
+ the old refresh token. When the server rotates refresh tokens, the second
+ one fails and says to sign in again, though the first kept a working token.
- A host's addresses are checked when connecting, not pinned for the
connection.
diff --git a/server/nodes/mcp/__init__.py b/server/nodes/mcp/__init__.py
index 8336aac5..32a875bd 100644
--- a/server/nodes/mcp/__init__.py
+++ b/server/nodes/mcp/__init__.py
@@ -7,8 +7,11 @@ something employees can use.
- ``_store.py``: where a connector is kept (two credential rows).
- ``_credentials.py``: each connector's own card in the credentials
catalogue.
-- ``_handlers.py``: add, test, refresh, accept or discard what a refresh
- found, set a tool, and remove.
+- ``_oauth.py``: signing in with OAuth on the server's own page, and the
+ connections such a sign-in makes; ``_router.py``: where the sign-in comes
+ back to.
+- ``_handlers.py``: add, sign in again, test, refresh, accept or discard
+ what a refresh found, set a tool, and remove.
- ``mcp_connector.py``: the node that gives an agent a connector's tools,
one per tool (``ToolNode.tool_bindings``), and each connector as an app a
hire can use (``connector_apps``).
@@ -17,13 +20,17 @@ something employees can use.
from __future__ import annotations
from services.employees.apps import register_app_source
-from services.ws_handler_registry import register_option_loader, register_ws_handlers
+from services.ws_handler_registry import register_oauth_callback_path, register_option_loader, register_router, register_ws_handlers
from ._credentials import McpConnectorCredential
from ._handlers import WS_HANDLERS
+from ._oauth import CALLBACK_PATH
+from ._router import router
from .mcp_connector import McpConnectorNode, connector_apps, load_connectors
register_ws_handlers(WS_HANDLERS)
+register_router(router, name="mcp")
+register_oauth_callback_path("mcp", CALLBACK_PATH)
register_option_loader("mcpConnectors", load_connectors)
register_app_source("mcp", connector_apps)
diff --git a/server/nodes/mcp/_client.py b/server/nodes/mcp/_client.py
index 5781e854..25a56bc5 100644
--- a/server/nodes/mcp/_client.py
+++ b/server/nodes/mcp/_client.py
@@ -2,16 +2,18 @@
Each connection uses our own httpx client with redirects off, so a server
cannot bounce the owner's sign-in to another host. The sign-in goes as a
-header. The transport is streamable HTTP, or the older SSE transport for a
-server that refuses it (the MCP spec's own fallback), and the one that
-answered when the connector was added is kept.
-
-Before connecting, the server's host is resolved and every address it gives
-is checked against ``services/netpolicy.py``. Cloud metadata and
-OpenCompany's own ports are never reached. Plain http is allowed only to
-this machine or the owner's own network, because over the internet it would
-carry the sign-in in clear. The addresses are checked when connecting, not
-pinned for the connection.
+header, or, for an OAuth sign-in, through the SDK's ``OAuthClientProvider``
+(``auth``; see ``_oauth.py``). The transport is streamable HTTP, or the
+older SSE transport for a server that refuses it (the MCP spec's own
+fallback), and the one that answered when the connector was added is kept.
+
+Every request is checked against ``services/netpolicy.py`` first: its host
+is resolved and every address it gives is checked (``check_server``), the
+server's and, for an OAuth sign-in, its authorization server's, which the
+server names. Cloud metadata and OpenCompany's own ports are never reached.
+Plain http is allowed only to this machine or the owner's own network,
+because over the internet it would carry the sign-in in clear. The
+addresses are checked per request, not pinned for the connection.
A tool as an employee sees it is ``<connector>__<tool>``. A tool whose name
or input description no model could use is kept with the reason, never
@@ -25,9 +27,9 @@ import ipaddress
import re
import socket
from contextlib import asynccontextmanager
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import timedelta
-from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Literal, Optional, Tuple
+from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Literal, Mapping, Optional, Tuple
from urllib.parse import urlsplit
import httpx
@@ -79,13 +81,16 @@ class ConnectorError(Exception):
@dataclass(frozen=True)
class SignIn:
- """How a connector signs in to its server: nothing, a bearer token, or one
- header of the owner's choosing."""
+ """How a connector signs in to its server: nothing, a bearer token, one
+ header of the owner's choosing, or OAuth on the server's own sign-in
+ page. ``oauth`` is what an OAuth sign-in keeps besides its tokens: the
+ client it registered and the endpoints it found (``_oauth.py``)."""
- kind: Literal["none", "bearer", "header"] = "none"
+ kind: Literal["none", "bearer", "header", "oauth"] = "none"
token: str = ""
header: str = ""
value: str = ""
+ oauth: Mapping[str, Any] = field(default_factory=dict)
@classmethod
def from_form(cls, raw: Dict[str, Any]) -> "SignIn":
@@ -93,6 +98,8 @@ class SignIn:
kind = str(raw.get("kind") or "none")
if kind == "none":
return cls()
+ if kind == "oauth":
+ return cls(kind="oauth")
if kind == "bearer":
token = str(raw.get("token") or "").strip()
if not token or any(c in token for c in "\r\n"):
@@ -117,10 +124,16 @@ class SignIn:
return cls(kind="bearer", token=str(stored.get("token") or ""))
if kind == "header":
return cls(kind="header", header=str(stored.get("header") or ""), value=str(stored.get("value") or ""))
+ if kind == "oauth":
+ oauth = stored.get("oauth")
+ return cls(kind="oauth", oauth=dict(oauth) if isinstance(oauth, dict) else {})
return cls()
- def dump(self) -> Dict[str, str]:
- return {"kind": self.kind, "token": self.token, "header": self.header, "value": self.value}
+ def dump(self) -> Dict[str, Any]:
+ kept: Dict[str, Any] = {"kind": self.kind, "token": self.token, "header": self.header, "value": self.value}
+ if self.kind == "oauth":
+ kept["oauth"] = dict(self.oauth)
+ return kept
def public(self) -> Dict[str, str]:
"""What may be shown or kept in plain text: never the token or value."""
@@ -196,18 +209,37 @@ async def _resolve(host: str, port: int) -> List[Any]:
return found
-def _client(headers: Dict[str, str], *, transport: Optional[httpx.AsyncBaseTransport]) -> httpx.AsyncClient:
+async def _check_request(request: httpx.Request) -> None:
+ await check_server(str(request.url))
+
+
+def http_client(
+ headers: Dict[str, str], *, transport: Optional[httpx.AsyncBaseTransport], auth: Optional[httpx.Auth] = None, timeout: Any = None
+) -> httpx.AsyncClient:
+ """A connector's httpx client: redirects off, and every request it sends
+ (the OAuth sign-in's included) checked first. ``transport`` replaces the
+ network (tests)."""
return httpx.AsyncClient(
- headers=headers, timeout=httpx.Timeout(TIMEOUT_S, read=CALL_TIMEOUT_S), follow_redirects=False, transport=transport
+ headers=headers,
+ timeout=timeout or httpx.Timeout(TIMEOUT_S, read=CALL_TIMEOUT_S),
+ auth=auth,
+ follow_redirects=False,
+ transport=transport,
+ event_hooks={"request": [_check_request]},
)
@asynccontextmanager
async def open_session(
- url: str, sign_in: SignIn, transport: Transport, *, http_transport: Optional[httpx.AsyncBaseTransport] = None
+ url: str,
+ sign_in: SignIn,
+ transport: Transport,
+ *,
+ http_transport: Optional[httpx.AsyncBaseTransport] = None,
+ auth: Optional[httpx.Auth] = None,
) -> AsyncIterator[Tuple["ClientSession", "InitializeResult"]]:
- """An initialized session with the server. ``http_transport`` replaces the
- network (tests)."""
+ """An initialized session with the server. ``auth`` signs in with OAuth;
+ ``http_transport`` replaces the network (tests)."""
from mcp import ClientSession
from mcp.client.sse import sse_client
from mcp.client.streamable_http import streamable_http_client
@@ -218,7 +250,7 @@ async def open_session(
info = Implementation(name="OpenCompany", version=app_version())
limit = timedelta(seconds=TIMEOUT_S)
if transport == "streamable_http":
- async with _client(sign_in.headers(), transport=http_transport) as http:
+ async with http_client(sign_in.headers(), transport=http_transport, auth=auth) as http:
async with streamable_http_client(url, http_client=http) as (read, write, _session_id):
async with ClientSession(read, write, read_timeout_seconds=limit, client_info=info) as session:
yield session, await session.initialize()
@@ -226,12 +258,11 @@ async def open_session(
def factory(headers=None, timeout=None, auth=None) -> httpx.AsyncClient:
# The SDK's own factory follows redirects.
- return httpx.AsyncClient(headers=headers, timeout=timeout, auth=auth, follow_redirects=False, transport=http_transport)
+ return http_client(headers or {}, transport=http_transport, auth=auth, timeout=timeout)
- async with sse_client(url, headers=sign_in.headers(), timeout=TIMEOUT_S, sse_read_timeout=CALL_TIMEOUT_S, httpx_client_factory=factory) as (
- read,
- write,
- ):
+ async with sse_client(
+ url, headers=sign_in.headers(), timeout=TIMEOUT_S, sse_read_timeout=CALL_TIMEOUT_S, httpx_client_factory=factory, auth=auth
+ ) as (read, write):
async with ClientSession(read, write, read_timeout_seconds=limit, client_info=info) as session:
yield session, await session.initialize()
@@ -252,10 +283,15 @@ async def list_tools(session: "ClientSession") -> List["Tool"]:
async def read_server(
- url: str, sign_in: SignIn, transport: Transport, *, http_transport: Optional[httpx.AsyncBaseTransport] = None
+ url: str,
+ sign_in: SignIn,
+ transport: Transport,
+ *,
+ http_transport: Optional[httpx.AsyncBaseTransport] = None,
+ auth: Optional[httpx.Auth] = None,
) -> Discovery:
"""Connect over ``transport`` and read what the server offers."""
- async with open_session(url, sign_in, transport, http_transport=http_transport) as (session, init):
+ async with open_session(url, sign_in, transport, http_transport=http_transport, auth=auth) as (session, init):
tools = await list_tools(session)
server = init.serverInfo
return Discovery(
@@ -266,7 +302,9 @@ async def read_server(
)
-async def discover(url: str, sign_in: SignIn, *, http_transport: Optional[httpx.AsyncBaseTransport] = None) -> Discovery:
+async def discover(
+ url: str, sign_in: SignIn, *, http_transport: Optional[httpx.AsyncBaseTransport] = None, auth: Optional[httpx.Auth] = None
+) -> Discovery:
"""A new connector's first read: streamable HTTP, else the older SSE
transport, within ``DISCOVER_S`` in all. Raises ``ConnectorError`` with
the first transport's failure."""
@@ -276,7 +314,7 @@ async def discover(url: str, sign_in: SignIn, *, http_transport: Optional[httpx.
async with asyncio.timeout(DISCOVER_S):
for transport in TRANSPORTS:
try:
- return await read_server(url, sign_in, transport, http_transport=http_transport)
+ 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
first = first or exc
except TimeoutError as exc:
@@ -285,14 +323,19 @@ async def discover(url: str, sign_in: SignIn, *, http_transport: Optional[httpx.
async def read_again(
- url: str, sign_in: SignIn, transport: Transport, *, http_transport: Optional[httpx.AsyncBaseTransport] = None
+ url: str,
+ sign_in: SignIn,
+ transport: Transport,
+ *,
+ http_transport: Optional[httpx.AsyncBaseTransport] = None,
+ auth: Optional[httpx.Auth] = None,
) -> Discovery:
"""Read a saved connector's server again (Test, Refresh), within
``DISCOVER_S``."""
host = await check_server(url)
try:
async with asyncio.timeout(DISCOVER_S):
- return await read_server(url, sign_in, transport, http_transport=http_transport)
+ 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
@@ -342,12 +385,13 @@ async def call_tool(
arguments: Dict[str, Any],
*,
http_transport: Optional[httpx.AsyncBaseTransport] = None,
+ auth: Optional[httpx.Auth] = None,
) -> CallResult:
"""Call one of the server's tools, within ``CALL_TIMEOUT_S``."""
host = await check_server(url)
try:
async with asyncio.timeout(CALL_TIMEOUT_S):
- async with open_session(url, sign_in, transport, http_transport=http_transport) as (session, _init):
+ async with open_session(url, sign_in, transport, http_transport=http_transport, auth=auth) as (session, _init):
result = await session.call_tool(name, arguments, 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
@@ -455,6 +499,7 @@ __all__ = [
"check_server",
"describe",
"discover",
+ "http_client",
"open_session",
"read_again",
"snapshots",
diff --git a/server/nodes/mcp/_handlers.py b/server/nodes/mcp/_handlers.py
index f015b61a..d994ae9f 100644
--- a/server/nodes/mcp/_handlers.py
+++ b/server/nodes/mcp/_handlers.py
@@ -2,7 +2,12 @@
- ``mcp_connector_add`` ``{name?, url, sign_in: {kind, token?, header?,
value?}}``: reads the server (``_client.discover``) and saves it only when
- it answered; ``{ref, tools}``.
+ it answered; ``{ref, tools}``. With ``kind: "oauth"`` it starts signing in
+ (``_oauth.start_sign_in``) and answers ``{ref, sign_in_url}``, the page
+ the owner signs in on; the connector is saved, with its tools, once they
+ have, and the callback page says how it went.
+- ``mcp_connector_sign_in`` ``{ref}``: signs an OAuth connector in again;
+ ``{sign_in_url}``.
- ``mcp_connector_test`` ``{ref}``: whether the server still answers;
``{ok, message}``, saving nothing.
- ``mcp_connector_refresh`` ``{ref}``: reads the tools again. A change (tools
@@ -32,7 +37,9 @@ from services.plugin.base import NodeUserError
from services.plugin.ws import ws_response
from ._client import ConnectorError, SignIn, changes, discover, read_again, snapshots
+from ._oauth import SignedIn, connection_auth, save_tokens, start_sign_in
from ._store import (
+ Connector,
default_settings,
describe_new,
exists,
@@ -44,6 +51,7 @@ from ._store import (
remove,
save_meta,
save_new,
+ save_sign_in,
slug_of,
)
@@ -66,6 +74,38 @@ async def _announce(ref: str, stage: str) -> None:
await get_status_broadcaster().broadcast_credential_event(f"credential.api_key.{stage}", provider=ref)
+def _redirect_uri(websocket: WebSocket) -> str:
+ """Where the server's sign-in page sends the owner back: this app."""
+ from services.oauth_utils import get_redirect_uri
+
+ return get_redirect_uri(websocket, "mcp")
+
+
+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)
+
+
+async def _add_signed_in(ref: str, slug: str, name: str, url: str, signed_in: SignedIn) -> str:
+ """A new connector, once the owner signed in: its tools read, then it
+ and its tokens kept."""
+ found = await discover(url, signed_in.sign_in, auth=signed_in.auth)
+ if await exists(ref):
+ raise ConnectorError(f"There is already a connector called {slug}. Choose another name.")
+ meta = describe_new(slug, name, url, signed_in.sign_in, found)
+ await save_new(ref, url, signed_in.sign_in, meta)
+ try:
+ await save_tokens(ref, signed_in.tokens)
+ except ConnectorError:
+ await remove(ref)
+ raise
+ await _announce(ref, "saved")
+ count = len(meta["tools"])
+ return f"{meta['name']} is connected, with {count} tool{'' if count == 1 else 's'}."
+
+
@ws_response
async def handle_mcp_connector_add(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
if refused := _refused(websocket):
@@ -90,8 +130,16 @@ async def handle_mcp_connector_add(data: Dict[str, Any], websocket: WebSocket) -
ref = ref_of(slug)
if await exists(ref):
raise ConnectorError(f"There is already a connector called {slug}. Choose another name.")
+ name = name or (urlsplit(url).hostname or slug)
+ if sign_in.kind == "oauth":
+
+ async def keep(signed_in: SignedIn) -> str:
+ return await _add_signed_in(ref, slug, name, url, signed_in)
+
+ address = await start_sign_in(url, redirect_uri=_redirect_uri(websocket), on_signed_in=keep)
+ return {"success": True, "ref": ref, "sign_in_url": address}
found = await discover(url, sign_in)
- meta = describe_new(slug, name or (urlsplit(url).hostname or slug), url, sign_in, found)
+ meta = describe_new(slug, name, url, sign_in, found)
await save_new(ref, url, sign_in, meta)
except ConnectorError as exc:
raise NodeUserError(str(exc)) from None
@@ -100,13 +148,34 @@ async def handle_mcp_connector_add(data: Dict[str, Any], websocket: WebSocket) -
@ws_response
-async def handle_mcp_connector_test(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+async def handle_mcp_connector_sign_in(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
if refused := _refused(websocket):
return refused
try:
connector = await get_connector(str(data.get("ref") or ""), principal=_principal(websocket))
url, sign_in = await read_access(connector)
- found = await read_again(url, sign_in, connector.meta.get("transport") or "streamable_http")
+ if sign_in.kind != "oauth":
+ raise ConnectorError(f"{connector.name} doesn't sign in on its server's page.")
+
+ async def keep(signed_in: SignedIn) -> str:
+ await save_sign_in(connector.ref, signed_in.sign_in)
+ await save_tokens(connector.ref, signed_in.tokens)
+ await _announce(connector.ref, "saved")
+ return f"{connector.name} is signed in again."
+
+ address = await start_sign_in(url, redirect_uri=_redirect_uri(websocket), on_signed_in=keep)
+ except ConnectorError as exc:
+ raise NodeUserError(str(exc)) from None
+ return {"success": True, "sign_in_url": address}
+
+
+@ws_response
+async def handle_mcp_connector_test(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ if refused := _refused(websocket):
+ return refused
+ try:
+ connector = await get_connector(str(data.get("ref") or ""), principal=_principal(websocket))
+ found = await _read(connector)
except ConnectorError as exc:
return {"success": True, "ok": False, "message": str(exc)}
count = len(found.tools)
@@ -119,8 +188,7 @@ async def handle_mcp_connector_refresh(data: Dict[str, Any], websocket: WebSocke
return refused
try:
connector = await get_connector(str(data.get("ref") or ""), principal=_principal(websocket))
- url, sign_in = await read_access(connector)
- found = await read_again(url, sign_in, connector.meta.get("transport") or "streamable_http")
+ found = await _read(connector)
tools = snapshots(connector.slug, found.tools)
diff: Dict[str, Any] = changes(connector.tools, tools)
diff["instructions"] = found.instructions != connector.meta.get("instructions")
@@ -190,6 +258,7 @@ async def handle_mcp_connector_remove(data: Dict[str, Any], websocket: WebSocket
WS_HANDLERS = {
"mcp_connector_add": handle_mcp_connector_add,
+ "mcp_connector_sign_in": handle_mcp_connector_sign_in,
"mcp_connector_test": handle_mcp_connector_test,
"mcp_connector_refresh": handle_mcp_connector_refresh,
"mcp_connector_review": handle_mcp_connector_review,
diff --git a/server/nodes/mcp/_oauth.py b/server/nodes/mcp/_oauth.py
new file mode 100644
index 00000000..d801cdae
--- /dev/null
+++ b/server/nodes/mcp/_oauth.py
@@ -0,0 +1,384 @@
+"""Signing a custom connector in with OAuth, through the official ``mcp`` SDK's
+``OAuthClientProvider``: it finds the server's authorization server,
+registers a client, signs in with an authorization code and PKCE, and
+refreshes the token.
+
+Signing in (``start_sign_in``) runs in the background, because the owner
+finishes it in their browser:
+
+1. A first request to the server (an MCP ``initialize``, sent as a plain
+ POST: inside an MCP session its 30 s read timeout would cut the owner
+ off) is refused with 401. The provider registers a client and hands over
+ the address of the server's sign-in page, which the command that started
+ it returns for the app to open.
+2. The owner signs in, and the authorization server sends their browser to
+ ``CALLBACK_PATH`` (``_router.py``) with a code and the sign-in's
+ ``state``. ``finish`` hands the code to the waiting provider, which
+ exchanges it for tokens.
+3. ``on_signed_in``, from the command that started it, saves the result (a
+ new connector with its tools, or a saved one's new sign-in) and says how
+ it went, which the callback page shows.
+
+What a sign-in keeps: its tokens in the OAuth token store
+(``AuthService.store_oauth_tokens``, keyed by the connector's reference,
+with their expiry), and in the connector's encrypted sign-in
+(``SignIn.oauth``) the client it registered and the endpoints it found.
+
+A later connection (``connection_auth``) builds a provider from those, with
+the token's expiry and the endpoints set before first use. 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 it refreshes an expired token, and the new one is kept. When the
+refresh is refused, only the owner can sign in again: the connection fails
+with ``SignInNeeded``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional, Set, Tuple
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+
+from core.logging import get_logger
+
+from ._client import DISCOVER_S, TIMEOUT_S, ConnectorError, SignIn, check_server, describe, http_client
+
+if TYPE_CHECKING:
+ from mcp.client.auth import OAuthClientProvider
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
+
+logger = get_logger(__name__)
+
+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
+
+
+class SignInNeeded(ConnectorError):
+ """Only the owner can sign the connector in again."""
+
+
+def _auth() -> Any:
+ from services.plugin.deps import get_auth_service
+
+ return get_auth_service()
+
+
+def _initialize() -> Dict[str, Any]:
+ """The opening of an MCP session, as a sign-in's first request."""
+ from mcp.types import LATEST_PROTOCOL_VERSION
+
+ from core.approot import app_version
+
+ return {
+ "jsonrpc": "2.0",
+ "id": 0,
+ "method": "initialize",
+ "params": {"protocolVersion": LATEST_PROTOCOL_VERSION, "capabilities": {}, "clientInfo": {"name": "OpenCompany", "version": app_version()}},
+ }
+
+
+# ----- what the SDK stores through -----
+
+
+class _Memory:
+ """The SDK's token storage while signing in: kept only once it is done."""
+
+ def __init__(self) -> None:
+ self.tokens: Optional["OAuthToken"] = None
+ self.client: Optional["OAuthClientInformationFull"] = None
+
+ async def get_tokens(self) -> Optional["OAuthToken"]:
+ return self.tokens
+
+ async def set_tokens(self, tokens: "OAuthToken") -> None:
+ self.tokens = tokens
+
+ async def get_client_info(self) -> Optional["OAuthClientInformationFull"]:
+ return self.client
+
+ async def set_client_info(self, client_info: "OAuthClientInformationFull") -> None:
+ self.client = client_info
+
+
+class _Saved:
+ """A saved connector's tokens, as read when its connection opened, and
+ the client it registered. A refreshed token is kept at once."""
+
+ def __init__(self, ref: str, client: "OAuthClientInformationFull", tokens: Optional["OAuthToken"]) -> None:
+ self.ref = ref
+ self.client = client
+ self.tokens = tokens
+
+ async def get_tokens(self) -> Optional["OAuthToken"]:
+ return self.tokens
+
+ async def set_tokens(self, tokens: "OAuthToken") -> None:
+ await save_tokens(self.ref, tokens)
+ self.tokens = tokens
+
+ async def get_client_info(self) -> Optional["OAuthClientInformationFull"]:
+ return self.client
+
+ async def set_client_info(self, client_info: "OAuthClientInformationFull") -> None:
+ self.client = client_info
+
+
+async def save_tokens(ref: str, tokens: "OAuthToken") -> None:
+ """Keep a connector's tokens with their expiry. A refresh that sends no
+ refresh token keeps the one it had."""
+ from mcp.shared.auth_utils import calculate_token_expiry
+
+ auth = _auth()
+ refresh = tokens.refresh_token or await auth.get_oauth_refresh_token(ref) or ""
+ expires = calculate_token_expiry(tokens.expires_in)
+ kept = await auth.store_oauth_tokens(
+ provider=ref,
+ access_token=tokens.access_token,
+ refresh_token=refresh,
+ scopes=tokens.scope,
+ expiry=datetime.fromtimestamp(expires, timezone.utc) if expires is not None else None,
+ )
+ if not kept:
+ raise ConnectorError("Couldn't keep the sign-in. Try again.")
+
+
+# ----- signing in -----
+
+
+@dataclass
+class SignedIn:
+ """A finished sign-in: the provider, signed in, to read the server with
+ now; what the connector keeps of it; and its tokens."""
+
+ auth: "OAuthClientProvider"
+ sign_in: SignIn
+ tokens: "OAuthToken"
+
+
+def _kept(provider: "OAuthClientProvider") -> Dict[str, Any]:
+ """What a sign-in keeps besides its tokens (``SignIn.oauth``)."""
+ context = provider.context
+
+ def dump(model: Any) -> Optional[Dict[str, Any]]:
+ return model.model_dump(mode="json", exclude_none=True) if model is not None else None
+
+ return {
+ "client": dump(context.client_info),
+ "authorization_server": dump(context.oauth_metadata),
+ "resource": dump(context.protected_resource_metadata),
+ "auth_server_url": context.auth_server_url,
+ "scope": context.client_metadata.scope,
+ }
+
+
+async def sign_in(
+ url: str,
+ *,
+ redirect_uri: str,
+ redirect_handler: Callable[[str], Awaitable[None]],
+ callback_handler: Callable[[], Awaitable[Tuple[str, Optional[str]]]],
+ http_transport: Optional[httpx.AsyncBaseTransport] = None,
+) -> SignedIn:
+ """Sign in to the server at ``url``: steps 1 and 2 above."""
+ from mcp.client.auth import OAuthClientProvider, OAuthFlowError
+ from mcp.shared.auth import OAuthClientMetadata
+
+ host = await check_server(url)
+ storage = _Memory()
+ provider = OAuthClientProvider(
+ server_url=url,
+ client_metadata=OAuthClientMetadata(client_name="OpenCompany", redirect_uris=[redirect_uri]),
+ storage=storage,
+ redirect_handler=redirect_handler,
+ callback_handler=callback_handler,
+ timeout=SIGN_IN_S,
+ )
+ try:
+ async with asyncio.timeout(SIGN_IN_S + 2 * TIMEOUT_S):
+ async with http_client({}, transport=http_transport, auth=provider) as http:
+ async with http.stream("POST", url, json=_initialize(), headers={"Accept": "application/json, text/event-stream"}):
+ pass
+ except ConnectorError:
+ raise
+ except OAuthFlowError as exc:
+ raise ConnectorError(f"Signing in to {host} failed: {exc}") from None
+ except Exception as exc: # noqa: BLE001 - described in words for the owner
+ raise ConnectorError(describe(exc, host)) from None
+ if storage.tokens is None:
+ raise ConnectorError(f"{host} didn't ask to sign in. Choose None, or the sign-in it uses.")
+ return SignedIn(auth=provider, sign_in=SignIn(kind="oauth", oauth=_kept(provider)), tokens=storage.tokens)
+
+
+@dataclass(eq=False)
+class _Waiting:
+ """A sign-in waiting for the owner's browser to come back."""
+
+ code: "asyncio.Future[Tuple[str, Optional[str]]]"
+ task: "Optional[asyncio.Task[str]]" = None
+
+
+#: Sign-ins under way, by their ``state``.
+_waiting: Dict[str, _Waiting] = {}
+#: Kept referenced, so a sign-in is not garbage collected while it waits.
+_running: Set["asyncio.Task[str]"] = set()
+
+
+def _ended(task: "asyncio.Task[str]") -> None:
+ _running.discard(task)
+ if task.cancelled():
+ return
+ error = task.exception()
+ if isinstance(error, ConnectorError):
+ logger.info("A connector's sign-in ended", reason=str(error))
+ elif error is not None:
+ logger.warning("A connector's sign-in failed", exc_info=error)
+
+
+async def start_sign_in(
+ url: str,
+ *,
+ redirect_uri: str,
+ on_signed_in: Callable[[SignedIn], Awaitable[str]],
+ http_transport: Optional[httpx.AsyncBaseTransport] = None,
+) -> str:
+ """Start signing in to ``url`` in the background, and return the address
+ of the server's sign-in page for the owner to open, once the server
+ asked for it (within ``DISCOVER_S``). ``on_signed_in`` saves the result
+ and says how it went."""
+ loop = asyncio.get_running_loop()
+ opened: "asyncio.Future[str]" = loop.create_future()
+ waiting = _Waiting(code=loop.create_future())
+ states: List[str] = []
+
+ async def redirect(address: str) -> None:
+ parts = urlsplit(address)
+ state = (parse_qs(parts.query).get("state") or [""])[0]
+ if parts.scheme not in ("http", "https") or not state:
+ raise ConnectorError("The server's sign-in page has no web address to open.")
+ _waiting[state] = waiting
+ states.append(state)
+ if not opened.done():
+ opened.set_result(address)
+
+ async def callback() -> Tuple[str, Optional[str]]:
+ try:
+ return await asyncio.wait_for(waiting.code, SIGN_IN_S)
+ except TimeoutError:
+ raise ConnectorError("The sign-in wasn't finished in time. Start it again.") from None
+
+ async def run() -> str:
+ try:
+ signed_in = await sign_in(url, redirect_uri=redirect_uri, redirect_handler=redirect, callback_handler=callback, http_transport=http_transport)
+ return await on_signed_in(signed_in)
+ finally:
+ for state in states:
+ _waiting.pop(state, None)
+
+ task = asyncio.create_task(run())
+ waiting.task = task
+ _running.add(task)
+ task.add_done_callback(_ended)
+ await asyncio.wait({opened, task}, timeout=DISCOVER_S, return_when=asyncio.FIRST_COMPLETED)
+ if opened.done():
+ return opened.result()
+ if task.done():
+ task.result()
+ task.cancel()
+ raise ConnectorError(f"{urlsplit(url).hostname or url} didn't answer in time.")
+
+
+async def finish(state: str, *, code: Optional[str], error: Optional[str]) -> Tuple[bool, str]:
+ """The owner's browser came back to ``CALLBACK_PATH``: hand the code to
+ the sign-in waiting for it, then wait for it to be saved. Returns whether
+ it worked, and what the page says."""
+ waiting = _waiting.get(state)
+ if waiting is None or waiting.task is None:
+ return False, "This sign-in has ended. Start it again from the Connectors page."
+ if not waiting.code.done():
+ if error:
+ waiting.code.set_exception(ConnectorError(f"The sign-in was refused: {error}"))
+ elif not code:
+ waiting.code.set_exception(ConnectorError("The server sent no sign-in code. Start it again."))
+ else:
+ waiting.code.set_result((code, state))
+ try:
+ return True, await asyncio.wait_for(asyncio.shield(waiting.task), DISCOVER_S + 2 * TIMEOUT_S)
+ except ConnectorError as exc:
+ return False, str(exc)
+ except TimeoutError:
+ return True, "Still finishing: the connector shows on the Connectors page once it is done."
+ except Exception: # noqa: BLE001 - logged by _ended; the page says it failed
+ return False, "The sign-in failed. Start it again from the Connectors page."
+
+
+# ----- connections -----
+
+
+def _needs_sign_in(name: str) -> Callable[..., Awaitable[Any]]:
+ async def refuse(*_args: Any) -> Any:
+ raise SignInNeeded(f"{name} needs you to sign in again: open it on the Connectors page and press Sign in again.")
+
+ return refuse
+
+
+def _timestamp(value: Any) -> Optional[float]:
+ """A stored expiry as a Unix time (SQLite gives it back without its UTC zone)."""
+ if not isinstance(value, datetime):
+ return None
+ 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"]:
+ """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."""
+ if sign_in.kind != "oauth":
+ return None
+ from mcp.client.auth import OAuthClientProvider
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthMetadata, OAuthToken, ProtectedResourceMetadata
+ from pydantic import ValidationError
+
+ kept = sign_in.oauth
+ try:
+ client = OAuthClientInformationFull.model_validate(kept.get("client") or {})
+ server = OAuthMetadata.model_validate(kept["authorization_server"]) if kept.get("authorization_server") else None
+ resource = ProtectedResourceMetadata.model_validate(kept["resource"]) if kept.get("resource") else None
+ except ValidationError:
+ raise SignInNeeded(f"{name} needs you to sign in again: open it on the Connectors page and press Sign in again.") from None
+ stored = await _auth().get_stored_oauth_tokens(ref)
+ tokens = (
+ OAuthToken(access_token=stored["access_token"], refresh_token=stored.get("refresh_token") or None, scope=stored.get("scopes") or None)
+ if stored and stored.get("access_token")
+ else None
+ )
+ refuse = _needs_sign_in(name)
+ provider = OAuthClientProvider(
+ server_url=url,
+ client_metadata=OAuthClientMetadata(redirect_uris=client.redirect_uris, scope=kept.get("scope")),
+ storage=_Saved(ref, client, tokens),
+ redirect_handler=refuse,
+ callback_handler=refuse,
+ )
+ context = provider.context
+ context.token_expiry_time = _timestamp(stored.get("token_expiry")) if stored else None
+ context.oauth_metadata = server
+ context.protected_resource_metadata = resource
+ context.auth_server_url = kept.get("auth_server_url")
+ return provider
+
+
+__all__ = [
+ "CALLBACK_PATH",
+ "SIGN_IN_S",
+ "SignInNeeded",
+ "SignedIn",
+ "connection_auth",
+ "finish",
+ "save_tokens",
+ "sign_in",
+ "start_sign_in",
+]
diff --git a/server/nodes/mcp/_router.py b/server/nodes/mcp/_router.py
new file mode 100644
index 00000000..c0c1135e
--- /dev/null
+++ b/server/nodes/mcp/_router.py
@@ -0,0 +1,37 @@
+"""Where a custom connector's OAuth sign-in comes back
+(``_oauth.CALLBACK_PATH``): the server's authorization server sends the
+owner's browser here once they signed in. The route sits behind the app's
+own sign-in like the rest of ``/api``, and the page says how the sign-in
+went (``render_oauth_callback_html`` escapes what the server sent).
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from fastapi import APIRouter, Query
+from fastapi.responses import HTMLResponse
+
+from services.events.oauth_lifecycle import render_oauth_callback_html
+
+from ._oauth import CALLBACK_PATH, finish
+
+#: The plugin's colour (meta.json).
+_COLOR = "#8be9fd"
+
+router = APIRouter(tags=["mcp"])
+
+
[email protected](CALLBACK_PATH)
+async def sign_in_callback(
+ code: Optional[str] = Query(None),
+ state: Optional[str] = Query(None),
+ error: Optional[str] = Query(None),
+ error_description: Optional[str] = Query(None),
+) -> HTMLResponse:
+ ok, message = await finish(state or "", code=code, error=error_description or error)
+ page = render_oauth_callback_html("mcp", status="success" if ok else "error", message=message, color_hex=_COLOR, title="Signed in")
+ return HTMLResponse(content=page, status_code=200)
+
+
+__all__ = ["router"]
diff --git a/server/nodes/mcp/_store.py b/server/nodes/mcp/_store.py
index 99a48dcd..6255902c 100644
--- a/server/nodes/mcp/_store.py
+++ b/server/nodes/mcp/_store.py
@@ -8,6 +8,9 @@ OpenAI-compatible endpoints are kept, through ``AuthService``.
settings for them, and a refresh waiting to be accepted.
- ``mcp:<slug>_proxy``: the server's URL, encrypted, since it may carry a key.
+An OAuth sign-in's tokens are kept in the OAuth token store under
+``mcp:<slug>`` (``_oauth.save_tokens``), and removed with the connector.
+
A slug is at most 20 characters, so ``<slug>__<tool>`` leaves a tool's own
name room within the 64 a model accepts.
"""
@@ -189,11 +192,20 @@ async def save_meta(connector: Connector, meta: Dict[str, Any]) -> None:
raise ConnectorError("Couldn't save the change. Try again.")
+async def save_sign_in(ref: str, sign_in: SignIn) -> None:
+ """Keep a saved connector's new sign-in; its description, read again
+ now, stays as it is."""
+ connector = await get_connector(ref)
+ if not await _auth().store_api_key(provider=ref, api_key=json.dumps(sign_in.dump()), models=[], model_params={META_KEY: connector.meta}):
+ raise ConnectorError("Couldn't keep the sign-in. Try again.")
+
+
async def remove(ref: str, *, principal: Optional[str] = None) -> None:
auth = _auth()
scope = {"principal": principal} if principal is not None else {}
await auth.remove_api_key(ref, **scope)
await auth.remove_api_key(url_key(ref))
+ await auth.remove_oauth_tokens(ref)
__all__ = [
@@ -212,6 +224,7 @@ __all__ = [
"remove",
"save_meta",
"save_new",
+ "save_sign_in",
"slug_of",
"url_key",
]
diff --git a/server/nodes/mcp/mcp_connector.py b/server/nodes/mcp/mcp_connector.py
index e4aba1a4..21b917a6 100644
--- a/server/nodes/mcp/mcp_connector.py
+++ b/server/nodes/mcp/mcp_connector.py
@@ -27,6 +27,7 @@ from services.plugin.tool import ToolBinding, inline_schema_refs
from ._client import ConnectorError, call_name, call_tool, check_arguments
from ._credentials import TEMPLATE, McpConnectorCredential
+from ._oauth import connection_auth
from ._store import get_connector, list_connectors, read_access, slug_of
@@ -135,7 +136,8 @@ class McpConnectorNode(ToolNode):
arguments = params.model_dump()
check_arguments(tool["input_schema"], arguments)
url, sign_in = await read_access(connector)
- result = await call_tool(url, sign_in, connector.meta.get("transport") or "streamable_http", tool["name"], arguments)
+ 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)
except ConnectorError as exc:
raise NodeUserError(str(exc)) from None
if result.is_error:
diff --git a/server/services/auth.py b/server/services/auth.py
index edec863d..db505a8a 100644
--- a/server/services/auth.py
+++ b/server/services/auth.py
@@ -27,6 +27,7 @@ not detected.
import hashlib
import time
from dataclasses import dataclass, field
+from datetime import datetime
from typing import Dict, Any, Optional, List
from core.config import Settings
@@ -469,6 +470,7 @@ class AuthService:
name: Optional[str] = None,
scopes: Optional[str] = None,
customer_id: str = "owner",
+ expiry: Optional[datetime] = None,
) -> bool:
"""Store OAuth tokens in encrypted credentials database.
@@ -480,6 +482,7 @@ class AuthService:
name: User display name
scopes: Comma-separated scopes
customer_id: Customer identifier (default 'owner' for single-user)
+ expiry: When the access token expires (UTC), when known
Returns:
True if stored successfully
@@ -495,6 +498,7 @@ class AuthService:
refresh_token=refresh_token,
email=email,
name=name,
+ expiry=expiry,
scopes=scopes,
customer_id=customer_id,
)
@@ -598,6 +602,24 @@ class AuthService:
logger.error("Failed to get OAuth refresh token", provider=provider, error=str(e))
return None
+ async def get_stored_oauth_tokens(self, provider: str, customer_id: str = "owner") -> Optional[Dict[str, Any]]:
+ """The tokens as stored, read from the encrypted DB every time:
+ ``access_token``, ``refresh_token``, ``token_expiry`` and ``scopes``.
+
+ For a caller that refreshes its own tokens (a custom connector's
+ sign-in, nodes/mcp): another process may have refreshed them since
+ this one last read them, so neither copy is cached here.
+ """
+ self.require_local_credentials()
+ try:
+ tokens = await self.credentials_db.get_oauth_tokens(provider, customer_id)
+ except Exception as e:
+ logger.error("Failed to read OAuth tokens", provider=provider, error=str(e))
+ return None
+ if not tokens:
+ return None
+ return {key: tokens.get(key) for key in ("access_token", "refresh_token", "token_expiry", "scopes")}
+
async def refresh_oauth_tokens_with_breaker(
self,
provider: str,
diff --git a/server/services/events/oauth_lifecycle.py b/server/services/events/oauth_lifecycle.py
index 938aa21f..a2838dbd 100644
--- a/server/services/events/oauth_lifecycle.py
+++ b/server/services/events/oauth_lifecycle.py
@@ -520,8 +520,10 @@ def render_oauth_callback_html(
status: str,
message: str,
color_hex: str,
+ title: Optional[str] = None,
) -> str:
- """Render the small auto-closing callback page.
+ """Render the small auto-closing callback page. ``title`` replaces the
+ success heading ("<Provider> Connected").
``status`` MUST be ``"success"`` or ``"error"``. The page posts a
``{provider}_oauth_callback`` message to ``window.opener`` (the
@@ -555,7 +557,7 @@ def render_oauth_callback_html(
# so the JSON literal is also safe inside
# a ``<script>`` block.
is_success = status == "success"
- title = f"{provider.capitalize()} Connected" if is_success else "Connection Failed"
+ title = (title or f"{provider.capitalize()} Connected") if is_success else "Connection Failed"
return _HTML_TEMPLATE.format(
title=html.escape(title),
message=html.escape(message),
diff --git a/server/tests/credentials/test_auth_service.py b/server/tests/credentials/test_auth_service.py
index 8ed301e8..bcb715f9 100644
--- a/server/tests/credentials/test_auth_service.py
+++ b/server/tests/credentials/test_auth_service.py
@@ -190,3 +190,15 @@ class TestOAuthOps:
async def test_get_oauth_tokens_missing_provider_returns_none(self, auth_service):
assert await auth_service.get_oauth_tokens("never-stored") is None
+
+ async def test_tokens_keep_their_expiry_and_are_read_from_the_db(self, auth_service):
+ from datetime import datetime, timezone
+
+ expiry = datetime(2026, 10, 10, 12, 0, tzinfo=timezone.utc)
+ await auth_service.store_oauth_tokens("mcp:orders", "access-1", "refresh-1", scopes="read", expiry=expiry)
+ # Another process refreshed them: the DB changed under this one's cache.
+ await auth_service.credentials_db.save_oauth_tokens("mcp:orders", "access-2", "refresh-2", scopes="read", expiry=expiry)
+ stored = await auth_service.get_stored_oauth_tokens("mcp:orders")
+ assert (stored["access_token"], stored["refresh_token"], stored["scopes"]) == ("access-2", "refresh-2", "read")
+ assert stored["token_expiry"].replace(tzinfo=timezone.utc) == expiry
+ assert await auth_service.get_stored_oauth_tokens("never-stored") is None
diff --git a/server/tests/nodes/test_mcp_connector.py b/server/tests/nodes/test_mcp_connector.py
index dbb1a4f1..58622a1c 100644
--- a/server/tests/nodes/test_mcp_connector.py
+++ b/server/tests/nodes/test_mcp_connector.py
@@ -7,16 +7,18 @@ from __future__ import annotations
import contextlib
import functools
import json
+from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from typing import Any, Dict, List, Tuple
from unittest.mock import AsyncMock
+from urllib.parse import parse_qs, parse_qsl, urlsplit
import httpx
import pytest
from mcp.server.fastmcp import FastMCP
from mcp.types import Tool, ToolAnnotations
-from nodes.mcp import _client, _handlers, mcp_connector
+from nodes.mcp import _client, _handlers, _oauth, mcp_connector
from nodes.mcp._client import ConnectorError, SignIn, check_server, snapshots
from nodes.mcp._credentials import McpConnectorCredential
from nodes.mcp._store import new_slug
@@ -24,16 +26,32 @@ from nodes.mcp.mcp_connector import McpConnectorNode
from services.plugin import NodeContext
URL = "http://127.0.0.1:8931/mcp"
-SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id=None))
+SERVER = "http://127.0.0.1:8931"
+SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id=None), base_url="http://localhost:5678/")
class FakeAuth:
- """The credentials store: provider -> (secret, model_params)."""
+ """The credentials store: provider -> (secret, model_params), and the
+ OAuth token store: provider -> tokens."""
distributed_credentials = False
def __init__(self) -> None:
self.rows: Dict[str, Tuple[str, Dict[str, Any]]] = {}
+ self.oauth: Dict[str, Dict[str, Any]] = {}
+
+ async def store_oauth_tokens(self, provider, access_token, refresh_token, email=None, name=None, scopes=None, customer_id="owner", expiry=None):
+ self.oauth[provider] = {"access_token": access_token, "refresh_token": refresh_token, "token_expiry": expiry, "scopes": scopes}
+ return True
+
+ async def get_stored_oauth_tokens(self, provider, customer_id="owner"):
+ return dict(self.oauth[provider]) if provider in self.oauth else None
+
+ async def get_oauth_refresh_token(self, provider, customer_id="owner"):
+ return (self.oauth.get(provider) or {}).get("refresh_token")
+
+ async def remove_oauth_tokens(self, provider, customer_id="owner"):
+ return self.oauth.pop(provider, None) is not None
def require_local_credentials(self) -> None:
return None
@@ -124,6 +142,8 @@ class Refusing(httpx.AsyncBaseTransport):
def connect_through(monkeypatch, transport: httpx.AsyncBaseTransport) -> None:
monkeypatch.setattr(_handlers, "discover", functools.partial(_client.discover, http_transport=transport))
monkeypatch.setattr(_handlers, "read_again", functools.partial(_client.read_again, http_transport=transport))
+ monkeypatch.setattr(_handlers, "start_sign_in", functools.partial(_oauth.start_sign_in, http_transport=transport))
+ monkeypatch.setattr(mcp_connector, "call_tool", functools.partial(_client.call_tool, http_transport=transport))
@contextlib.asynccontextmanager
@@ -453,3 +473,136 @@ class TestInHires:
# Once it is removed, the card no longer lists it.
await _handlers.handle_mcp_connector_remove({"ref": "mcp:orders"}, SOCKET)
assert await _apps(graph, built.parameters, Connections(auth)) == []
+
+
+class SignsIn(httpx.AsyncBaseTransport):
+ """The MCP server behind OAuth, with an authorization server at
+ ``issuer``: its metadata, client registration, and tokens for the code
+ "the-code" or a refresh token it gave; 401 for a request without an
+ access token it gave."""
+
+ def __init__(self, inner: httpx.AsyncBaseTransport, *, issuer: str = SERVER) -> None:
+ self.inner, self.issuer = inner, issuer
+ self.access: set = set()
+ self.refresh: set = set()
+ self.issued = self.refreshed = 0
+
+ def _tokens(self, request: httpx.Request) -> httpx.Response:
+ self.issued += 1
+ access, 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)
+
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ await request.aread()
+ path = request.url.path
+ if path.startswith("/.well-known/oauth-protected-resource"):
+ return httpx.Response(200, json={"resource": URL, "authorization_servers": [f"{self.issuer}/"]}, request=request)
+ if path == "/.well-known/oauth-authorization-server":
+ endpoints = {"issuer": f"{SERVER}/", "authorization_endpoint": f"{SERVER}/authorize", "token_endpoint": f"{SERVER}/token"}
+ return httpx.Response(200, json={**endpoints, "registration_endpoint": f"{SERVER}/register"}, request=request)
+ if path == "/register":
+ return httpx.Response(201, json={**json.loads(request.content), "client_id": "client-1"}, request=request)
+ if path == "/token":
+ form = dict(parse_qsl(request.content.decode()))
+ if form.get("grant_type") == "authorization_code" and form.get("code") == "the-code":
+ return self._tokens(request)
+ if form.get("grant_type") == "refresh_token" and form.get("refresh_token") in self.refresh:
+ self.refreshed += 1
+ return self._tokens(request)
+ return httpx.Response(400, json={"error": "invalid_grant"}, request=request)
+ if request.headers.get("authorization", "").removeprefix("Bearer ") not in self.access:
+ challenge = f'Bearer resource_metadata="{SERVER}/.well-known/oauth-protected-resource/mcp"'
+ return httpx.Response(401, headers={"WWW-Authenticate": challenge}, request=request)
+ return await self.inner.handle_async_request(request)
+
+
+async def behind_sign_in(monkeypatch, server: FastMCP, **options):
+ gate = SignsIn(httpx.ASGITransport(app=server.streamable_http_app()), **options)
+ connect_through(monkeypatch, gate)
+ async with server.session_manager.run():
+ yield gate
+
+
+async def comes_back(address: str, **query: str) -> httpx.Response:
+ """The owner's browser, sent back from the server's sign-in page."""
+ from fastapi import FastAPI
+
+ from nodes.mcp._router import router
+
+ app = FastAPI()
+ app.include_router(router)
+ state = parse_qs(urlsplit(address).query)["state"][0]
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://localhost:5678") as browser:
+ return await browser.get("/api/mcp/oauth/callback", params={"code": "the-code", "state": state, **query})
+
+
+class TestOAuth:
+ """Signing in on the server's own page (nodes/mcp/_oauth.py)."""
+
+ async def test_add_signs_in_on_the_servers_page_then_keeps_it(self, auth, monkeypatch):
+ async with behind_sign_in(monkeypatch, orders_server()):
+ started = await add(sign_in={"kind": "oauth"})
+ assert started["success"] and started["ref"] == "mcp:orders"
+ address = started["sign_in_url"]
+ sent_back = parse_qs(urlsplit(address).query)
+ assert address.startswith(f"{SERVER}/authorize?") and sent_back["redirect_uri"] == ["http://localhost:5678/api/mcp/oauth/callback"]
+ assert sent_back["code_challenge_method"] == ["S256"]
+ # Nothing is kept until the owner has signed in.
+ assert auth.rows == {}
+ page = await comes_back(address)
+ assert "Orders is connected, with 2 tools." in page.text
+ assert auth.meta("mcp:orders")["sign_in"] == {"kind": "oauth"}
+ kept = json.loads(auth.rows["mcp:orders"][0])["oauth"]
+ assert kept["client"]["client_id"] == "client-1" and kept["authorization_server"]["token_endpoint"] == f"{SERVER}/token"
+ tokens = auth.oauth["mcp:orders"]
+ assert (tokens["access_token"], tokens["refresh_token"]) == ("access-1", "refresh-1")
+ assert tokens["token_expiry"] > datetime.now(timezone.utc) + timedelta(minutes=50)
+
+ async def test_an_expired_token_is_refreshed_and_kept_then_sign_in_again(self, auth, monkeypatch):
+ context = NodeContext(node_id="n1", node_type="mcpConnector", raw={})
+ async with behind_sign_in(monkeypatch, orders_server()) as gate:
+ await comes_back((await add(sign_in={"kind": "oauth"}))["sign_in_url"])
+
+ 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
+ auth.oauth["mcp:orders"]["token_expiry"] = datetime.now(timezone.utc) - timedelta(minutes=1)
+ assert (await call())["text"] == "Order A1: 2 books"
+ assert gate.refreshed == 1 and auth.oauth["mcp:orders"]["access_token"] == "access-2"
+ # A refresh the server refuses leaves only signing in again.
+ gate.refresh.clear()
+ auth.oauth["mcp:orders"]["token_expiry"] = datetime.now(timezone.utc) - timedelta(minutes=1)
+ assert await call() == {"error": "Orders needs you to sign in again: open it on the Connectors page and press Sign in again."}
+ 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 (await call())["text"] == "Order A1: 2 books"
+ assert (await _handlers.handle_mcp_connector_test({"ref": "mcp:orders"}, SOCKET))["ok"] is True
+ await _handlers.handle_mcp_connector_remove({"ref": "mcp:orders"}, SOCKET)
+ assert auth.oauth == {}
+
+ 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"]
+ page = await comes_back(address, error="access_denied", code="")
+ assert "The sign-in was refused: access_denied" in page.text
+ # The same sign-in again has ended.
+ assert "This sign-in has ended" in (await comes_back(address)).text
+ assert auth.rows == {} and auth.oauth == {}
+
+ async def test_only_a_server_that_asks_signs_in(self, auth, monkeypatch):
+ async with serving(monkeypatch, orders_server()):
+ assert await add(sign_in={"kind": "oauth"}) == {
+ "success": False,
+ "error": "127.0.0.1 didn't ask to sign in. Choose None, or the sign-in it uses.",
+ }
+
+ async def test_the_authorization_server_must_be_reachable_too(self, auth, monkeypatch):
+ # The server names its authorization server; cloud metadata is never reached.
+ async with behind_sign_in(monkeypatch, orders_server(), issuer="http://169.254.169.254"):
+ result = await add(sign_in={"kind": "oauth"})
+ assert result["success"] is False and result["error"].startswith("169.254.169.254 can't be used")
+ assert auth.rows == {}
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index aff63206..c06e218f 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -102,6 +102,7 @@ _PLUGINS_WITH_ROUTERS = (
"browser",
"discord",
"google",
+ "mcp",
"microsoft",
"twitter",
)