mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-04 14:16:49 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4793c139e9 | ||
|
|
3fde8b4cce | ||
|
|
fad072e16d | ||
|
|
4203379c77 | ||
|
|
a713203c20 | ||
|
|
91291ce049 | ||
|
|
74f0fbf93a | ||
|
|
ec2ca3b382 | ||
|
|
6eaedd252c | ||
|
|
671670f702 | ||
|
|
1494b42aca | ||
|
|
1b5b051905 | ||
|
|
9ad534ede7 |
@@ -51,6 +51,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/protocol-compatibility.md](docs/protocol-compatibility.md) | Why app/daemon versions drift, protocol vs feature contract, capability gating, COMPAT tagging |
|
||||
| [docs/protocol-validation.md](docs/protocol-validation.md) | zod-aot generated inbound WebSocket validation, patched compiler regressions, schema-purity rules |
|
||||
| [docs/connected-hosts.md](docs/connected-hosts.md) | Daemon-owned host registrations, routed SDK scopes, identity and authority boundaries |
|
||||
| [docs/mcp-server.md](docs/mcp-server.md) | Standalone MCP Server listener, tunnels and public URL, OAuth 2.1 and Bearer auth, sign-in approval, access presets |
|
||||
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
|
||||
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ You will see this warning once after you reset Paseo on a host. If you did not r
|
||||
|
||||
By default, the daemon binds to `127.0.0.1`. With no password configured, anything that can reach the daemon socket can control the daemon. Loopback is reachable by other users on the machine and by some forwarding tools.
|
||||
|
||||
The daemon supports an optional shared-secret password (set via `auth.password` in `config.json` or the `PASEO_PASSWORD` env var; stored bcrypt-hashed). WebSocket clients send the password in `hello`; the daemon sends no session data before admission. Direct connections still accept bearer headers and WebSocket bearer subprotocols for older clients. HTTP stays bearer-header based. Health (`GET /api/health`) and CORS preflight (`OPTIONS`) are exempt; `/api/files/download` and `/mcp/agents` use their own capability tokens.
|
||||
The daemon supports an optional shared-secret password (set via `auth.password` in `config.json` or the `PASEO_PASSWORD` env var; stored bcrypt-hashed). WebSocket clients send the password in `hello`; the daemon sends no session data before admission. Direct connections still accept bearer headers and WebSocket bearer subprotocols for older clients. HTTP stays bearer-header based. Health (`GET /api/health`) and CORS preflight (`OPTIONS`) are exempt; `/api/files/download` uses download tokens. `/_internal/mcp/agents` requires an agent capability token or an owner credential, even without a configured password.
|
||||
|
||||
The daemon writes a new `$PASEO_HOME/local-credential` on every run with mode `0600` and removes it on shutdown. The CLI and desktop main process read it only for the daemon whose PID lock `listen` matches their connection target. A same-user process can read this credential, so the password protects against network clients and other OS users, not processes running as the daemon user. Protect `$PASEO_HOME` accordingly. Relay traffic remains end-to-end encrypted independently of password admission.
|
||||
|
||||
|
||||
+18
-17
@@ -86,22 +86,23 @@ workspace for a directory clears it. The store lives in memory and resets on dae
|
||||
|
||||
**Key modules:**
|
||||
|
||||
| Module | Responsibility |
|
||||
| ------------------------------- | ------------------------------------------------------------------------------ |
|
||||
| `server/bootstrap.ts` | Daemon initialization: HTTP server, WS server, agent manager, storage, relay |
|
||||
| `server/websocket-server.ts` | WebSocket connection management, hello handshake, binary frame routing |
|
||||
| `server/session.ts` | Per-client session state, timeline subscriptions, terminal operations |
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
| `server/agent/providers/` | Provider adapters (see "Agent providers" below) |
|
||||
| `server/orchestration-skills/` | Bundled catalog, host selection, convergence, and skill-directory transactions |
|
||||
| `server/relay-transport.ts` | Outbound relay connection with E2E encryption |
|
||||
| `server/schedule/` | Cron-based scheduled agents |
|
||||
| Module | Responsibility |
|
||||
| ------------------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `server/bootstrap.ts` | Daemon initialization: HTTP server, WS server, agent manager, storage, relay |
|
||||
| `server/websocket-server.ts` | WebSocket connection management, hello handshake, binary frame routing |
|
||||
| `server/session.ts` | Per-client session state, timeline subscriptions, terminal operations |
|
||||
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
|
||||
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
|
||||
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
|
||||
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
|
||||
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
|
||||
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
|
||||
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
|
||||
| `server/mcp-server/` | Dedicated HTTP MCP Server with OAuth 2.1, Bearer tokens, and tunnels ([docs](mcp-server.md)) |
|
||||
| `server/agent/providers/` | Provider adapters (see "Agent providers" below) |
|
||||
| `server/orchestration-skills/` | Bundled catalog, host selection, convergence, and skill-directory transactions |
|
||||
| `server/relay-transport.ts` | Outbound relay connection with E2E encryption |
|
||||
| `server/schedule/` | Cron-based scheduled agents |
|
||||
|
||||
### `packages/protocol` — Wire schemas and shared protocol types
|
||||
|
||||
@@ -467,7 +468,7 @@ All providers:
|
||||
- Map tool calls to a normalized `ToolCallDetail` type
|
||||
- Expose provider-specific modes (plan, default, full-access)
|
||||
|
||||
Providers that can accept native tool definitions should set `supportsNativePaseoTools` and read `launchContext.paseoTools`. The daemon then passes the shared Paseo tool catalog directly and removes the internal Paseo MCP server from that provider launch config. Providers that only support MCP continue to receive the same tools through the MCP fallback at `/mcp/agents`.
|
||||
Providers that can accept native tool definitions should set `supportsNativePaseoTools` and read `launchContext.paseoTools`. The daemon then passes the shared Paseo tool catalog directly and removes the internal Paseo MCP server from that provider launch config. Providers that only support MCP continue to receive the same tools through the MCP fallback at `/_internal/mcp/agents`.
|
||||
|
||||
## Data flow: running an agent
|
||||
|
||||
|
||||
+5
-1
@@ -69,6 +69,9 @@ $PASEO_HOME/
|
||||
├── runtime/
|
||||
│ └── managed-processes/
|
||||
│ └── {recordId}.json # Helper processes owned by Paseo; reconciled on daemon bootstrap
|
||||
├── mcp-server/
|
||||
│ ├── credentials.json # Apps and Bearer tokens: hashed secrets and permissions (mode 0600)
|
||||
│ └── oauth-signing-key # Signs stateless OAuth client IDs (mode 0600)
|
||||
├── plugins/
|
||||
│ ├── sources.json # Managed kind and Git acquisition remote
|
||||
│ └── {pluginId}/{uuid}/ # Git checkout or npm package/lockfile/dependency tree
|
||||
@@ -264,7 +267,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
|
||||
agentProfiles: AgentProfile[], // named agent launch bundles; omitted means none
|
||||
cors: { allowedOrigins: string[] },
|
||||
relay: { enabled: boolean, endpoint: string, publicEndpoint: string, useTls: boolean, publicUseTls: boolean }, // new homes materialize enabled: false
|
||||
auth: { password: string } // bcrypt hash, optional
|
||||
auth: { password: string }, // bcrypt hash, optional
|
||||
mcpServer: { enabled: boolean, listenHost: string, port: number, tunnelProviderId: string, publicUrl: string, auth: { oauth: boolean, bearerTokens: boolean, defaultPermissions: string[] } }
|
||||
},
|
||||
app: {
|
||||
baseUrl: string
|
||||
|
||||
+1
-1
@@ -389,7 +389,7 @@ npm run measure:agent-tools --workspace=@getpaseo/server
|
||||
|
||||
The command reports compact JSON bytes, estimated tokens, field totals, largest
|
||||
tools, and the browser-tools delta. It defaults to the agent-scoped catalog; use
|
||||
`-- --scope=top-level` for the unaffiliated `/mcp/agents` shape and `-- --json`
|
||||
`-- --scope=top-level` for the top-level catalog and `-- --json`
|
||||
for machine-readable output.
|
||||
|
||||
## Worktree starting refs
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# MCP Server
|
||||
|
||||
The MCP Server lets clients outside Paseo use Paseo's top-level tools over HTTP. The daemon runs its own HTTP listener and OAuth 2.1 authorization server, so sign-in requires no external accounts or third-party identity providers. Connected clients receive only the tool inputs and results allowed by their granted permissions, and enabling a tunnel or public URL routes requests through that endpoint.
|
||||
|
||||
Code lives in `packages/server/src/server/mcp-server/` (server), `packages/app/src/mcp-server/` (Settings and approval prompt), and `packages/protocol/src/mcp-server.ts` (wire schemas and access presets).
|
||||
|
||||
## Addresses
|
||||
|
||||
The MCP Server runs its own HTTP listener, separate from the daemon port (`:6767`) and separate from the internal agent bridge (`/_internal/mcp/agents`). The listener serves only `/mcp` and, while OAuth is on, the OAuth metadata and sign-in pages. It never serves the daemon WebSocket API or the web app.
|
||||
|
||||
```text
|
||||
listener (always, while enabled) http://127.0.0.1:6770/mcp listenHost, port
|
||||
+ tunnel (optional) https://abc.tunnel.example/mcp any TunnelProvider
|
||||
+ public URL (optional) https://mcp.example.com/mcp reverse proxy, own domain
|
||||
```
|
||||
|
||||
All active addresses work at the same time. A tunnel adds an address without removing the local listener. Binding `0.0.0.0` or a LAN address exposes only the MCP Server listener, never the daemon port. The default port stays fixed at `6770` so reverse proxies and saved client configurations keep working across restarts.
|
||||
|
||||
While OAuth is enabled, each request resolves its origin against the allowlist built from these addresses (`internal/origins.ts`). OAuth metadata, the issuer, and the protected resource name that origin. The server checks `X-Forwarded-Host` first because tunnels rewrite `Host`, and accepts only hosts already on the allowlist. Any unknown host receives HTTP `421`.
|
||||
|
||||
If a tunnel rewrites `Host` and omits `X-Forwarded-Host`, the request resolves to the loopback origin, and OAuth discovery fails. Set the tunnel's public origin as `publicUrl` so the allowlist accepts it.
|
||||
|
||||
## Authentication
|
||||
|
||||
Two independent flags control authentication under `daemon.mcpServer.auth`:
|
||||
|
||||
- `oauth` (default `true`): Mounts `/.well-known/oauth-*` and `/oauth/*`, enforces the host allowlist, and accepts OAuth credentials.
|
||||
- `bearerTokens` (default `true`): Accepts static Bearer credentials minted in Paseo.
|
||||
|
||||
When `oauth` and `bearerTokens` are both `false`, `/mcp` accepts unauthenticated requests with `defaultPermissions` (`[]` by default). In that mode, the server does not mount OAuth routes or enforce the `421` host allowlist.
|
||||
|
||||
## OAuth sign-in and approval
|
||||
|
||||
Client registration is stateless. The issued `client_id` holds the client name and redirect URIs, signed with an HMAC using `$PASEO_HOME/mcp-server/oauth-signing-key`. Redirect URIs must use `https` or loopback `http` without fragments or credentials. Loopback redirects match any port (RFC 8252).
|
||||
|
||||
Authorization requires PKCE with `S256`. Authorization codes expire after 60 seconds and are spent on the first exchange attempt, even if it fails. Issued access tokens are long-lived Bearer credentials with no refresh tokens. Revoking the credential is the only way to end access.
|
||||
|
||||
`/oauth/authorize` opens an in-memory pending sign-in and renders a waiting page with a verification code such as `123-456`. Every connected Paseo client with `access.manage` sees the sign-in through `mcp_server.access.list` and prompts the owner with the app name, the redirect host, and the same code. The owner chooses an access preset and approves or denies.
|
||||
|
||||
Pending sign-ins expire after 3 minutes, with at most 20 open at once and 5 per IP per minute. When no Paseo app is open to prompt, the owner can generate a one-time approval code (`XXXXX-XXXXX`, valid for 10 minutes, up to 10 open) in Settings and enter it on the browser sign-in page. Submitting an approval code directly creates a session without using the 20-slot pending queue. Five wrong attempts lock that sign-in.
|
||||
|
||||
## Access and presets
|
||||
|
||||
Credentials store explicit permissions, never preset names, so expanding a preset does not widen existing grants. The presets are Read-only, Orchestrate, and Full (`MCP_SERVER_PERMISSION_PRESETS`). The granting session must already hold every permission it grants, as described in [permissions](permissions.md).
|
||||
|
||||
Each MCP request builds an MCP server holding only the top-level tools allowed by its granted permissions. This tool catalog does not depend on `daemon.tools.enabled`. Tools routed to [connected hosts](connected-hosts.md) carry the credential's permissions, not the daemon owner's.
|
||||
|
||||
`/mcp` rejects any request carrying an `Origin` header with HTTP `403`, even when authentication is off, so browser pages cannot call `/mcp` directly.
|
||||
+1
-1
@@ -35,7 +35,7 @@ Connected-host management uses `tunnel.manage`; source-owned connection and meta
|
||||
requires the producer or `access.manage`. Routed operations retain both caller and link authority,
|
||||
see [Connected hosts](connected-hosts.md#ownership-and-authority).
|
||||
|
||||
Owner, operator, and viewer are UI presets expanded into explicit permissions. Do not persist them as roles. Adding a permission must not silently widen an existing principal.
|
||||
Owner, operator, and viewer are UI presets expanded into explicit permissions. Do not persist them as roles. Adding a permission must not silently widen an existing principal. [MCP Server](mcp-server.md) credentials follow the same rule with their own presets.
|
||||
|
||||
Permissions are additive allows. Missing authority denies the operation. Do not add deny precedence.
|
||||
|
||||
|
||||
+2
-2
@@ -130,7 +130,7 @@ Keep the curated Claude catalog: `supportedModels()` has historically omitted ol
|
||||
|
||||
Paseo tools are not implemented as MCP tools internally. They live in a shared tool catalog under `packages/server/src/server/agent/tools/`; MCP is only the fallback adapter. The daemon resolves `agents.providers.<provider>.paseoTools` by the exact provider ID. The catalog policy belongs to the caller: it filters the tools exposed to the current agent. When that agent calls `create_agent`, the child receives the policy for the child provider ID; the caller's policy is not inherited.
|
||||
|
||||
A provider that can register runtime tools directly should set `supportsNativePaseoTools: true` and consume the already-filtered `launchContext.paseoTools` in `createSession`/`resumeSession`. When native tools are present, `AgentManager` strips the internal Paseo MCP server from the provider launch config so the provider does not receive the same tools twice. Providers that only know MCP should keep `supportsMcpServers: true` and let the daemon inject `/mcp/agents`; the MCP server builds the same policy-filtered catalog for that caller. Filtering is enforced at catalog registration in both paths. Browser tools remain subject to the daemon browser-tools setting and browser-host availability.
|
||||
A provider that can register runtime tools directly should set `supportsNativePaseoTools: true` and consume the already-filtered `launchContext.paseoTools` in `createSession`/`resumeSession`. When native tools are present, `AgentManager` strips the internal Paseo MCP server from the provider launch config so the provider does not receive the same tools twice. Providers that only know MCP should keep `supportsMcpServers: true` and let the daemon inject `/_internal/mcp/agents`; the MCP server builds the same policy-filtered catalog for that caller. Filtering is enforced at catalog registration in both paths. Browser tools remain subject to the daemon browser-tools setting and browser-host availability.
|
||||
|
||||
Pi is a process-backed provider. Paseo requires the user to have the `pi` binary installed and talks to it through `pi --mode rpc`; the server package does not embed Pi's SDK/runtime packages.
|
||||
|
||||
@@ -142,7 +142,7 @@ Pi model records expose input capabilities through `model.input`. Only send raw
|
||||
|
||||
Probe Pi MCP support with Pi RPC `get_commands` for the agent cwd. Pi 0.99 and later ship MCP as a built-in extension, which registers an extension command named `mcp` with `sourceInfo.path` `builtin:mcp`. Register injected servers through `pi.registerMcpServer` in Paseo's generated extension; the built-in extension rejects SSE servers and names with characters other than letters, digits, `_`, and `-`, and a server of the same name in Pi's `mcp.json` takes precedence.
|
||||
|
||||
The open-source `pi-mcp-adapter` extension replaces the built-in one and registers its own `mcp` command (often with `sourceInfo.source` containing `pi-mcp-adapter`). When it is loaded, write a per-agent MCP config and pass it with `--mcp-config` instead of modifying user or project MCP files. Because that flag replaces the Pi global config layer, preserve the existing `<Pi agent dir>/mcp.json` in the generated file before overlaying injected servers. For local HTTP servers such as Paseo's own `/mcp/agents` endpoint, explicitly disable adapter OAuth (`auth: false`, `oauth: false`) in the generated config.
|
||||
The open-source `pi-mcp-adapter` extension replaces the built-in one and registers its own `mcp` command (often with `sourceInfo.source` containing `pi-mcp-adapter`). When it is loaded, write a per-agent MCP config and pass it with `--mcp-config` instead of modifying user or project MCP files. Because that flag replaces the Pi global config layer, preserve the existing `<Pi agent dir>/mcp.json` in the generated file before overlaying injected servers. For local HTTP servers such as Paseo's own `/_internal/mcp/agents` endpoint, explicitly disable adapter OAuth (`auth: false`, `oauth: false`) in the generated config.
|
||||
|
||||
Pi control-plane RPCs wait 60 seconds by default. Override `params.rpcTimeoutMs` when extension or MCP startup on a slow host needs more time. Timeout errors name the pending RPC phase and report both elapsed time and the configured deadline. This setting does not govern long-running Pi compaction or Pi extension UI results. See [OMP profiles and Pi-compatible forks](custom-providers.md#omp-profiles-and-pi-compatible-forks) for OMP startup and RPC deadlines.
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { test } from "../support/fixtures";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
allocateFreePort,
|
||||
approveOAuthSignIn,
|
||||
captureMcpScreenshot,
|
||||
createBearerToken,
|
||||
fetchMcpTools,
|
||||
openMcpServerSettings,
|
||||
resetMcpServerState,
|
||||
selectDefaultAccess,
|
||||
setListenerPort,
|
||||
setSwitchRow,
|
||||
startOAuthBrowserSignIn,
|
||||
stripMcpServerFeature,
|
||||
verifyOAuthSetupGuides,
|
||||
} from "../support/helpers/mcp-server";
|
||||
import { openSettingsHost, seedSavedSettingsHosts } from "../support/helpers/settings";
|
||||
|
||||
test.describe("MCP Server settings and OAuth approval", () => {
|
||||
test("starts disabled, enables on a configured port, shows OAuth setup guides, and serves Bearer tokens", async ({
|
||||
page,
|
||||
}) => {
|
||||
await resetMcpServerState({ enabled: false });
|
||||
const port = await allocateFreePort();
|
||||
const mcpUrl = `http://127.0.0.1:${port}/mcp`;
|
||||
|
||||
await openMcpServerSettings(page);
|
||||
|
||||
await expect(page.getByTestId("mcp-server-listener-status")).toHaveText("Stopped");
|
||||
await expect(page.getByTestId("mcp-server-urls")).toContainText(
|
||||
"Turn on MCP Server to get a URL.",
|
||||
);
|
||||
await captureMcpScreenshot(page, "desktop-mcp-off");
|
||||
|
||||
await setListenerPort(page, port);
|
||||
await setSwitchRow(page, "mcp-server-enabled", true);
|
||||
await expect(page.getByTestId("mcp-server-listener-status")).toHaveText("Listening");
|
||||
await expect(page.getByTestId("mcp-server-url")).toContainText(mcpUrl);
|
||||
await expect(page.getByTestId("mcp-server-create-token")).toBeVisible();
|
||||
await expect(page.getByTestId("mcp-server-create-code")).toBeVisible();
|
||||
await captureMcpScreenshot(page, "desktop-mcp-on-both-auth");
|
||||
|
||||
await verifyOAuthSetupGuides(page, mcpUrl, "desktop-mcp-guide-openclaw");
|
||||
|
||||
await setSwitchRow(page, "mcp-server-auth-oauth", false);
|
||||
await expect(page.getByTestId("mcp-server-create-code")).toHaveCount(0);
|
||||
await expect(page.getByTestId("mcp-server-create-token")).toBeVisible();
|
||||
await captureMcpScreenshot(page, "desktop-mcp-bearer-only");
|
||||
|
||||
const issuedToken = await createBearerToken(page, "E2E script");
|
||||
expect((await fetchMcpTools(mcpUrl)).status).toBe(401);
|
||||
|
||||
const tokenResult = await fetchMcpTools(mcpUrl, { Authorization: `Bearer ${issuedToken}` });
|
||||
expect(tokenResult.status).toBe(200);
|
||||
expect(tokenResult.tools.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("warns and applies Default access when both OAuth and Bearer tokens are disabled", async ({
|
||||
page,
|
||||
}) => {
|
||||
const port = await allocateFreePort();
|
||||
const mcpUrl = `http://127.0.0.1:${port}/mcp`;
|
||||
await resetMcpServerState({ enabled: true, port });
|
||||
|
||||
await openMcpServerSettings(page);
|
||||
await setSwitchRow(page, "mcp-server-auth-oauth", false);
|
||||
await setSwitchRow(page, "mcp-server-auth-bearer", false);
|
||||
|
||||
await expect(page.getByTestId("mcp-server-no-auth-warning")).toBeVisible();
|
||||
await expect(page.getByTestId("mcp-server-default-access")).toContainText("None (no tools)");
|
||||
await captureMcpScreenshot(page, "desktop-mcp-no-auth-none");
|
||||
|
||||
await selectDefaultAccess(page, "Read-only");
|
||||
await captureMcpScreenshot(page, "desktop-mcp-no-auth-read");
|
||||
|
||||
const openResult = await fetchMcpTools(mcpUrl);
|
||||
expect(openResult.status).toBe(200);
|
||||
expect(openResult.tools.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("prompts in-app for live OAuth sign-in without focusing close and issues an OAuth token", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const port = await allocateFreePort();
|
||||
const baseUrl = `http://127.0.0.1:${port}`;
|
||||
const mcpUrl = `${baseUrl}/mcp`;
|
||||
await resetMcpServerState({ enabled: true, port });
|
||||
|
||||
await openMcpServerSettings(page);
|
||||
|
||||
const signIn = await startOAuthBrowserSignIn(context, baseUrl, "E2E OAuth Client");
|
||||
try {
|
||||
await approveOAuthSignIn(page, {
|
||||
clientName: "E2E OAuth Client",
|
||||
redirectHost: signIn.redirectHost,
|
||||
preset: "orchestrate",
|
||||
screenshotName: "desktop-mcp-approval-modal",
|
||||
});
|
||||
|
||||
const oauthToken = await signIn.completeAfterApproval();
|
||||
const oauthResult = await fetchMcpTools(mcpUrl, { Authorization: `Bearer ${oauthToken}` });
|
||||
expect(oauthResult.status).toBe(200);
|
||||
expect(oauthResult.tools.length).toBeGreaterThan(0);
|
||||
|
||||
await expect(page.getByTestId("mcp-server-credentials")).toContainText("E2E OAuth Client");
|
||||
await expect(page.getByTestId("mcp-server-credentials")).toContainText("Orchestrate");
|
||||
} finally {
|
||||
await signIn.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("renders MCP Server settings cleanly on a compact mobile viewport", async ({ page }) => {
|
||||
const port = await allocateFreePort();
|
||||
await resetMcpServerState({ enabled: true, port });
|
||||
|
||||
await openMcpServerSettings(page);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expect(page.getByTestId("mcp-server-enabled")).toBeVisible();
|
||||
await captureMcpScreenshot(page, "compact-mcp-settings");
|
||||
});
|
||||
|
||||
test("gates MCP Server entry on server_info.features.mcpServer for older daemons", async ({
|
||||
page,
|
||||
outdatedDaemon,
|
||||
}) => {
|
||||
await stripMcpServerFeature(page, outdatedDaemon.endpoint);
|
||||
await seedSavedSettingsHosts(page, [outdatedDaemon]);
|
||||
await page.reload();
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, outdatedDaemon.serverId);
|
||||
|
||||
const sidebar = page.getByTestId("settings-sidebar");
|
||||
await expect(sidebar.getByTestId("settings-host-section-daemon")).toBeVisible();
|
||||
await expect(sidebar.getByTestId("settings-host-section-mcp-server")).toHaveCount(0);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const nonce = localStorage.getItem("@paseo:e2e-seed-nonce");
|
||||
if (nonce) localStorage.setItem("@paseo:e2e-disable-default-seed-once", nonce);
|
||||
});
|
||||
await page.goto(buildSettingsHostSectionRoute(outdatedDaemon.serverId, "mcp-server"));
|
||||
await expect(page.getByTestId("mcp-server-unavailable")).toHaveText(
|
||||
"Update this host to run the MCP Server.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
|
||||
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { getE2EDaemonPort, getE2EMcpRequestInit } from "../support/helpers/daemon-port";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
@@ -305,7 +305,10 @@ async function callPaseoToolAs(
|
||||
const mcp = new Client({ name: "turn-collapse-e2e", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
|
||||
new URL(
|
||||
`http://127.0.0.1:${getE2EDaemonPort()}/_internal/mcp/agents?callerAgentId=${callerAgentId}`,
|
||||
),
|
||||
{ requestInit: getE2EMcpRequestInit() },
|
||||
),
|
||||
);
|
||||
try {
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { TestInfo } from "@playwright/test";
|
||||
import { test as base, expect, type Page } from "../fixtures";
|
||||
import { buildHostAgentDetailRoute } from "@/utils/host-routes";
|
||||
import { openSessions } from "./archive-tab";
|
||||
import { getE2EDaemonPort } from "./daemon-port";
|
||||
import { getE2EDaemonPort, getE2EMcpRequestInit } from "./daemon-port";
|
||||
import { assertComposerIdle } from "./rewind-flow";
|
||||
import { getServerId } from "./server-id";
|
||||
import { archiveWorkspaceFromSidebar, expectWorkspaceAbsentFromSidebar } from "./sidebar";
|
||||
@@ -80,7 +80,8 @@ async function createCodexRestoreJourney(page: Page, client: SeedDaemonClient, i
|
||||
async createWorktreeWithCodex() {
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents`),
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/_internal/mcp/agents`),
|
||||
{ requestInit: getE2EMcpRequestInit() },
|
||||
),
|
||||
);
|
||||
workspace = workspaceSchema.parse(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { escapeRegex } from "./regex";
|
||||
|
||||
/**
|
||||
@@ -21,6 +23,23 @@ export function getE2EDaemonPort(): string {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `requestInit` with the isolated E2E daemon's `local-credential`
|
||||
* bearer header for authenticating direct `/_internal/mcp/agents` owner calls.
|
||||
*/
|
||||
export function getE2EMcpRequestInit(): { headers: Record<string, string> } {
|
||||
const paseoHome = process.env.E2E_PASEO_HOME;
|
||||
if (!paseoHome) {
|
||||
throw new Error("E2E_PASEO_HOME is not set (expected from the Playwright worker fixture).");
|
||||
}
|
||||
const token = readFileSync(path.join(paseoHome, "local-credential"), "utf8").trim();
|
||||
return {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Playwright `routeWebSocket` matcher for a WebSocket on `port`. Matches the
|
||||
* `:<port>` segment at a word boundary, so it catches the URL regardless of
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { createServer as createHttpServer, type Server as HttpServer } from "node:http";
|
||||
import { createServer } from "node:net";
|
||||
import path from "node:path";
|
||||
import { type BrowserContext, expect, type Page } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "./app";
|
||||
import { connectDaemonClient } from "./daemon-client-loader";
|
||||
import { wsRoutePatternForPort } from "./daemon-port";
|
||||
import { getServerId } from "./server-id";
|
||||
import { openHostSection } from "./settings";
|
||||
|
||||
const ARTIFACT_DIR = process.env.PASEO_MCP_ARTIFACT_DIR?.trim() || null;
|
||||
|
||||
interface McpServerResetClient {
|
||||
configureMcpServer(patch: {
|
||||
enabled?: boolean;
|
||||
listenHost?: string;
|
||||
port?: number;
|
||||
tunnelProviderId?: string | null;
|
||||
publicUrl?: string | null;
|
||||
auth?: {
|
||||
oauth?: boolean;
|
||||
bearerTokens?: boolean;
|
||||
defaultPermissions?: string[];
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
listMcpServerAccess(): Promise<{ credentials: Array<{ id: string }> }>;
|
||||
revokeMcpServerCredential(id: string): Promise<boolean>;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Saves a named full-page screenshot when `PASEO_MCP_ARTIFACT_DIR` is set. */
|
||||
export async function captureMcpScreenshot(page: Page, name: string): Promise<void> {
|
||||
if (!ARTIFACT_DIR) return;
|
||||
await mkdir(ARTIFACT_DIR, { recursive: true });
|
||||
await page.waitForTimeout(250);
|
||||
await page.screenshot({ path: path.join(ARTIFACT_DIR, `${name}.png`), fullPage: true });
|
||||
}
|
||||
|
||||
/** Allocates an ephemeral loopback port for isolated listener tests. */
|
||||
export async function allocateFreePort(): Promise<number> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const server = createServer();
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
server.close();
|
||||
reject(new Error("Could not allocate a free port"));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Restores the worker daemon's MCP Server config and clears credentials before a scenario. */
|
||||
export async function resetMcpServerState(options?: {
|
||||
enabled?: boolean;
|
||||
port?: number;
|
||||
}): Promise<void> {
|
||||
const client = await connectDaemonClient<McpServerResetClient>({
|
||||
clientIdPrefix: "mcp-server-reset",
|
||||
});
|
||||
try {
|
||||
await client.configureMcpServer({
|
||||
enabled: options?.enabled ?? false,
|
||||
listenHost: "127.0.0.1",
|
||||
port: options?.port ?? 6770,
|
||||
tunnelProviderId: null,
|
||||
publicUrl: null,
|
||||
auth: { oauth: true, bearerTokens: true, defaultPermissions: [] },
|
||||
});
|
||||
const { credentials } = await client.listMcpServerAccess();
|
||||
for (const credential of credentials) {
|
||||
await client.revokeMcpServerCredential(credential.id);
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens Settings -> MCP Server for the active E2E host. */
|
||||
export async function openMcpServerSettings(page: Page, serverId = getServerId()): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openHostSection(page, serverId, "mcp-server");
|
||||
await expect(page.getByTestId("page-title")).toHaveText("MCP Server");
|
||||
}
|
||||
|
||||
/** Updates the listener port through the Listen address sheet. */
|
||||
export async function setListenerPort(page: Page, port: number): Promise<void> {
|
||||
await page.getByTestId("mcp-server-listener").click();
|
||||
await expect(page.getByTestId("mcp-server-listener-sheet")).toBeVisible();
|
||||
await page.getByTestId("mcp-server-listener-port").fill(String(port));
|
||||
await page.getByTestId("mcp-server-listener-save").click();
|
||||
await expect(page.getByTestId("mcp-server-listener-sheet")).toBeHidden();
|
||||
await expect(page.getByTestId("mcp-server-listener")).toContainText(`127.0.0.1:${port}`);
|
||||
}
|
||||
|
||||
/** Sets a settings switch row (`mcp-server-enabled`, `mcp-server-auth-oauth`, `mcp-server-auth-bearer`). */
|
||||
export async function setSwitchRow(
|
||||
page: Page,
|
||||
rowTestId: string,
|
||||
expectedChecked: boolean,
|
||||
): Promise<void> {
|
||||
const toggle = page.getByTestId(rowTestId).getByRole("switch");
|
||||
const current = await toggle.getAttribute("aria-checked");
|
||||
if (current !== String(expectedChecked)) {
|
||||
await toggle.click();
|
||||
}
|
||||
await expect(toggle).toHaveAttribute("aria-checked", String(expectedChecked));
|
||||
}
|
||||
|
||||
/** Opens the Setup guides modal, inspects OpenClaw and Poke OAuth instructions, and optionally captures OpenClaw. */
|
||||
export async function verifyOAuthSetupGuides(
|
||||
page: Page,
|
||||
mcpUrl: string,
|
||||
screenshotName?: string,
|
||||
): Promise<void> {
|
||||
await page.getByTestId("mcp-server-connect-app").click();
|
||||
await expect(page.getByTestId("mcp-server-connect")).toBeVisible();
|
||||
|
||||
await page.getByTestId("mcp-server-connect-openclaw").click();
|
||||
await expect(page.getByTestId("mcp-server-connect-snippet")).toContainText(
|
||||
`openclaw mcp set paseo '{"url":"${mcpUrl}","transport":"streamable-http","auth":"oauth"}'`,
|
||||
);
|
||||
await expect(page.getByTestId("mcp-server-token-create")).toHaveCount(0);
|
||||
if (screenshotName) {
|
||||
await captureMcpScreenshot(page, screenshotName);
|
||||
}
|
||||
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await page.getByTestId("mcp-server-connect-poke").click();
|
||||
await expect(page.getByTestId("mcp-server-connect-needs-public")).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(page.getByTestId("mcp-server-connect")).toBeHidden();
|
||||
}
|
||||
|
||||
/** Creates a static Bearer token via the UI modal and returns the revealed `pmcp_` secret. */
|
||||
export async function createBearerToken(page: Page, name: string): Promise<string> {
|
||||
await page
|
||||
.getByTestId("mcp-server-create-token")
|
||||
.getByRole("button", { name: "Create token", exact: true })
|
||||
.click();
|
||||
await page.getByTestId("mcp-server-token-name").fill(name);
|
||||
await page.getByTestId("mcp-server-token-create").click();
|
||||
const tokenEl = page.getByTestId("mcp-server-token-value");
|
||||
await expect(tokenEl).toBeVisible();
|
||||
const token = (await tokenEl.textContent()) ?? "";
|
||||
expect(token).toMatch(/^pmcp_/);
|
||||
await page.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(page.getByTestId("mcp-server-credentials")).toContainText(name);
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Selects a Default access preset when both OAuth and Bearer tokens are off. */
|
||||
export async function selectDefaultAccess(page: Page, presetLabel: string): Promise<void> {
|
||||
await page.getByRole("button", { name: /Default access:/ }).click();
|
||||
await page.getByRole("menuitem", { name: presetLabel, exact: true }).click();
|
||||
await expect(page.getByTestId("mcp-server-default-access")).toContainText(presetLabel);
|
||||
}
|
||||
|
||||
/** Sends `tools/list` to the MCP HTTP endpoint and returns HTTP status + tool names. */
|
||||
export async function fetchMcpTools(
|
||||
mcpUrl: string,
|
||||
headers: Record<string, string> = {},
|
||||
): Promise<{ status: number; tools: string[] }> {
|
||||
const res = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json, text/event-stream",
|
||||
...headers,
|
||||
},
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
|
||||
});
|
||||
if (!res.ok) return { status: res.status, tools: [] };
|
||||
const text = await res.text();
|
||||
const dataLine = text
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("data:"))
|
||||
?.slice(5)
|
||||
.trim();
|
||||
const parsed = JSON.parse(dataLine ?? text) as {
|
||||
result?: { tools?: Array<{ name: string }> };
|
||||
};
|
||||
return {
|
||||
status: res.status,
|
||||
tools: (parsed.result?.tools ?? []).map((tool) => tool.name),
|
||||
};
|
||||
}
|
||||
|
||||
interface PendingOAuthBrowserSession {
|
||||
completeAfterApproval(): Promise<string>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Registers a PKCE client, opens `/oauth/authorize` in a second tab, and waits for the pending screen. */
|
||||
export async function startOAuthBrowserSignIn(
|
||||
context: BrowserContext,
|
||||
baseUrl: string,
|
||||
clientName: string,
|
||||
): Promise<PendingOAuthBrowserSession & { redirectHost: string }> {
|
||||
let resolveCallback!: (url: URL) => void;
|
||||
const callbackPromise = new Promise<URL>((resolve) => {
|
||||
resolveCallback = resolve;
|
||||
});
|
||||
let callbackPort = 0;
|
||||
const callbackServer: HttpServer = createHttpServer((req, res) => {
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
res.end("Signed in");
|
||||
resolveCallback(new URL(req.url ?? "/", `http://127.0.0.1:${callbackPort}`));
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
callbackServer.once("error", reject);
|
||||
callbackServer.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
const address = callbackServer.address();
|
||||
if (!address || typeof address === "string") {
|
||||
callbackServer.close();
|
||||
throw new Error("Could not bind OAuth callback receiver");
|
||||
}
|
||||
callbackPort = address.port;
|
||||
const redirectUri = `http://127.0.0.1:${callbackPort}/callback`;
|
||||
const redirectHost = new URL(redirectUri).host;
|
||||
|
||||
const browserPage = await context.newPage();
|
||||
const close = async () => {
|
||||
await browserPage.close().catch(() => undefined);
|
||||
await new Promise<void>((resolve) => callbackServer.close(() => resolve()));
|
||||
};
|
||||
|
||||
try {
|
||||
const dcrRes = await fetch(`${baseUrl}/oauth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ client_name: clientName, redirect_uris: [redirectUri] }),
|
||||
});
|
||||
expect(dcrRes.status).toBe(201);
|
||||
const { client_id: clientId } = (await dcrRes.json()) as { client_id: string };
|
||||
|
||||
const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
|
||||
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
||||
const authUrl = new URL(`${baseUrl}/oauth/authorize`);
|
||||
authUrl.searchParams.set("response_type", "code");
|
||||
authUrl.searchParams.set("client_id", clientId);
|
||||
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||
authUrl.searchParams.set("code_challenge", challenge);
|
||||
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||
authUrl.searchParams.set("state", "e2e-state");
|
||||
|
||||
await browserPage.goto(authUrl.toString());
|
||||
await expect(browserPage.locator("body")).toContainText("Approve this sign-in in Paseo");
|
||||
|
||||
return {
|
||||
redirectHost,
|
||||
close,
|
||||
async completeAfterApproval() {
|
||||
const callbackUrl = await callbackPromise;
|
||||
expect(callbackUrl.searchParams.get("state")).toBe("e2e-state");
|
||||
const code = callbackUrl.searchParams.get("code");
|
||||
expect(code).toBeTruthy();
|
||||
|
||||
const tokenRes = await fetch(`${baseUrl}/oauth/token`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: code!,
|
||||
redirect_uri: redirectUri,
|
||||
client_id: clientId,
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
});
|
||||
expect(tokenRes.status).toBe(200);
|
||||
const { access_token } = (await tokenRes.json()) as { access_token: string };
|
||||
return access_token;
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Verifies the in-app OAuth approval modal (including close button focus), picks a preset, and approves. */
|
||||
export async function approveOAuthSignIn(
|
||||
page: Page,
|
||||
options: {
|
||||
clientName: string;
|
||||
redirectHost: string;
|
||||
preset: "read" | "orchestrate" | "full";
|
||||
screenshotName?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const modal = page.getByTestId("mcp-server-approval");
|
||||
await expect(modal).toBeVisible();
|
||||
await expect(modal).toContainText(options.clientName);
|
||||
await expect(modal).toContainText(options.redirectHost);
|
||||
await expect(page.getByTestId("mcp-server-approval-code")).toHaveText(/^\d{3}-\d{3}$/);
|
||||
|
||||
const closeButton = modal.getByRole("button", { name: "Close", exact: true });
|
||||
await expect(closeButton).not.toBeFocused();
|
||||
await expect(closeButton).toHaveCSS("outline-style", "none");
|
||||
|
||||
await page.getByTestId(`mcp-server-approval-preset-${options.preset}`).click();
|
||||
if (options.screenshotName) {
|
||||
await captureMcpScreenshot(page, options.screenshotName);
|
||||
}
|
||||
await page.getByTestId("mcp-server-approval-approve").click();
|
||||
await expect(modal).toBeHidden();
|
||||
}
|
||||
|
||||
/** Strips `features.mcpServer` from a daemon's `server_info` frame to simulate an older host. */
|
||||
export async function stripMcpServerFeature(page: Page, endpoint: string): Promise<void> {
|
||||
const port = endpoint.split(":").pop();
|
||||
if (!port) {
|
||||
throw new Error(`Unexpected daemon endpoint: ${endpoint}`);
|
||||
}
|
||||
await page.routeWebSocket(wsRoutePatternForPort(port), (browser) => {
|
||||
const server = browser.connectToServer();
|
||||
browser.onMessage((message) => server.send(message));
|
||||
server.onMessage((message) => {
|
||||
if (typeof message !== "string") {
|
||||
browser.send(message);
|
||||
return;
|
||||
}
|
||||
const envelope = JSON.parse(message);
|
||||
if (
|
||||
envelope.message?.type === "status" &&
|
||||
envelope.message.payload?.status === "server_info" &&
|
||||
envelope.message.payload.features
|
||||
) {
|
||||
delete envelope.message.payload.features.mcpServer;
|
||||
}
|
||||
browser.send(JSON.stringify(envelope));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -70,6 +70,7 @@ type HostSection =
|
||||
| "terminals"
|
||||
| "plugins"
|
||||
| "devices"
|
||||
| "mcp-server"
|
||||
| "daemon";
|
||||
|
||||
export async function openSettingsSection(page: Page, section: SettingsSection): Promise<void> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { connectDaemonClient } from "./daemon-client-loader";
|
||||
import { startIsolatedHostDaemon } from "./isolated-host-daemon";
|
||||
import { seedWorkspace } from "./seed-client";
|
||||
import { getE2EDaemonPort } from "./daemon-port";
|
||||
import { getE2EDaemonPort, getE2EMcpRequestInit } from "./daemon-port";
|
||||
import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { daemonWsRoutePattern } from "./daemon-port";
|
||||
@@ -386,7 +386,10 @@ export async function delegateFleetThroughMcp() {
|
||||
.toBe("online");
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
new URL(
|
||||
`http://127.0.0.1:${getE2EDaemonPort()}/_internal/mcp/agents?callerAgentId=${parent.id}`,
|
||||
),
|
||||
{ requestInit: getE2EMcpRequestInit() },
|
||||
),
|
||||
);
|
||||
expect(await call("list_hosts")).toMatchObject({
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
resolveDesktopDivisionLayout,
|
||||
} from "@/window-layout";
|
||||
import { AddHostProvider, AddHostFlowHost } from "@/hosts/add-host";
|
||||
import { McpServerApprovalPrompts } from "@/mcp-server";
|
||||
import { HostRefusalSheetHost } from "@/hosts/host-refusal-sheet";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
@@ -572,6 +573,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<AddProjectFlowHost />
|
||||
<HostChooserModal />
|
||||
<HostConfirmationSheet />
|
||||
<McpServerApprovalPrompts />
|
||||
<PluginExecutionApprovalSheet />
|
||||
<ProviderSettingsHost />
|
||||
<WorkspaceSetupDialog />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useOverlayRegistration, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -768,6 +768,7 @@ export function AdaptiveModalSheet({
|
||||
desktopHeight != null && { height: desktopHeight },
|
||||
desktopMaxWidth != null && { maxWidth: desktopMaxWidth },
|
||||
isWeb && WEB_ENTER_STYLE,
|
||||
isWeb && { outlineWidth: 0 },
|
||||
],
|
||||
[desktopMaxWidth, desktopHeight],
|
||||
);
|
||||
@@ -812,6 +813,24 @@ export function AdaptiveModalSheet({
|
||||
layer: modalLayer,
|
||||
onKeyDown: handleOverlayKeyDown,
|
||||
});
|
||||
const desktopCardRef = useRef<HTMLElement | null>(null);
|
||||
const setDesktopCardRef = useCallback(
|
||||
(node: unknown) => {
|
||||
desktopCardRef.current =
|
||||
isWeb && typeof HTMLElement !== "undefined" && node instanceof HTMLElement ? node : null;
|
||||
setOverlayScope(node);
|
||||
},
|
||||
[setOverlayScope],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!isWeb || isMobile || !visible) return;
|
||||
const card = desktopCardRef.current;
|
||||
if (!card || card.contains(document.activeElement)) return;
|
||||
// Focus the dialog container when no child claims autofocus so opening a sheet does not land
|
||||
// initial focus (and a visible focus ring) on the header close button.
|
||||
card.focus({ preventScroll: true });
|
||||
}, [isMobile, shouldRenderWeb, visible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWeb || isMobile) return;
|
||||
@@ -902,7 +921,7 @@ export function AdaptiveModalSheet({
|
||||
const desktopContent = (
|
||||
<View style={desktopOverlayStyle} testID={testID}>
|
||||
<DismissBackdrop label={t("common.actions.dismiss")} onPress={onClose} />
|
||||
<View ref={setOverlayScope} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
|
||||
<View ref={setDesktopCardRef} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
|
||||
{cardInner}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -10,9 +10,16 @@ interface StatusBadgeProps {
|
||||
leading?: ReactNode;
|
||||
/** `xs` fits beside a line of `sm` text: the same label on tighter padding. */
|
||||
size?: "sm" | "xs";
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
export function StatusBadge({ label, variant = "muted", leading, size = "sm" }: StatusBadgeProps) {
|
||||
export function StatusBadge({
|
||||
label,
|
||||
variant = "muted",
|
||||
leading,
|
||||
size = "sm",
|
||||
testID,
|
||||
}: StatusBadgeProps) {
|
||||
const pillStyle = useMemo(
|
||||
() => [
|
||||
styles.pill,
|
||||
@@ -34,7 +41,7 @@ export function StatusBadge({ label, variant = "muted", leading, size = "sm" }:
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={pillStyle}>
|
||||
<View style={pillStyle} testID={testID}>
|
||||
{leading}
|
||||
<Text style={textStyle}>{label}</Text>
|
||||
</View>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ar: TranslationResources = {
|
||||
@@ -3835,4 +3836,5 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ar,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginGallery } from "./plugin-gallery";
|
||||
|
||||
export const en = {
|
||||
@@ -3957,6 +3958,7 @@ export const en = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.en,
|
||||
} as const;
|
||||
|
||||
type WidenStringLeaves<T> = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const es: TranslationResources = {
|
||||
@@ -3877,4 +3878,5 @@ export const es: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.es,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const fr: TranslationResources = {
|
||||
@@ -3888,4 +3889,5 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.fr,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ja: TranslationResources = {
|
||||
@@ -3838,4 +3839,5 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ja,
|
||||
} as const;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ko: TranslationResources = {
|
||||
@@ -3822,4 +3823,5 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ko,
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ptBR: TranslationResources = {
|
||||
@@ -3857,4 +3858,5 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer["pt-BR"],
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ru: TranslationResources = {
|
||||
@@ -3869,4 +3870,5 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ru,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const zhCN: TranslationResources = {
|
||||
@@ -3754,4 +3755,5 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer["zh-CN"],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
MCP_SERVER_PERMISSION_PRESETS,
|
||||
MCP_SERVER_PERMISSION_PRESET_ORDER,
|
||||
type McpServerAccess,
|
||||
type McpServerApproval,
|
||||
type McpServerConfigureAuthPatch,
|
||||
type McpServerCredential,
|
||||
type McpServerStatus,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
SettingsAction,
|
||||
SettingsCard,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
SettingsSelect,
|
||||
SettingsSwitch,
|
||||
} from "@/components/settings";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { formatTimeAgo } from "@/utils/time";
|
||||
import { ApprovalCodeSheet, TokenSheet } from "./grant-sheets";
|
||||
import type { McpServerLoad, McpServerModel } from "./model";
|
||||
import {
|
||||
credentialAccess,
|
||||
defaultAccessSelection,
|
||||
type DefaultAccessSelection,
|
||||
} from "./presentation";
|
||||
|
||||
function defaultAccessHint(
|
||||
selection: DefaultAccessSelection,
|
||||
status: McpServerStatus,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (selection === "none") return t("mcpServer.auth.defaultAccessNoneHint");
|
||||
if (selection === "custom") return status.auth.defaultPermissions.join(", ");
|
||||
return t(`mcpServer.presets.${selection}Hint`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication toggles (OAuth 2.1, Bearer tokens), unauthenticated default access, pending
|
||||
* OAuth sign-ins, token/approval code creation, and connected clients.
|
||||
*/
|
||||
export function AccessSection({
|
||||
model,
|
||||
status,
|
||||
access,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
access: McpServerLoad<McpServerAccess>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [creating, setCreating] = useState<"token" | "code" | null>(null);
|
||||
const createToken = useCallback(() => setCreating("token"), []);
|
||||
const createCode = useCallback(() => setCreating("code"), []);
|
||||
const stopCreating = useCallback(() => setCreating(null), []);
|
||||
const authOff = !status.auth.oauth && !status.auth.bearerTokens;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title={t("mcpServer.auth.section")}>
|
||||
<AuthTogglesCard model={model} status={status} />
|
||||
{authOff ? <UnauthenticatedAccess model={model} status={status} /> : null}
|
||||
<AccessGrants
|
||||
model={model}
|
||||
status={status}
|
||||
access={access}
|
||||
onCreateToken={createToken}
|
||||
onCreateCode={createCode}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<TokenSheet model={model} visible={creating === "token"} onClose={stopCreating} />
|
||||
<ApprovalCodeSheet model={model} visible={creating === "code"} onClose={stopCreating} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthTogglesCard({ model, status }: { model: McpServerModel; status: McpServerStatus }) {
|
||||
const { t } = useTranslation();
|
||||
const configureAuth = useMutation({
|
||||
mutationFn: (auth: McpServerConfigureAuthPatch) => model.configure({ auth }),
|
||||
});
|
||||
const { mutate: mutateAuth } = configureAuth;
|
||||
const setOAuth = useCallback((oauth: boolean) => mutateAuth({ oauth }), [mutateAuth]);
|
||||
const setBearerTokens = useCallback(
|
||||
(bearerTokens: boolean) => mutateAuth({ bearerTokens }),
|
||||
[mutateAuth],
|
||||
);
|
||||
const oauthEnabled =
|
||||
configureAuth.isPending && configureAuth.variables?.oauth !== undefined
|
||||
? configureAuth.variables.oauth
|
||||
: status.auth.oauth;
|
||||
const bearerEnabled =
|
||||
configureAuth.isPending && configureAuth.variables?.bearerTokens !== undefined
|
||||
? configureAuth.variables.bearerTokens
|
||||
: status.auth.bearerTokens;
|
||||
const authError = configureAuth.error
|
||||
? t("mcpServer.server.saveFailed", { message: configureAuth.error.message })
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<SettingsCard>
|
||||
<SettingsSwitch
|
||||
label={t("mcpServer.auth.oauth")}
|
||||
hint={t("mcpServer.auth.oauthHint")}
|
||||
value={oauthEnabled}
|
||||
onValueChange={configureAuth.isPending ? undefined : setOAuth}
|
||||
error={configureAuth.variables?.oauth !== undefined ? authError : undefined}
|
||||
testID="mcp-server-auth-oauth"
|
||||
/>
|
||||
<SettingsSwitch
|
||||
label={t("mcpServer.auth.bearerTokens")}
|
||||
hint={t("mcpServer.auth.bearerTokensHint")}
|
||||
value={bearerEnabled}
|
||||
onValueChange={configureAuth.isPending ? undefined : setBearerTokens}
|
||||
error={configureAuth.variables?.bearerTokens !== undefined ? authError : undefined}
|
||||
testID="mcp-server-auth-bearer"
|
||||
/>
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
function UnauthenticatedAccess({
|
||||
model,
|
||||
status,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
title={t("mcpServer.auth.noAuthTitle")}
|
||||
description={t("mcpServer.auth.noAuthDescription")}
|
||||
testID="mcp-server-no-auth-warning"
|
||||
/>
|
||||
<SettingsCard>
|
||||
<DefaultAccessRow model={model} status={status} />
|
||||
</SettingsCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AccessGrants({
|
||||
model,
|
||||
status,
|
||||
access,
|
||||
onCreateToken,
|
||||
onCreateCode,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
access: McpServerLoad<McpServerAccess>;
|
||||
onCreateToken(): void;
|
||||
onCreateCode(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (access.kind === "error") {
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.access.loadFailed", { message: access.message })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (access.kind === "loading") return null;
|
||||
|
||||
const { approvals, credentials } = access.value;
|
||||
const showActions = status.auth.oauth || status.auth.bearerTokens;
|
||||
const showCredentials = showActions || credentials.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
{status.auth.oauth && approvals.length > 0 ? (
|
||||
<SettingsCard>
|
||||
{approvals.map((approval) => (
|
||||
<PendingApprovalRow key={approval.id} model={model} approval={approval} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
{showActions ? (
|
||||
<SettingsCard>
|
||||
{status.auth.bearerTokens ? (
|
||||
<SettingsAction
|
||||
label={t("mcpServer.access.createToken")}
|
||||
hint={t("mcpServer.access.createTokenHint")}
|
||||
actionLabel={t("mcpServer.token.create")}
|
||||
onPress={onCreateToken}
|
||||
testID="mcp-server-create-token"
|
||||
/>
|
||||
) : null}
|
||||
{status.auth.oauth ? (
|
||||
<SettingsAction
|
||||
label={t("mcpServer.access.createCode")}
|
||||
hint={t("mcpServer.access.createCodeHint")}
|
||||
actionLabel={t("mcpServer.code.create")}
|
||||
onPress={onCreateCode}
|
||||
testID="mcp-server-create-code"
|
||||
/>
|
||||
) : null}
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
{showCredentials ? <CredentialsCard model={model} credentials={credentials} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CredentialsCard({
|
||||
model,
|
||||
credentials,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
credentials: readonly McpServerCredential[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SettingsCard testID="mcp-server-credentials">
|
||||
{credentials.length === 0 ? (
|
||||
<View style={settingsStyles.row}>
|
||||
<Text style={styles.empty}>{t("mcpServer.access.empty")}</Text>
|
||||
</View>
|
||||
) : (
|
||||
credentials.map((credential) => (
|
||||
<CredentialRow key={credential.id} model={model} credential={credential} />
|
||||
))
|
||||
)}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
function DefaultAccessRow({ model, status }: { model: McpServerModel; status: McpServerStatus }) {
|
||||
const { t } = useTranslation();
|
||||
const selection = defaultAccessSelection(status.auth.defaultPermissions);
|
||||
const choose = useMutation({
|
||||
mutationFn: (value: DefaultAccessSelection) => {
|
||||
if (value === "custom") return Promise.resolve();
|
||||
const defaultPermissions = value === "none" ? [] : [...MCP_SERVER_PERMISSION_PRESETS[value]];
|
||||
return model.configure({ auth: { defaultPermissions } });
|
||||
},
|
||||
});
|
||||
const activeValue = choose.isPending && choose.variables ? choose.variables : selection;
|
||||
const options = useMemo(() => {
|
||||
const list: { value: DefaultAccessSelection; label: string }[] = [
|
||||
{ value: "none", label: t("mcpServer.auth.defaultAccessNone") },
|
||||
...MCP_SERVER_PERMISSION_PRESET_ORDER.map((preset) => ({
|
||||
value: preset,
|
||||
label: t(`mcpServer.presets.${preset}`),
|
||||
})),
|
||||
];
|
||||
if (selection === "custom") {
|
||||
list.push({ value: "custom", label: t("mcpServer.auth.defaultAccessCustom") });
|
||||
}
|
||||
return list;
|
||||
}, [selection, t]);
|
||||
|
||||
return (
|
||||
<SettingsSelect
|
||||
label={t("mcpServer.auth.defaultAccess")}
|
||||
hint={defaultAccessHint(activeValue, status, t)}
|
||||
value={activeValue}
|
||||
options={options}
|
||||
onValueChange={choose.mutate}
|
||||
disabled={choose.isPending}
|
||||
error={
|
||||
choose.error
|
||||
? t("mcpServer.server.saveFailed", { message: choose.error.message })
|
||||
: undefined
|
||||
}
|
||||
testID="mcp-server-default-access"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PendingApprovalRow({
|
||||
model,
|
||||
approval,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
approval: McpServerApproval;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const review = useCallback(() => model.reviewApproval(approval.id), [model, approval.id]);
|
||||
return (
|
||||
<SettingsAction
|
||||
label={approval.clientName}
|
||||
hint={`${approval.redirectHost} · ${approval.verificationCode}`}
|
||||
actionLabel={t("mcpServer.access.review")}
|
||||
onPress={review}
|
||||
testID={`mcp-server-pending-${approval.id}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function describeCredential(credential: McpServerCredential, t: TFunction): string {
|
||||
const access = credentialAccess(credential);
|
||||
const parts = [
|
||||
t(credential.authKind === "oauth" ? "mcpServer.access.signedIn" : "mcpServer.access.token"),
|
||||
access.kind === "preset" ? t(`mcpServer.presets.${access.preset}`) : access.permissions,
|
||||
credential.lastUsedAt
|
||||
? t("mcpServer.access.lastUsed", { time: formatTimeAgo(new Date(credential.lastUsedAt)) })
|
||||
: t("mcpServer.access.neverUsed"),
|
||||
];
|
||||
if (credential.redirectHost) parts.splice(1, 0, credential.redirectHost);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
function CredentialRow({
|
||||
model,
|
||||
credential,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
credential: McpServerCredential;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const revoke = useMutation({ mutationFn: () => model.revoke(credential.id) });
|
||||
const { mutate } = revoke;
|
||||
const confirmRevoke = useCallback(async () => {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("mcpServer.access.revokeTitle", { label: credential.label }),
|
||||
message: t("mcpServer.access.revokeMessage", { label: credential.label }),
|
||||
confirmLabel: t("mcpServer.access.revoke"),
|
||||
cancelLabel: t("common.actions.cancel"),
|
||||
destructive: true,
|
||||
});
|
||||
if (confirmed) mutate();
|
||||
}, [credential.label, mutate, t]);
|
||||
const onRevoke = useCallback(() => void confirmRevoke(), [confirmRevoke]);
|
||||
return (
|
||||
<SettingsRow
|
||||
label={credential.label}
|
||||
hint={describeCredential(credential, t)}
|
||||
error={
|
||||
revoke.error
|
||||
? t("mcpServer.access.revokeFailed", { message: revoke.error.message })
|
||||
: undefined
|
||||
}
|
||||
testID={`mcp-server-credential-${credential.id}`}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onRevoke}
|
||||
loading={revoke.isPending}
|
||||
disabled={revoke.isPending}
|
||||
accessibilityLabel={`${t("mcpServer.access.revoke")} ${credential.label}`}
|
||||
testID={`mcp-server-revoke-${credential.id}`}
|
||||
>
|
||||
{t("mcpServer.access.revoke")}
|
||||
</Button>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
empty: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
}));
|
||||
@@ -0,0 +1,192 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
MCP_SERVER_PERMISSION_PRESETS,
|
||||
type McpServerApproval,
|
||||
type McpServerPermissionPreset,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { mcpServerModelFor, useMcpServer } from "./host";
|
||||
import type { McpServerModel } from "./model";
|
||||
import { DEFAULT_PRESET, PresetPicker } from "./parts";
|
||||
|
||||
type Decision = { kind: "approve"; preset: McpServerPermissionPreset } | { kind: "deny" };
|
||||
|
||||
/**
|
||||
* Asks the owner about an app's sign-in: which app, where its browser returns, the code the
|
||||
* sign-in page shows, and how much access to grant. Closing it decides nothing; the sign-in stays
|
||||
* listed in settings until it expires.
|
||||
*/
|
||||
export function ApprovalSheet({
|
||||
model,
|
||||
approval,
|
||||
hostLabel,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
approval: McpServerApproval;
|
||||
hostLabel: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [preset, setPreset] = useState<McpServerPermissionPreset>(DEFAULT_PRESET);
|
||||
const decide = useMutation({
|
||||
mutationFn: (decision: Decision) =>
|
||||
decision.kind === "approve"
|
||||
? model.approve(approval.id, MCP_SERVER_PERMISSION_PRESETS[decision.preset])
|
||||
: model.deny(approval.id),
|
||||
});
|
||||
const { mutate } = decide;
|
||||
const approve = useCallback(() => mutate({ kind: "approve", preset }), [mutate, preset]);
|
||||
const deny = useCallback(() => mutate({ kind: "deny" }), [mutate]);
|
||||
const later = useCallback(() => model.dismissPrompt(approval.id), [model, approval.id]);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("mcpServer.approval.title") }), [t]);
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible
|
||||
onClose={later}
|
||||
desktopMaxWidth={440}
|
||||
testID="mcp-server-approval"
|
||||
>
|
||||
<View style={styles.body}>
|
||||
<Text style={styles.description}>
|
||||
{t("mcpServer.approval.description", { app: approval.clientName, host: hostLabel })}
|
||||
</Text>
|
||||
<View style={settingsStyles.card}>
|
||||
<Detail label={t("mcpServer.approval.app")} value={approval.clientName} />
|
||||
<Detail
|
||||
label={t("mcpServer.approval.returnsTo")}
|
||||
value={approval.redirectHost}
|
||||
testID="mcp-server-approval-redirect"
|
||||
bordered
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.code}>
|
||||
<Text style={styles.codeValue} testID="mcp-server-approval-code">
|
||||
{approval.verificationCode}
|
||||
</Text>
|
||||
<Text style={styles.codeHint}>{t("mcpServer.approval.codeHint")}</Text>
|
||||
</View>
|
||||
<PresetPicker value={preset} onChange={setPreset} testID="mcp-server-approval-preset" />
|
||||
{decide.error ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.approval.failed", { message: decide.error.message })}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
style={styles.action}
|
||||
onPress={deny}
|
||||
disabled={decide.isPending}
|
||||
testID="mcp-server-approval-deny"
|
||||
>
|
||||
{t("mcpServer.approval.deny")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
style={styles.action}
|
||||
onPress={approve}
|
||||
loading={decide.isPending && decide.variables?.kind === "approve"}
|
||||
disabled={decide.isPending}
|
||||
testID="mcp-server-approval-approve"
|
||||
>
|
||||
{t("mcpServer.approval.approve")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function Detail({
|
||||
label,
|
||||
value,
|
||||
bordered = false,
|
||||
testID,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
bordered?: boolean;
|
||||
testID?: string;
|
||||
}) {
|
||||
return (
|
||||
<View style={[styles.detail, bordered && settingsStyles.rowBorder]}>
|
||||
<Text style={styles.detailLabel}>{label}</Text>
|
||||
<Text style={styles.detailValue} selectable numberOfLines={2} testID={testID}>
|
||||
{value}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Prompts for one host's waiting sign-ins while this device is connected to it. */
|
||||
function HostApprovalPrompt({ serverId, hostLabel }: { serverId: string; hostLabel: string }) {
|
||||
const model = mcpServerModelFor(serverId);
|
||||
const state = useMcpServer(model);
|
||||
if (state.host !== "online" || !state.prompt) return null;
|
||||
// A new key per sign-in starts each prompt with the default access and no stale error.
|
||||
return (
|
||||
<ApprovalSheet
|
||||
key={state.prompt.id}
|
||||
model={model}
|
||||
approval={state.prompt}
|
||||
hostLabel={hostLabel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Mount once at the app root: any connected device can approve an app's sign-in. */
|
||||
export function McpServerApprovalPrompts() {
|
||||
const hosts = useHosts();
|
||||
return (
|
||||
<>
|
||||
{hosts.map((host) => (
|
||||
<HostApprovalPrompt key={host.serverId} serverId={host.serverId} hostLabel={host.label} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: { gap: theme.spacing[4] },
|
||||
description: { color: theme.colors.foreground, fontSize: theme.fontSize.base },
|
||||
detail: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[3],
|
||||
},
|
||||
detailLabel: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
detailValue: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
flexShrink: 1,
|
||||
textAlign: "right",
|
||||
},
|
||||
code: { alignItems: "center", gap: theme.spacing[1] },
|
||||
codeValue: {
|
||||
color: theme.colors.foreground,
|
||||
fontFamily: theme.fontFamily.mono,
|
||||
fontSize: theme.fontSize["2xl"],
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
letterSpacing: 2,
|
||||
},
|
||||
codeHint: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
textAlign: "center",
|
||||
},
|
||||
actions: { flexDirection: "row", gap: theme.spacing[3] },
|
||||
action: { flex: 1 },
|
||||
}));
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { McpServerStatus } from "@getpaseo/protocol/messages";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { SettingsCard, SettingsDetailRow } from "@/components/settings";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import {
|
||||
CONNECT_APPS,
|
||||
connectUrl,
|
||||
resolveGuideMode,
|
||||
type ConnectApp,
|
||||
type ConnectAppId,
|
||||
type ConnectGuideMode,
|
||||
} from "./connect-apps";
|
||||
import { TokenCreator } from "./grant-sheets";
|
||||
import type { McpServerModel } from "./model";
|
||||
import { CopyBlock, Steps } from "./parts";
|
||||
|
||||
function useAppName(): (app: ConnectApp) => string {
|
||||
const { t } = useTranslation();
|
||||
return useCallback((app: ConnectApp) => app.name ?? t("mcpServer.connect.other"), [t]);
|
||||
}
|
||||
|
||||
function guideStepsKey(
|
||||
mode: Exclude<ConnectGuideMode, "oauth-required">,
|
||||
appId: ConnectAppId,
|
||||
): string {
|
||||
if (mode === "token") return `mcpServer.connect.tokenSteps.${appId}`;
|
||||
if (mode === "none") return `mcpServer.connect.noAuthSteps.${appId}`;
|
||||
return `mcpServer.connect.steps.${appId}`;
|
||||
}
|
||||
|
||||
/** Setup guides for adding Paseo to an MCP client, adapted to the active auth mode. */
|
||||
export function ConnectAppSheet({
|
||||
model,
|
||||
status,
|
||||
visible,
|
||||
onClose,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
visible: boolean;
|
||||
onClose(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appName = useAppName();
|
||||
const [chosen, setChosen] = useState<ConnectAppId | null>(null);
|
||||
const app = CONNECT_APPS.find((entry) => entry.id === chosen) ?? null;
|
||||
const back = useCallback(() => setChosen(null), []);
|
||||
const close = useCallback(() => {
|
||||
setChosen(null);
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
app
|
||||
? {
|
||||
title: appName(app),
|
||||
back: { onPress: back, accessibilityLabel: t("common.actions.back") },
|
||||
}
|
||||
: { title: t("mcpServer.connect.title") },
|
||||
[app, appName, back, t],
|
||||
);
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={close}
|
||||
desktopMaxWidth={520}
|
||||
testID="mcp-server-connect"
|
||||
>
|
||||
{app ? (
|
||||
<ConnectAppSteps key={app.id} model={model} status={status} app={app} />
|
||||
) : (
|
||||
<SettingsCard>
|
||||
{CONNECT_APPS.map((entry) => (
|
||||
<AppRow key={entry.id} app={entry} name={appName(entry)} onChoose={setChosen} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
)}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function AppRow({
|
||||
app,
|
||||
name,
|
||||
onChoose,
|
||||
}: {
|
||||
app: ConnectApp;
|
||||
name: string;
|
||||
onChoose(id: ConnectAppId): void;
|
||||
}) {
|
||||
const choose = useCallback(() => onChoose(app.id), [app.id, onChoose]);
|
||||
return (
|
||||
<SettingsDetailRow label={name} onPress={choose} testID={`mcp-server-connect-${app.id}`} />
|
||||
);
|
||||
}
|
||||
|
||||
export function ConnectAppSteps({
|
||||
model,
|
||||
status,
|
||||
app,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
app: ConnectApp;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const name = useAppName()(app);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const url = connectUrl(status, app);
|
||||
if (!url) {
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
title={t("mcpServer.connect.needsPublic", { app: name })}
|
||||
testID="mcp-server-connect-needs-public"
|
||||
/>
|
||||
);
|
||||
}
|
||||
const mode = resolveGuideMode(status.auth, app);
|
||||
if (mode === "oauth-required") {
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
title={t("mcpServer.connect.oauthRequired", { app: name })}
|
||||
testID="mcp-server-connect-oauth-required"
|
||||
/>
|
||||
);
|
||||
}
|
||||
const showTokenCreator =
|
||||
mode === "token" || (app.id === "other" && mode === "oauth" && status.auth.bearerTokens);
|
||||
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
{mode === "none" ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
title={t("mcpServer.connect.noAuthNotice")}
|
||||
testID="mcp-server-connect-no-auth"
|
||||
/>
|
||||
) : null}
|
||||
<Steps text={t(guideStepsKey(mode, app.id))} />
|
||||
<CopyBlock label={t("mcpServer.connect.url")} value={url} testID="mcp-server-connect-url" />
|
||||
{app.snippet ? (
|
||||
<CopyBlock
|
||||
label={t("mcpServer.connect.config")}
|
||||
value={app.snippet({ url, token, mode })}
|
||||
testID="mcp-server-connect-snippet"
|
||||
/>
|
||||
) : null}
|
||||
{showTokenCreator ? (
|
||||
<TokenCreator model={model} defaultName={name} onCreated={setToken} />
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: { gap: theme.spacing[4] },
|
||||
}));
|
||||
@@ -0,0 +1,151 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CONNECT_APPS, connectUrl, resolveGuideMode, type ConnectAppId } from "./connect-apps";
|
||||
import { credentialAccess, mcpUrlKind, parsePort } from "./presentation";
|
||||
import { fakeCredential, fakeStatus, fakeTunnelStatus } from "./test-fixtures";
|
||||
|
||||
function app(id: ConnectAppId) {
|
||||
const found = CONNECT_APPS.find((entry) => entry.id === id);
|
||||
if (!found) throw new Error(`No app ${id}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
describe("connectUrl", () => {
|
||||
it("gives a cloud app nothing until a tunnel or public URL is up", () => {
|
||||
expect(connectUrl(fakeStatus(), app("claude"))).toBeNull();
|
||||
expect(connectUrl(fakeStatus(), app("poke"))).toBeNull();
|
||||
expect(connectUrl(fakeStatus(), app("grok"))).toBeNull();
|
||||
expect(
|
||||
connectUrl(fakeTunnelStatus("https://abc.tunnel.example", "ephemeral"), app("poke")),
|
||||
).toBe("https://abc.tunnel.example/mcp");
|
||||
});
|
||||
|
||||
it("gives a local app the listener unless the owner set a public URL", () => {
|
||||
const tunneled = fakeTunnelStatus("https://abc.tunnel.example", "ephemeral");
|
||||
expect(connectUrl(tunneled, app("claude-code"))).toBe("http://127.0.0.1:6770/mcp");
|
||||
expect(connectUrl(tunneled, app("openclaw"))).toBe("http://127.0.0.1:6770/mcp");
|
||||
const withPublic = fakeStatus({
|
||||
publicUrl: "https://mcp.example.com",
|
||||
mcpUrls: ["https://mcp.example.com/mcp", "http://127.0.0.1:6770/mcp"],
|
||||
});
|
||||
expect(connectUrl(withPublic, app("cursor"))).toBe("https://mcp.example.com/mcp");
|
||||
});
|
||||
});
|
||||
|
||||
describe("app setup modes and snippets", () => {
|
||||
const url = "http://127.0.0.1:6770/mcp";
|
||||
|
||||
it("uses OAuth 2.1 by default for Claude, ChatGPT, Poke, Grok Bot, OpenClaw, Claude Code, and Cursor", () => {
|
||||
const oauthStatus = fakeStatus({
|
||||
auth: { oauth: true, bearerTokens: true, defaultPermissions: [] },
|
||||
});
|
||||
for (const id of [
|
||||
"claude",
|
||||
"chatgpt",
|
||||
"poke",
|
||||
"grok",
|
||||
"openclaw",
|
||||
"claude-code",
|
||||
"cursor",
|
||||
] as const) {
|
||||
expect(resolveGuideMode(oauthStatus.auth, app(id))).toBe("oauth");
|
||||
}
|
||||
expect(resolveGuideMode(oauthStatus.auth, app("other"))).toBe("oauth");
|
||||
});
|
||||
|
||||
it("switches supported apps to Bearer token mode when OAuth is off and Bearer tokens are on", () => {
|
||||
const bearerOnly = { oauth: false, bearerTokens: true, defaultPermissions: [] };
|
||||
expect(resolveGuideMode(bearerOnly, app("claude"))).toBe("oauth-required");
|
||||
expect(resolveGuideMode(bearerOnly, app("chatgpt"))).toBe("oauth-required");
|
||||
expect(resolveGuideMode(bearerOnly, app("poke"))).toBe("token");
|
||||
expect(resolveGuideMode(bearerOnly, app("grok"))).toBe("token");
|
||||
expect(resolveGuideMode(bearerOnly, app("openclaw"))).toBe("token");
|
||||
expect(resolveGuideMode(bearerOnly, app("claude-code"))).toBe("token");
|
||||
expect(resolveGuideMode(bearerOnly, app("cursor"))).toBe("token");
|
||||
expect(resolveGuideMode(bearerOnly, app("other"))).toBe("token");
|
||||
});
|
||||
|
||||
it("uses unauthenticated mode when both OAuth and Bearer tokens are off", () => {
|
||||
const noAuth = {
|
||||
oauth: false,
|
||||
bearerTokens: false,
|
||||
defaultPermissions: ["daemon.read" as const],
|
||||
};
|
||||
expect(resolveGuideMode(noAuth, app("claude"))).toBe("none");
|
||||
expect(resolveGuideMode(noAuth, app("openclaw"))).toBe("none");
|
||||
});
|
||||
|
||||
it("formats OpenClaw CLI setup for OAuth, Bearer token, and unauthenticated modes", () => {
|
||||
const openclaw = app("openclaw");
|
||||
expect(openclaw.snippet?.({ url, token: null, mode: "oauth" })).toBe(
|
||||
`openclaw mcp set paseo '{"url":"${url}","transport":"streamable-http","auth":"oauth"}'`,
|
||||
);
|
||||
expect(openclaw.snippet?.({ url, token: "pmcp_x", mode: "token" })).toBe(
|
||||
`openclaw mcp set paseo '{"url":"${url}","transport":"streamable-http","headers":{"Authorization":"Bearer pmcp_x"}}'`,
|
||||
);
|
||||
expect(openclaw.snippet?.({ url, token: null, mode: "none" })).toBe(
|
||||
`openclaw mcp set paseo '{"url":"${url}","transport":"streamable-http"}'`,
|
||||
);
|
||||
});
|
||||
|
||||
it("adds Paseo to Claude Code with OAuth, or with a token header", () => {
|
||||
const claudeCode = app("claude-code");
|
||||
expect(claudeCode.snippet?.({ url, token: null, mode: "oauth" })).toBe(
|
||||
"claude mcp add --transport http paseo http://127.0.0.1:6770/mcp",
|
||||
);
|
||||
expect(claudeCode.snippet?.({ url, token: "pmcp_x", mode: "token" })).toBe(
|
||||
'claude mcp add --transport http paseo http://127.0.0.1:6770/mcp --header "Authorization: Bearer pmcp_x"',
|
||||
);
|
||||
});
|
||||
|
||||
it("writes an mcpServers entry for Cursor", () => {
|
||||
expect(JSON.parse(app("cursor").snippet?.({ url, token: null, mode: "oauth" }) ?? "")).toEqual({
|
||||
mcpServers: { paseo: { url } },
|
||||
});
|
||||
expect(
|
||||
JSON.parse(app("cursor").snippet?.({ url, token: "pmcp_x", mode: "token" }) ?? ""),
|
||||
).toEqual({
|
||||
mcpServers: { paseo: { url, headers: { Authorization: "Bearer pmcp_x" } } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("settings presentation", () => {
|
||||
it("labels each MCP URL by the address it uses", () => {
|
||||
const status = fakeStatus({
|
||||
publicUrl: "https://mcp.example.com",
|
||||
tunnel: {
|
||||
providerId: "fake",
|
||||
state: "ready",
|
||||
url: "https://abc.tunnel.example",
|
||||
stability: "stable",
|
||||
detail: null,
|
||||
error: null,
|
||||
},
|
||||
mcpUrls: [
|
||||
"https://mcp.example.com/mcp",
|
||||
"https://abc.tunnel.example/mcp",
|
||||
"http://192.168.1.20:6770/mcp",
|
||||
"http://127.0.0.1:6770/mcp",
|
||||
],
|
||||
});
|
||||
expect(status.mcpUrls.map((url) => mcpUrlKind(status, url))).toEqual([
|
||||
"public",
|
||||
"tunnel",
|
||||
"network",
|
||||
"local",
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts only real TCP ports", () => {
|
||||
expect(parsePort(" 6770 ")).toBe(6770);
|
||||
for (const text of ["0", "65536", "-1", "67.7", "", "abc"]) expect(parsePort(text)).toBeNull();
|
||||
});
|
||||
|
||||
it("names a credential's access by its preset when it matches one", () => {
|
||||
expect(credentialAccess(fakeCredential())).toEqual({ kind: "preset", preset: "read" });
|
||||
expect(credentialAccess(fakeCredential({ permissions: ["workspace.read"] }))).toEqual({
|
||||
kind: "custom",
|
||||
permissions: "workspace.read",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { McpServerAuthSettings, McpServerStatus } from "@getpaseo/protocol/messages";
|
||||
|
||||
export type ConnectAppId =
|
||||
| "claude"
|
||||
| "chatgpt"
|
||||
| "poke"
|
||||
| "grok"
|
||||
| "openclaw"
|
||||
| "claude-code"
|
||||
| "cursor"
|
||||
| "other";
|
||||
|
||||
export type ConnectGuideMode = "oauth" | "token" | "none" | "oauth-required";
|
||||
|
||||
/**
|
||||
* An app the Setup guides sheet has steps for. Apps that run in someone else's cloud reach Paseo
|
||||
* from the internet, so they need the tunnel or public URL. Apps on the owner's computer can use
|
||||
* the listener's own address.
|
||||
*/
|
||||
export interface ConnectApp {
|
||||
id: ConnectAppId;
|
||||
/** A product name, the same in every language. Null for "Other", which is translated. */
|
||||
name: string | null;
|
||||
reach: "internet" | "local";
|
||||
/** Whether the client also supports a static Bearer token when OAuth is turned off. */
|
||||
supportsToken: boolean;
|
||||
/** Config or command with the URL (and optional token) filled in, when configured via text. */
|
||||
snippet?(input: { url: string; token: string | null; mode: ConnectGuideMode }): string;
|
||||
}
|
||||
|
||||
const SERVER_NAME = "paseo";
|
||||
|
||||
function bearer(token: string): string {
|
||||
return `Authorization: Bearer ${token}`;
|
||||
}
|
||||
|
||||
/** The `mcpServers` config file shape several MCP apps read. */
|
||||
function mcpServersJson({ url, token }: { url: string; token: string | null }): string {
|
||||
const server = token ? { url, headers: { Authorization: `Bearer ${token}` } } : { url };
|
||||
return JSON.stringify({ mcpServers: { [SERVER_NAME]: server } }, null, 2);
|
||||
}
|
||||
|
||||
function openClawCommand({
|
||||
url,
|
||||
token,
|
||||
mode,
|
||||
}: {
|
||||
url: string;
|
||||
token: string | null;
|
||||
mode: ConnectGuideMode;
|
||||
}): string {
|
||||
const entry: Record<string, unknown> = {
|
||||
url,
|
||||
transport: "streamable-http",
|
||||
};
|
||||
if (mode === "oauth") {
|
||||
entry.auth = "oauth";
|
||||
} else if (token) {
|
||||
entry.headers = { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
return `openclaw mcp set ${SERVER_NAME} '${JSON.stringify(entry)}'`;
|
||||
}
|
||||
|
||||
export const CONNECT_APPS: readonly ConnectApp[] = [
|
||||
{ id: "claude", name: "Claude", reach: "internet", supportsToken: false },
|
||||
{ id: "chatgpt", name: "ChatGPT", reach: "internet", supportsToken: false },
|
||||
{ id: "poke", name: "Poke", reach: "internet", supportsToken: true },
|
||||
{ id: "grok", name: "Grok Bot", reach: "internet", supportsToken: true },
|
||||
{
|
||||
id: "openclaw",
|
||||
name: "OpenClaw",
|
||||
reach: "local",
|
||||
supportsToken: true,
|
||||
snippet: openClawCommand,
|
||||
},
|
||||
{
|
||||
id: "claude-code",
|
||||
name: "Claude Code",
|
||||
reach: "local",
|
||||
supportsToken: true,
|
||||
snippet: ({ url, token }) =>
|
||||
token
|
||||
? `claude mcp add --transport http ${SERVER_NAME} ${url} --header "${bearer(token)}"`
|
||||
: `claude mcp add --transport http ${SERVER_NAME} ${url}`,
|
||||
},
|
||||
{
|
||||
id: "cursor",
|
||||
name: "Cursor",
|
||||
reach: "local",
|
||||
supportsToken: true,
|
||||
snippet: mcpServersJson,
|
||||
},
|
||||
{
|
||||
id: "other",
|
||||
name: null,
|
||||
reach: "local",
|
||||
supportsToken: true,
|
||||
snippet: ({ url, token }) => (token ? `${url}\n${bearer(token)}` : url),
|
||||
},
|
||||
];
|
||||
|
||||
/** Picks which guide mode matches the server's active authentication toggles. */
|
||||
export function resolveGuideMode(auth: McpServerAuthSettings, app: ConnectApp): ConnectGuideMode {
|
||||
if (!auth.oauth && !auth.bearerTokens) return "none";
|
||||
if (auth.oauth) return "oauth";
|
||||
return app.supportsToken ? "token" : "oauth-required";
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL to give an app. Internet apps need an address outside this computer: the public URL or
|
||||
* the tunnel. Local apps prefer the owner's own public URL, which does not change, and otherwise
|
||||
* use the listener, which works without a tunnel. Null while no suitable URL is up.
|
||||
*/
|
||||
export function connectUrl(status: McpServerStatus, app: ConnectApp): string | null {
|
||||
const listenerUrl = status.listener.url;
|
||||
if (app.reach === "internet") {
|
||||
return status.mcpUrls.find((url) => url !== listenerUrl && url.startsWith("https://")) ?? null;
|
||||
}
|
||||
if (status.publicUrl) return status.mcpUrls[0] ?? listenerUrl;
|
||||
return listenerUrl ?? status.mcpUrls[0] ?? null;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
MCP_SERVER_PERMISSION_PRESETS,
|
||||
type McpServerPermissionPreset,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import type { McpServerModel } from "./model";
|
||||
import { CopyBlock, DEFAULT_PRESET, PresetPicker } from "./parts";
|
||||
|
||||
/**
|
||||
* Creates a static Bearer token. The token shows once; after that only its name and access are
|
||||
* listed.
|
||||
*/
|
||||
export function TokenCreator({
|
||||
model,
|
||||
defaultName,
|
||||
onCreated,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
defaultName: string;
|
||||
onCreated?(token: string): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [name, setName] = useState(defaultName);
|
||||
const [preset, setPreset] = useState<McpServerPermissionPreset>(DEFAULT_PRESET);
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
model.createToken({
|
||||
label: name.trim() || defaultName,
|
||||
permissions: MCP_SERVER_PERMISSION_PRESETS[preset],
|
||||
}),
|
||||
onSuccess: ({ token }) => onCreated?.(token),
|
||||
});
|
||||
const { mutate } = create;
|
||||
const submit = useCallback(() => mutate(), [mutate]);
|
||||
|
||||
if (create.data) {
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<CopyBlock
|
||||
label={create.data.credential.label}
|
||||
value={create.data.token}
|
||||
testID="mcp-server-token-value"
|
||||
/>
|
||||
<InlineAlert size="sm" variant="warning" title={t("mcpServer.token.copyNow")} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<Field label={t("mcpServer.token.name")}>
|
||||
<FormTextInput
|
||||
initialValue={defaultName}
|
||||
onChangeText={setName}
|
||||
placeholder={t("mcpServer.token.namePlaceholder")}
|
||||
accessibilityLabel={t("mcpServer.token.name")}
|
||||
testID="mcp-server-token-name"
|
||||
/>
|
||||
</Field>
|
||||
<PresetPicker value={preset} onChange={setPreset} testID="mcp-server-token-preset" />
|
||||
{create.error ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.token.failed", { message: create.error.message })}
|
||||
/>
|
||||
) : null}
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={submit}
|
||||
loading={create.isPending}
|
||||
disabled={create.isPending}
|
||||
testID="mcp-server-token-create"
|
||||
>
|
||||
{t("mcpServer.token.create")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function TokenSheet({
|
||||
model,
|
||||
visible,
|
||||
onClose,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
visible: boolean;
|
||||
onClose(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("mcpServer.token.title") }), [t]);
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
desktopMaxWidth={480}
|
||||
testID="mcp-server-token-sheet"
|
||||
>
|
||||
{visible ? (
|
||||
<TokenCreator model={model} defaultName={t("mcpServer.token.namePlaceholder")} />
|
||||
) : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
/** Creates a one-time code that approves a sign-in from its browser page. */
|
||||
export function ApprovalCodeSheet({
|
||||
model,
|
||||
visible,
|
||||
onClose,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
visible: boolean;
|
||||
onClose(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("mcpServer.code.title") }), [t]);
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
desktopMaxWidth={440}
|
||||
testID="mcp-server-code-sheet"
|
||||
>
|
||||
{visible ? <ApprovalCodeCreator model={model} /> : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function ApprovalCodeCreator({ model }: { model: McpServerModel }) {
|
||||
const { t } = useTranslation();
|
||||
const [preset, setPreset] = useState<McpServerPermissionPreset>(DEFAULT_PRESET);
|
||||
const create = useMutation({
|
||||
mutationFn: () => model.createApprovalCode(MCP_SERVER_PERMISSION_PRESETS[preset]),
|
||||
});
|
||||
const { mutate } = create;
|
||||
const submit = useCallback(() => mutate(), [mutate]);
|
||||
return (
|
||||
<View style={styles.body}>
|
||||
<Text style={styles.hint}>{t("mcpServer.code.hint")}</Text>
|
||||
{create.data ? (
|
||||
<CopyBlock
|
||||
label={t(`mcpServer.presets.${preset}`)}
|
||||
value={create.data.code}
|
||||
large
|
||||
testID="mcp-server-code-value"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<PresetPicker value={preset} onChange={setPreset} testID="mcp-server-code-preset" />
|
||||
{create.error ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.code.failed", { message: create.error.message })}
|
||||
/>
|
||||
) : null}
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={submit}
|
||||
loading={create.isPending}
|
||||
disabled={create.isPending}
|
||||
testID="mcp-server-code-create"
|
||||
>
|
||||
{t("mcpServer.code.create")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: { gap: theme.spacing[4] },
|
||||
hint: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
}));
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import {
|
||||
createMcpServerModel,
|
||||
type McpServerClient,
|
||||
type McpServerModel,
|
||||
type McpServerState,
|
||||
} from "./model";
|
||||
|
||||
const models = new Map<string, McpServerModel>();
|
||||
|
||||
/** The one MCP Server model for a host. It observes the host only while subscribed. */
|
||||
export function mcpServerModelFor(serverId: string): McpServerModel {
|
||||
let model = models.get(serverId);
|
||||
if (!model) {
|
||||
const runtime = getHostRuntimeStore();
|
||||
model = createMcpServerModel({
|
||||
// The daemon client implements more than this; the model needs only MCP Server calls.
|
||||
getClient: (): McpServerClient | null => runtime.getSnapshot(serverId)?.client ?? null,
|
||||
subscribe: (listener) => runtime.subscribe(serverId, listener),
|
||||
});
|
||||
models.set(serverId, model);
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
export function useMcpServer(model: McpServerModel): McpServerState {
|
||||
return useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { McpServerApprovalPrompts } from "./approval-prompt";
|
||||
export { McpServerSettings } from "./settings-page";
|
||||
@@ -0,0 +1,357 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DaemonPermission, McpServerAccess } from "@getpaseo/protocol/messages";
|
||||
import { ToastProvider } from "@/contexts/toast-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { AccessSection } from "./access-section";
|
||||
import { ApprovalSheet } from "./approval-prompt";
|
||||
import { ConnectAppSteps } from "./connect-app-sheet";
|
||||
import { CONNECT_APPS } from "./connect-apps";
|
||||
import { TokenCreator } from "./grant-sheets";
|
||||
import {
|
||||
createMcpServerModel,
|
||||
type McpServerClient,
|
||||
type McpServerConfigPatch,
|
||||
type McpServerLoad,
|
||||
type McpServerModel,
|
||||
} from "./model";
|
||||
import { NetworkSection, ServerSection } from "./server-section";
|
||||
import { fakeApproval, fakeCredential, fakeStatus, fakeTunnelStatus } from "./test-fixtures";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
function unmount() {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
}
|
||||
|
||||
afterEach(unmount);
|
||||
|
||||
function recordingModel(overrides: Partial<McpServerClient> = {}): {
|
||||
model: McpServerModel;
|
||||
calls: unknown[];
|
||||
} {
|
||||
const calls: unknown[] = [];
|
||||
const observation = () => ({
|
||||
subscribe: () => () => {},
|
||||
release: async () => {},
|
||||
});
|
||||
const client: McpServerClient = {
|
||||
getLastServerInfoMessage: () => ({ features: { mcpServer: true } }),
|
||||
observeMcpServerStatus: observation,
|
||||
observeMcpServerAccess: observation,
|
||||
configureMcpServer: async (patch: McpServerConfigPatch) => {
|
||||
calls.push({ configure: patch });
|
||||
return fakeStatus();
|
||||
},
|
||||
listTunnelProviders: async () => ({ providers: [] }),
|
||||
createMcpServerToken: async (input: { label: string; permissions: DaemonPermission[] }) => {
|
||||
calls.push({ createToken: input });
|
||||
return {
|
||||
credential: fakeCredential({ label: input.label, authKind: "token" }),
|
||||
token: "pmcp_0123456789abcdef_secret",
|
||||
};
|
||||
},
|
||||
revokeMcpServerCredential: async () => true,
|
||||
decideMcpServerApproval: async (input) => {
|
||||
calls.push(input);
|
||||
},
|
||||
createMcpServerApprovalCode: async () => ({ code: "ABCDE-FGHJK", expiresAt: "" }),
|
||||
...overrides,
|
||||
};
|
||||
const model = createMcpServerModel({ getClient: () => client, subscribe: () => () => {} });
|
||||
model.subscribe(() => {});
|
||||
return { model, calls };
|
||||
}
|
||||
|
||||
function mount(node: React.ReactNode) {
|
||||
unmount();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
act(() => {
|
||||
root?.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastProvider>{node}</ToastProvider>
|
||||
</I18nextProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function byTestId(testID: string): HTMLElement {
|
||||
const found = document.querySelector(`[data-testid="${testID}"]`);
|
||||
if (!(found instanceof HTMLElement)) throw new Error(`Nothing rendered as ${testID}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
async function press(testID: string) {
|
||||
await act(async () => {
|
||||
byTestId(testID).click();
|
||||
});
|
||||
}
|
||||
|
||||
describe("sign-in approval", () => {
|
||||
it("shows the app, where it returns, and the code, then approves with the chosen access", async () => {
|
||||
const { model, calls } = recordingModel();
|
||||
mount(<ApprovalSheet model={model} approval={fakeApproval("a1")} hostLabel="Studio Mac" />);
|
||||
|
||||
expect(document.body.textContent).toContain("App a1 wants to use Paseo tools on Studio Mac.");
|
||||
expect(byTestId("mcp-server-approval-redirect").textContent).toBe("app.example");
|
||||
expect(byTestId("mcp-server-approval-code").textContent).toBe("123-456");
|
||||
expect(document.body.textContent).toContain("Sees hosts, workspaces, and agents.");
|
||||
|
||||
await press("mcp-server-approval-preset-orchestrate");
|
||||
expect(document.body.textContent).toContain("Also starts agents and sends them prompts.");
|
||||
await press("mcp-server-approval-approve");
|
||||
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
approvalId: "a1",
|
||||
decision: "approve",
|
||||
permissions: ["daemon.read", "workspace.read", "workspace.write"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("denies without granting anything", async () => {
|
||||
const { model, calls } = recordingModel();
|
||||
mount(<ApprovalSheet model={model} approval={fakeApproval("a2")} hostLabel="Studio Mac" />);
|
||||
await press("mcp-server-approval-deny");
|
||||
expect(calls).toEqual([{ approvalId: "a2", decision: "deny" }]);
|
||||
});
|
||||
|
||||
it("focuses the dialog rather than the top-right close button when opening", async () => {
|
||||
const { model } = recordingModel();
|
||||
mount(<ApprovalSheet model={model} approval={fakeApproval("a3")} hostLabel="Studio Mac" />);
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||
|
||||
const dialog = document.querySelector('[role="dialog"]');
|
||||
const closeButton = document.querySelector('[aria-label="Close"]');
|
||||
expect(dialog).toBeTruthy();
|
||||
expect(closeButton).toBeTruthy();
|
||||
expect(document.activeElement).toBe(dialog);
|
||||
expect(document.activeElement).not.toBe(closeButton);
|
||||
});
|
||||
});
|
||||
|
||||
const LISTED_ACCESS: McpServerLoad<McpServerAccess> = {
|
||||
kind: "ready",
|
||||
value: {
|
||||
approvals: [fakeApproval("waiting")],
|
||||
credentials: [
|
||||
fakeCredential(),
|
||||
fakeCredential({
|
||||
id: "cred-2",
|
||||
label: "Build bot",
|
||||
authKind: "token",
|
||||
redirectHost: null,
|
||||
permissions: ["daemon.read", "workspace.read", "workspace.write"],
|
||||
}),
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const EMPTY_ACCESS: McpServerLoad<McpServerAccess> = {
|
||||
kind: "ready",
|
||||
value: { approvals: [], credentials: [] },
|
||||
};
|
||||
|
||||
describe("authentication and connected access", () => {
|
||||
it("lists connected clients, tokens, and pending approvals when OAuth and Bearer are enabled", () => {
|
||||
const { model } = recordingModel();
|
||||
mount(<AccessSection model={model} status={fakeStatus()} access={LISTED_ACCESS} />);
|
||||
|
||||
expect(byTestId("mcp-server-pending-waiting").textContent).toContain("App waiting");
|
||||
expect(byTestId("mcp-server-credential-cred-1").textContent).toContain(
|
||||
"Signed in · claude.ai · Read-only · Never used",
|
||||
);
|
||||
expect(byTestId("mcp-server-credential-cred-2").textContent).toContain(
|
||||
"Token · Orchestrate · Never used",
|
||||
);
|
||||
expect(byTestId("mcp-server-create-token")).toBeTruthy();
|
||||
expect(byTestId("mcp-server-create-code")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides token creation when Bearer tokens are off and hides approval code when OAuth is off", () => {
|
||||
const { model } = recordingModel();
|
||||
mount(
|
||||
<AccessSection
|
||||
model={model}
|
||||
status={fakeStatus({ auth: { oauth: true, bearerTokens: false, defaultPermissions: [] } })}
|
||||
access={EMPTY_ACCESS}
|
||||
/>,
|
||||
);
|
||||
expect(document.querySelector('[data-testid="mcp-server-create-token"]')).toBeNull();
|
||||
expect(byTestId("mcp-server-create-code")).toBeTruthy();
|
||||
|
||||
mount(
|
||||
<AccessSection
|
||||
model={model}
|
||||
status={fakeStatus({ auth: { oauth: false, bearerTokens: true, defaultPermissions: [] } })}
|
||||
access={EMPTY_ACCESS}
|
||||
/>,
|
||||
);
|
||||
expect(byTestId("mcp-server-create-token")).toBeTruthy();
|
||||
expect(document.querySelector('[data-testid="mcp-server-create-code"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("shows an unauthenticated warning and default access selector when both OAuth and Bearer are off", () => {
|
||||
const { model } = recordingModel();
|
||||
mount(
|
||||
<AccessSection
|
||||
model={model}
|
||||
status={fakeStatus({ auth: { oauth: false, bearerTokens: false, defaultPermissions: [] } })}
|
||||
access={EMPTY_ACCESS}
|
||||
/>,
|
||||
);
|
||||
expect(byTestId("mcp-server-no-auth-warning").textContent).toContain("Authentication is off");
|
||||
expect(byTestId("mcp-server-default-access").textContent).toContain("None (no tools)");
|
||||
expect(document.querySelector('[data-testid="mcp-server-create-token"]')).toBeNull();
|
||||
expect(document.querySelector('[data-testid="mcp-server-create-code"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("shows an empty list before any app connects", () => {
|
||||
const { model } = recordingModel();
|
||||
mount(<AccessSection model={model} status={fakeStatus()} access={EMPTY_ACCESS} />);
|
||||
expect(byTestId("mcp-server-credentials").textContent).toBe("No apps or tokens yet.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tokens", () => {
|
||||
it("creates a read-only token and shows it once with a warning to copy it", async () => {
|
||||
const { model, calls } = recordingModel();
|
||||
mount(<TokenCreator model={model} defaultName="Build script" />);
|
||||
await press("mcp-server-token-create");
|
||||
|
||||
expect(calls).toEqual([
|
||||
{ createToken: { label: "Build script", permissions: ["daemon.read", "workspace.read"] } },
|
||||
]);
|
||||
expect(byTestId("mcp-server-token-value").textContent).toBe("pmcp_0123456789abcdef_secret");
|
||||
expect(document.body.textContent).toContain("Copy this token now.");
|
||||
expect(document.querySelector('[data-testid="mcp-server-token-create"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("server settings", () => {
|
||||
it("shows listener status and listener errors without any agent-tools-off banner", () => {
|
||||
const { model } = recordingModel();
|
||||
mount(
|
||||
<ServerSection
|
||||
model={model}
|
||||
status={fakeStatus({
|
||||
listener: {
|
||||
host: "0.0.0.0",
|
||||
port: 6770,
|
||||
state: "error",
|
||||
url: null,
|
||||
error: "Port 6770 is in use",
|
||||
},
|
||||
mcpUrls: [],
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(document.body.textContent).not.toContain("Agent tools are off");
|
||||
expect(byTestId("mcp-server-listener-status").textContent).toContain("Error");
|
||||
expect(byTestId("mcp-server-listener-error").textContent).toContain("Port 6770 is in use");
|
||||
});
|
||||
|
||||
it("shows a saved tunnel provider while stopped and exposes provider load, error, retry, and success", async () => {
|
||||
let resolveFirst!: (value: {
|
||||
providers: Array<{
|
||||
id: string;
|
||||
pluginId: string;
|
||||
label: string;
|
||||
availability: { status: "available" };
|
||||
}>;
|
||||
}) => void;
|
||||
let rejectFirst!: (reason?: unknown) => void;
|
||||
let attempt = 0;
|
||||
const { model } = recordingModel({
|
||||
listTunnelProviders: () => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) {
|
||||
return new Promise((resolve, reject) => {
|
||||
resolveFirst = resolve;
|
||||
rejectFirst = reject;
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
providers: [
|
||||
{
|
||||
id: "cloudflare",
|
||||
pluginId: "cloudflare",
|
||||
label: "Cloudflare Tunnel",
|
||||
availability: { status: "available" },
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
});
|
||||
const status = fakeStatus({
|
||||
enabled: false,
|
||||
listener: { host: "127.0.0.1", port: 6770, state: "stopped", url: null, error: null },
|
||||
tunnel: {
|
||||
providerId: "cloudflare",
|
||||
state: "closed",
|
||||
url: null,
|
||||
stability: null,
|
||||
detail: null,
|
||||
error: null,
|
||||
},
|
||||
mcpUrls: [],
|
||||
});
|
||||
|
||||
mount(<NetworkSection serverId="srv-1" model={model} status={status} />);
|
||||
|
||||
// Loading state still shows the saved provider ID instead of falling back to "None".
|
||||
expect(byTestId("mcp-server-tunnel").textContent).toContain("cloudflare");
|
||||
expect(byTestId("mcp-server-tunnel").textContent).toContain("Loading tunnel providers…");
|
||||
|
||||
// Provider fetch error surfaces an inline alert with Retry.
|
||||
await vi.waitFor(() => expect(attempt).toBe(1));
|
||||
void resolveFirst;
|
||||
await act(async () => {
|
||||
rejectFirst(new Error("Plugin host unreachable"));
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(byTestId("mcp-server-tunnel-error").textContent).toContain(
|
||||
"Could not load tunnel providers: Plugin host unreachable",
|
||||
);
|
||||
});
|
||||
|
||||
// Retrying resolves to the provider label and shows that the saved tunnel opens on enable.
|
||||
await press("mcp-server-tunnel-retry");
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector('[data-testid="mcp-server-tunnel-error"]')).toBeNull();
|
||||
expect(byTestId("mcp-server-tunnel").textContent).toContain("Cloudflare Tunnel");
|
||||
expect(byTestId("mcp-server-tunnel").textContent).toContain(
|
||||
"Stopped. Opens when MCP Server is enabled.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("setup guides", () => {
|
||||
it("shows OAuth 2.1 steps for Poke, Grok Bot, and OpenClaw without requiring a token", () => {
|
||||
const { model } = recordingModel();
|
||||
const status = fakeTunnelStatus("https://abc.tunnel.example");
|
||||
for (const id of ["poke", "grok", "openclaw"] as const) {
|
||||
const app = CONNECT_APPS.find((entry) => entry.id === id)!;
|
||||
mount(<ConnectAppSteps model={model} status={status} app={app} />);
|
||||
expect(document.querySelector('[data-testid="mcp-server-token-create"]')).toBeNull();
|
||||
expect(document.body.textContent).toMatch(/approve the sign-in in Paseo/i);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type {
|
||||
McpServerAccess,
|
||||
McpServerApproval,
|
||||
McpServerStatus,
|
||||
SessionOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
createMcpServerModel,
|
||||
type McpServerClient,
|
||||
type McpServerConfigPatch,
|
||||
type McpServerObservation,
|
||||
} from "./model";
|
||||
import { fakeApproval, fakeStatus } from "./test-fixtures";
|
||||
|
||||
type Observer<Snapshot> = Parameters<McpServerObservation<Snapshot>["subscribe"]>[0];
|
||||
|
||||
/** A daemon subscription the test drives by hand. */
|
||||
class FakeObservation<Snapshot> implements McpServerObservation<Snapshot> {
|
||||
observer: Observer<Snapshot> | null = null;
|
||||
released = false;
|
||||
subscribe(observer: Observer<Snapshot>) {
|
||||
this.observer = observer;
|
||||
return () => {
|
||||
this.observer = null;
|
||||
};
|
||||
}
|
||||
async release() {
|
||||
this.released = true;
|
||||
}
|
||||
snapshot(value: Snapshot) {
|
||||
this.observer?.snapshot(value);
|
||||
}
|
||||
update(message: SessionOutboundMessage) {
|
||||
this.observer?.update(message);
|
||||
}
|
||||
fail(error: Error) {
|
||||
this.observer?.error?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
class FakeClient implements McpServerClient {
|
||||
status = new FakeObservation<{ status: McpServerStatus }>();
|
||||
access = new FakeObservation<McpServerAccess>();
|
||||
decisions: unknown[] = [];
|
||||
configs: unknown[] = [];
|
||||
constructor(private readonly features: { mcpServer?: boolean } = { mcpServer: true }) {}
|
||||
getLastServerInfoMessage() {
|
||||
return { features: this.features };
|
||||
}
|
||||
observeMcpServerStatus() {
|
||||
return this.status;
|
||||
}
|
||||
observeMcpServerAccess() {
|
||||
return this.access;
|
||||
}
|
||||
async configureMcpServer(patch: McpServerConfigPatch) {
|
||||
this.configs.push(patch);
|
||||
const base = fakeStatus();
|
||||
return {
|
||||
...base,
|
||||
...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}),
|
||||
...(patch.auth ? { auth: { ...base.auth, ...patch.auth } } : {}),
|
||||
};
|
||||
}
|
||||
async listTunnelProviders() {
|
||||
return { providers: [] };
|
||||
}
|
||||
async createMcpServerToken(): Promise<never> {
|
||||
throw new Error("not used");
|
||||
}
|
||||
async revokeMcpServerCredential() {
|
||||
return true;
|
||||
}
|
||||
async decideMcpServerApproval(input: unknown) {
|
||||
this.decisions.push(input);
|
||||
}
|
||||
async createMcpServerApprovalCode(): Promise<never> {
|
||||
throw new Error("not used");
|
||||
}
|
||||
}
|
||||
|
||||
function fakeHost(initial: FakeClient | null) {
|
||||
let client = initial;
|
||||
const listeners = new Set<() => void>();
|
||||
return {
|
||||
getClient: () => client,
|
||||
subscribe(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
connect(next: FakeClient | null) {
|
||||
client = next;
|
||||
for (const listener of listeners) listener();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function accessChanged(approvals: McpServerApproval[]): SessionOutboundMessage {
|
||||
return {
|
||||
type: "mcp_server.access.changed",
|
||||
payload: { subscriptionId: "sub-access", credentials: [], approvals },
|
||||
};
|
||||
}
|
||||
|
||||
describe("MCP Server model", () => {
|
||||
it("reports an offline host and a host too old for MCP Server", () => {
|
||||
const host = fakeHost(null);
|
||||
const model = createMcpServerModel(host);
|
||||
const stop = model.subscribe(() => {});
|
||||
expect(model.getSnapshot()).toEqual({ host: "offline" });
|
||||
|
||||
host.connect(new FakeClient({}));
|
||||
expect(model.getSnapshot()).toEqual({ host: "unsupported" });
|
||||
stop();
|
||||
});
|
||||
|
||||
it("follows status and access from snapshot through changes", () => {
|
||||
const client = new FakeClient();
|
||||
const model = createMcpServerModel(fakeHost(client));
|
||||
const stop = model.subscribe(() => {});
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
host: "online",
|
||||
status: { kind: "loading" },
|
||||
access: { kind: "loading" },
|
||||
});
|
||||
|
||||
client.status.snapshot({ status: fakeStatus({ enabled: false }) });
|
||||
client.access.snapshot({ credentials: [], approvals: [] });
|
||||
client.status.update({
|
||||
type: "mcp_server.status.changed",
|
||||
payload: { subscriptionId: "sub-status", status: fakeStatus({ enabled: true }) },
|
||||
});
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
status: { kind: "ready", value: { enabled: true } },
|
||||
access: { kind: "ready", value: { credentials: [], approvals: [] } },
|
||||
prompt: null,
|
||||
});
|
||||
stop();
|
||||
});
|
||||
|
||||
it("keeps status when this device may not manage access", () => {
|
||||
const client = new FakeClient();
|
||||
const model = createMcpServerModel(fakeHost(client));
|
||||
const stop = model.subscribe(() => {});
|
||||
client.status.snapshot({ status: fakeStatus({ enabled: true }) });
|
||||
client.access.fail(new Error("Permission denied"));
|
||||
expect(model.getSnapshot()).toMatchObject({
|
||||
status: { kind: "ready" },
|
||||
access: { kind: "error", message: "Permission denied" },
|
||||
prompt: null,
|
||||
});
|
||||
stop();
|
||||
});
|
||||
|
||||
it("prompts for each waiting sign-in until the owner decides, closes, or it expires", () => {
|
||||
const client = new FakeClient();
|
||||
const model = createMcpServerModel(fakeHost(client));
|
||||
const stop = model.subscribe(() => {});
|
||||
const first = fakeApproval("first");
|
||||
const second = fakeApproval("second");
|
||||
client.access.snapshot({ credentials: [], approvals: [first, second] });
|
||||
const prompt = () => {
|
||||
const state = model.getSnapshot();
|
||||
return state.host === "online" ? (state.prompt?.id ?? null) : "not online";
|
||||
};
|
||||
expect(prompt()).toBe("first");
|
||||
|
||||
model.dismissPrompt("first");
|
||||
expect(prompt()).toBe("second");
|
||||
model.dismissPrompt("second");
|
||||
expect(prompt()).toBeNull();
|
||||
|
||||
model.reviewApproval("second");
|
||||
expect(prompt()).toBe("second");
|
||||
|
||||
client.access.update(accessChanged([first]));
|
||||
expect(prompt()).toBeNull();
|
||||
client.access.update(accessChanged([]));
|
||||
expect(prompt()).toBeNull();
|
||||
stop();
|
||||
});
|
||||
|
||||
it("sends auth config patches and approval decisions", async () => {
|
||||
const client = new FakeClient();
|
||||
const model = createMcpServerModel(fakeHost(client));
|
||||
const stop = model.subscribe(() => {});
|
||||
await model.configure({
|
||||
auth: { oauth: false, bearerTokens: false, defaultPermissions: ["daemon.read"] },
|
||||
});
|
||||
await model.approve("a1", ["daemon.read", "workspace.read"]);
|
||||
await model.deny("a2");
|
||||
expect(client.configs).toEqual([
|
||||
{ auth: { oauth: false, bearerTokens: false, defaultPermissions: ["daemon.read"] } },
|
||||
]);
|
||||
expect(client.decisions).toEqual([
|
||||
{ approvalId: "a1", decision: "approve", permissions: ["daemon.read", "workspace.read"] },
|
||||
{ approvalId: "a2", decision: "deny" },
|
||||
]);
|
||||
stop();
|
||||
});
|
||||
|
||||
it("drops the old host's subscriptions on reconnect and after the last listener leaves", () => {
|
||||
const before = new FakeClient();
|
||||
const host = fakeHost(before);
|
||||
const model = createMcpServerModel(host);
|
||||
const stop = model.subscribe(() => {});
|
||||
const after = new FakeClient();
|
||||
host.connect(after);
|
||||
expect(before.status.released).toBe(true);
|
||||
expect(before.access.released).toBe(true);
|
||||
|
||||
before.status.snapshot({ status: fakeStatus({ enabled: true }) });
|
||||
expect(model.getSnapshot()).toMatchObject({ status: { kind: "loading" } });
|
||||
|
||||
stop();
|
||||
expect(after.status.released).toBe(true);
|
||||
expect(after.access.released).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses commands while the host is offline", async () => {
|
||||
const model = createMcpServerModel(fakeHost(null));
|
||||
const stop = model.subscribe(() => {});
|
||||
await expect(model.configure({ enabled: true })).rejects.toThrow("The host is not connected.");
|
||||
stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
import type {
|
||||
DaemonPermission,
|
||||
McpServerAccess,
|
||||
McpServerApproval,
|
||||
McpServerConfigureAuthPatch,
|
||||
McpServerCredential,
|
||||
McpServerStatus,
|
||||
SessionOutboundMessage,
|
||||
TunnelProviderInfo,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
/** A daemon subscription as the client hands it out: a snapshot, then change messages. */
|
||||
export interface McpServerObservation<Snapshot> {
|
||||
subscribe(observer: {
|
||||
snapshot(snapshot: Snapshot): void;
|
||||
update(message: SessionOutboundMessage): void;
|
||||
error?(error: unknown): void;
|
||||
}): () => void;
|
||||
release(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface McpServerConfigPatch {
|
||||
enabled?: boolean;
|
||||
listenHost?: string;
|
||||
port?: number;
|
||||
tunnelProviderId?: string | null;
|
||||
publicUrl?: string | null;
|
||||
auth?: McpServerConfigureAuthPatch;
|
||||
}
|
||||
|
||||
/** The part of the daemon client MCP Server settings use. */
|
||||
export interface McpServerClient {
|
||||
getLastServerInfoMessage(): { features?: { mcpServer?: boolean } | null } | null;
|
||||
observeMcpServerStatus(): McpServerObservation<{ status: McpServerStatus }>;
|
||||
observeMcpServerAccess(): McpServerObservation<McpServerAccess>;
|
||||
configureMcpServer(patch: McpServerConfigPatch): Promise<McpServerStatus>;
|
||||
listTunnelProviders(): Promise<{ providers: TunnelProviderInfo[] }>;
|
||||
createMcpServerToken(input: {
|
||||
label: string;
|
||||
permissions: DaemonPermission[];
|
||||
}): Promise<{ credential: McpServerCredential; token: string }>;
|
||||
revokeMcpServerCredential(credentialId: string): Promise<boolean>;
|
||||
decideMcpServerApproval(
|
||||
input:
|
||||
| { approvalId: string; decision: "approve"; permissions: DaemonPermission[] }
|
||||
| { approvalId: string; decision: "deny" },
|
||||
): Promise<void>;
|
||||
createMcpServerApprovalCode(
|
||||
permissions: DaemonPermission[],
|
||||
): Promise<{ code: string; expiresAt: string }>;
|
||||
}
|
||||
|
||||
/** Where the model finds the host's client. The client changes as the host reconnects. */
|
||||
export interface McpServerHost {
|
||||
getClient(): McpServerClient | null;
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
export type McpServerLoad<T> =
|
||||
| { kind: "loading" }
|
||||
| { kind: "ready"; value: T }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
export type McpServerState =
|
||||
| { host: "offline" }
|
||||
| { host: "unsupported" }
|
||||
| {
|
||||
host: "online";
|
||||
status: McpServerLoad<McpServerStatus>;
|
||||
/** Fails on its own when this device may not manage access; status still shows. */
|
||||
access: McpServerLoad<McpServerAccess>;
|
||||
/** The sign-in this device asks the owner about now, or null. */
|
||||
prompt: McpServerApproval | null;
|
||||
};
|
||||
|
||||
export class McpServerUnavailableError extends Error {
|
||||
constructor() {
|
||||
super("The host is not connected.");
|
||||
this.name = "McpServerUnavailableError";
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
const OFFLINE: McpServerState = { host: "offline" };
|
||||
const UNSUPPORTED: McpServerState = { host: "unsupported" };
|
||||
|
||||
/**
|
||||
* One host's MCP Server: its status, auth mode, the apps and tokens that can reach it, and the
|
||||
* sign-ins waiting for approval. Settings and the approval prompt share one model per host, so the
|
||||
* host sends each change once. The model observes the host only while something is subscribed.
|
||||
*/
|
||||
export function createMcpServerModel(host: McpServerHost) {
|
||||
let state: McpServerState = OFFLINE;
|
||||
let client: McpServerClient | null = null;
|
||||
let stopObserving: (() => void) | null = null;
|
||||
let stopHost: (() => void) | null = null;
|
||||
// Sign-ins the owner closed the prompt for. They stay pending and listed in settings.
|
||||
const dismissed = new Set<string>();
|
||||
// A sign-in the owner reopened from settings goes ahead of older ones.
|
||||
let reviewing: string | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const publish = (next: McpServerState) => {
|
||||
state = next;
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
|
||||
const promptFor = (access: McpServerLoad<McpServerAccess>): McpServerApproval | null => {
|
||||
if (access.kind !== "ready") return null;
|
||||
const pending = new Set(access.value.approvals.map((approval) => approval.id));
|
||||
for (const id of dismissed) if (!pending.has(id)) dismissed.delete(id);
|
||||
if (reviewing && !pending.has(reviewing)) reviewing = null;
|
||||
const open = access.value.approvals.filter((approval) => !dismissed.has(approval.id));
|
||||
return open.find((approval) => approval.id === reviewing) ?? open[0] ?? null;
|
||||
};
|
||||
|
||||
const update = (change: {
|
||||
status?: McpServerLoad<McpServerStatus>;
|
||||
access?: McpServerLoad<McpServerAccess>;
|
||||
}) => {
|
||||
if (state.host !== "online") return;
|
||||
const access = change.access ?? state.access;
|
||||
publish({
|
||||
host: "online",
|
||||
status: change.status ?? state.status,
|
||||
access,
|
||||
prompt: promptFor(access),
|
||||
});
|
||||
};
|
||||
|
||||
const observe = (observed: McpServerClient): (() => void) => {
|
||||
const current = () => client === observed;
|
||||
const status = observed.observeMcpServerStatus();
|
||||
const access = observed.observeMcpServerAccess();
|
||||
status.subscribe({
|
||||
snapshot: (snapshot) => {
|
||||
if (current()) update({ status: { kind: "ready", value: snapshot.status } });
|
||||
},
|
||||
update: (message) => {
|
||||
if (current() && message.type === "mcp_server.status.changed") {
|
||||
update({ status: { kind: "ready", value: message.payload.status } });
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
if (current()) update({ status: { kind: "error", message: errorMessage(error) } });
|
||||
},
|
||||
});
|
||||
access.subscribe({
|
||||
snapshot: ({ credentials, approvals }) => {
|
||||
if (current()) update({ access: { kind: "ready", value: { credentials, approvals } } });
|
||||
},
|
||||
update: (message) => {
|
||||
if (current() && message.type === "mcp_server.access.changed") {
|
||||
const { credentials, approvals } = message.payload;
|
||||
update({ access: { kind: "ready", value: { credentials, approvals } } });
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
if (current()) update({ access: { kind: "error", message: errorMessage(error) } });
|
||||
},
|
||||
});
|
||||
return () => {
|
||||
for (const observation of [status, access]) {
|
||||
void observation
|
||||
.release()
|
||||
.catch((error: unknown) =>
|
||||
console.error("MCP Server subscription cleanup failed", error),
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const sync = () => {
|
||||
const candidate = host.getClient();
|
||||
// The runtime keeps a client across reconnects but clears server info until the handshake.
|
||||
const next = candidate?.getLastServerInfoMessage() ? candidate : null;
|
||||
if (next === client) return;
|
||||
stopObserving?.();
|
||||
stopObserving = null;
|
||||
client = next;
|
||||
if (!next) {
|
||||
publish(OFFLINE);
|
||||
return;
|
||||
}
|
||||
// COMPAT(mcpServer): added in v0.19.1, remove gate after 2027-06-01.
|
||||
if (next.getLastServerInfoMessage()?.features?.mcpServer !== true) {
|
||||
publish(UNSUPPORTED);
|
||||
return;
|
||||
}
|
||||
publish({
|
||||
host: "online",
|
||||
status: { kind: "loading" },
|
||||
access: { kind: "loading" },
|
||||
prompt: null,
|
||||
});
|
||||
try {
|
||||
stopObserving = observe(next);
|
||||
} catch (error) {
|
||||
// The client refuses to observe when its connection dropped after the handshake. The host
|
||||
// runtime then reports the change, and the next sync starts over.
|
||||
const failed = { kind: "error" as const, message: errorMessage(error) };
|
||||
update({ status: failed, access: failed });
|
||||
}
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
stopHost = host.subscribe(sync);
|
||||
sync();
|
||||
};
|
||||
|
||||
const stop = () => {
|
||||
stopHost?.();
|
||||
stopHost = null;
|
||||
stopObserving?.();
|
||||
stopObserving = null;
|
||||
client = null;
|
||||
state = OFFLINE;
|
||||
};
|
||||
|
||||
const requireClient = (): McpServerClient => {
|
||||
if (!client || state.host !== "online") throw new McpServerUnavailableError();
|
||||
return client;
|
||||
};
|
||||
|
||||
return {
|
||||
getSnapshot: (): McpServerState => state,
|
||||
subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
if (!stopHost) start();
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) stop();
|
||||
};
|
||||
},
|
||||
async configure(patch: McpServerConfigPatch): Promise<void> {
|
||||
const status = await requireClient().configureMcpServer(patch);
|
||||
update({ status: { kind: "ready", value: status } });
|
||||
},
|
||||
async listTunnelProviders(): Promise<TunnelProviderInfo[]> {
|
||||
return (await requireClient().listTunnelProviders()).providers;
|
||||
},
|
||||
createToken(input: { label: string; permissions: readonly DaemonPermission[] }) {
|
||||
return requireClient().createMcpServerToken({
|
||||
label: input.label,
|
||||
permissions: [...input.permissions],
|
||||
});
|
||||
},
|
||||
async revoke(credentialId: string): Promise<void> {
|
||||
await requireClient().revokeMcpServerCredential(credentialId);
|
||||
},
|
||||
approve(approvalId: string, permissions: readonly DaemonPermission[]): Promise<void> {
|
||||
return requireClient().decideMcpServerApproval({
|
||||
approvalId,
|
||||
decision: "approve",
|
||||
permissions: [...permissions],
|
||||
});
|
||||
},
|
||||
deny(approvalId: string): Promise<void> {
|
||||
return requireClient().decideMcpServerApproval({ approvalId, decision: "deny" });
|
||||
},
|
||||
createApprovalCode(permissions: readonly DaemonPermission[]) {
|
||||
return requireClient().createMcpServerApprovalCode([...permissions]);
|
||||
},
|
||||
/** Stops prompting for a sign-in without deciding it. Settings still lists it. */
|
||||
dismissPrompt(approvalId: string): void {
|
||||
dismissed.add(approvalId);
|
||||
if (reviewing === approvalId) reviewing = null;
|
||||
update({});
|
||||
},
|
||||
/** Prompts again for a sign-in the owner closed earlier. */
|
||||
reviewApproval(approvalId: string): void {
|
||||
dismissed.delete(approvalId);
|
||||
reviewing = approvalId;
|
||||
update({});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type McpServerModel = ReturnType<typeof createMcpServerModel>;
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
MCP_SERVER_PERMISSION_PRESET_ORDER,
|
||||
type McpServerPermissionPreset,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field } from "@/components/ui/form-field";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { copyToClipboard } from "@/utils/copy-to-clipboard";
|
||||
|
||||
export const DEFAULT_PRESET: McpServerPermissionPreset = "read";
|
||||
|
||||
/** Read-only, Orchestrate, or Full, with a line on what the chosen one allows. */
|
||||
export function PresetPicker({
|
||||
value,
|
||||
onChange,
|
||||
testID,
|
||||
}: {
|
||||
value: McpServerPermissionPreset;
|
||||
onChange(preset: McpServerPermissionPreset): void;
|
||||
testID?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const options = useMemo<SegmentedControlOption<McpServerPermissionPreset>[]>(
|
||||
() =>
|
||||
MCP_SERVER_PERMISSION_PRESET_ORDER.map((preset) => ({
|
||||
value: preset,
|
||||
label: t(`mcpServer.presets.${preset}`),
|
||||
testID: testID ? `${testID}-${preset}` : undefined,
|
||||
})),
|
||||
[t, testID],
|
||||
);
|
||||
return (
|
||||
<Field label={t("mcpServer.presets.label")} hint={t(`mcpServer.presets.${value}Hint`)}>
|
||||
<SegmentedControl
|
||||
options={options}
|
||||
value={value}
|
||||
onValueChange={onChange}
|
||||
fill
|
||||
testID={testID}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
export function useCopy() {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
return useCallback(
|
||||
(text: string) => {
|
||||
void copyToClipboard(text)
|
||||
.then(() => toast.copied())
|
||||
.catch(() => toast.error(t("common.errors.unableToCopy")));
|
||||
},
|
||||
[t, toast],
|
||||
);
|
||||
}
|
||||
|
||||
/** A token, code, or config shown in full with a Copy button. */
|
||||
export function CopyBlock({
|
||||
label,
|
||||
value,
|
||||
large = false,
|
||||
testID,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
large?: boolean;
|
||||
testID?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const copy = useCopy();
|
||||
const onCopy = useCallback(() => copy(value), [copy, value]);
|
||||
const copyButton = useMemo(
|
||||
() => (
|
||||
<Button variant="ghost" size="sm" onPress={onCopy} testID={testID && `${testID}-copy`}>
|
||||
{t("common.actions.copy")}
|
||||
</Button>
|
||||
),
|
||||
[onCopy, t, testID],
|
||||
);
|
||||
return (
|
||||
<Field label={label} trailing={copyButton}>
|
||||
<View style={styles.block}>
|
||||
<Text selectable style={large ? styles.large : styles.mono} testID={testID}>
|
||||
{value}
|
||||
</Text>
|
||||
</View>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
/** Numbered steps from one translated string, one step per line. */
|
||||
export function Steps({ text }: { text: string }) {
|
||||
const steps = text.split("\n").filter((line) => line.trim().length > 0);
|
||||
return (
|
||||
<View style={styles.steps}>
|
||||
{steps.map((step, index) => (
|
||||
<View key={step} style={styles.step}>
|
||||
<Text style={styles.stepNumber}>{index + 1}.</Text>
|
||||
<Text style={styles.stepText}>{step}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
block: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
borderColor: theme.colors.border,
|
||||
borderWidth: 1,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[2],
|
||||
},
|
||||
mono: {
|
||||
color: theme.colors.foreground,
|
||||
fontFamily: theme.fontFamily.mono,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
large: {
|
||||
color: theme.colors.foreground,
|
||||
fontFamily: theme.fontFamily.mono,
|
||||
fontSize: theme.fontSize.xl,
|
||||
letterSpacing: 1,
|
||||
textAlign: "center",
|
||||
},
|
||||
steps: { gap: theme.spacing[2] },
|
||||
step: { flexDirection: "row", gap: theme.spacing[2] },
|
||||
stepNumber: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
minWidth: theme.spacing[4],
|
||||
},
|
||||
stepText: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
flexShrink: 1,
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
matchMcpServerPermissionPreset,
|
||||
type DaemonPermission,
|
||||
type McpServerCredential,
|
||||
type McpServerPermissionPreset,
|
||||
type McpServerStatus,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
export type McpUrlKind = "public" | "tunnel" | "network" | "local";
|
||||
|
||||
/** Which of the owner's addresses an MCP URL is, for its label in settings. */
|
||||
export function mcpUrlKind(status: McpServerStatus, url: string): McpUrlKind {
|
||||
const origin = new URL(url).origin;
|
||||
if (status.publicUrl && origin === new URL(status.publicUrl).origin) return "public";
|
||||
if (status.tunnel?.url && origin === new URL(status.tunnel.url).origin) return "tunnel";
|
||||
if (url === status.listener.url) return "local";
|
||||
return "network";
|
||||
}
|
||||
|
||||
/** A port typed by the owner, or null when it is not a usable TCP port. */
|
||||
export function parsePort(text: string): number | null {
|
||||
if (!/^\d{1,5}$/u.test(text.trim())) return null;
|
||||
const port = Number(text.trim());
|
||||
return port >= 1 && port <= 65_535 ? port : null;
|
||||
}
|
||||
|
||||
export type CredentialAccess =
|
||||
| { kind: "preset"; preset: McpServerPermissionPreset }
|
||||
| { kind: "custom"; permissions: string };
|
||||
|
||||
/** A credential's access as the preset name the owner picked, or its raw permissions. */
|
||||
export function credentialAccess(credential: McpServerCredential): CredentialAccess {
|
||||
const preset = matchMcpServerPermissionPreset(credential.permissions);
|
||||
return preset
|
||||
? { kind: "preset", preset }
|
||||
: { kind: "custom", permissions: credential.permissions.join(", ") };
|
||||
}
|
||||
|
||||
export type DefaultAccessSelection = "none" | McpServerPermissionPreset | "custom";
|
||||
|
||||
export function defaultAccessSelection(
|
||||
permissions: readonly DaemonPermission[],
|
||||
): DefaultAccessSelection {
|
||||
if (permissions.length === 0) return "none";
|
||||
return matchMcpServerPermissionPreset(permissions) ?? "custom";
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { McpServerStatus } from "@getpaseo/protocol/messages";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import {
|
||||
SettingsAction,
|
||||
SettingsCard,
|
||||
SettingsDetailRow,
|
||||
SettingsSection,
|
||||
SettingsSelect,
|
||||
SettingsSwitch,
|
||||
} from "@/components/settings";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { StatusBadge, type StatusBadgeVariant } from "@/components/ui/status-badge";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import type { McpServerConfigPatch, McpServerModel } from "./model";
|
||||
import { useCopy } from "./parts";
|
||||
import { mcpUrlKind, parsePort } from "./presentation";
|
||||
|
||||
const NO_TUNNEL = "none";
|
||||
|
||||
function listenerBadge(
|
||||
listener: McpServerStatus["listener"],
|
||||
t: TFunction,
|
||||
): { label: string; variant: StatusBadgeVariant } {
|
||||
if (listener.state === "listening") {
|
||||
return { label: t("mcpServer.server.statusListening"), variant: "success" };
|
||||
}
|
||||
if (listener.state === "error") {
|
||||
return { label: t("mcpServer.server.statusError"), variant: "error" };
|
||||
}
|
||||
return { label: t("mcpServer.server.statusStopped"), variant: "muted" };
|
||||
}
|
||||
|
||||
/** Enable toggle, live listener status, and active MCP URLs with Copy buttons. */
|
||||
export function ServerSection({
|
||||
model,
|
||||
status,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const configure = useMutation({
|
||||
mutationFn: (patch: McpServerConfigPatch) => model.configure(patch),
|
||||
});
|
||||
const { mutate } = configure;
|
||||
const setEnabled = useCallback((enabled: boolean) => mutate({ enabled }), [mutate]);
|
||||
const enabled =
|
||||
configure.isPending && configure.variables?.enabled !== undefined
|
||||
? configure.variables.enabled
|
||||
: status.enabled;
|
||||
const { listener } = status;
|
||||
const badge = listenerBadge(listener, t);
|
||||
const statusBadge = useMemo(
|
||||
() => (
|
||||
<StatusBadge
|
||||
size="xs"
|
||||
label={badge.label}
|
||||
variant={badge.variant}
|
||||
testID="mcp-server-listener-status"
|
||||
/>
|
||||
),
|
||||
[badge.label, badge.variant],
|
||||
);
|
||||
const ephemeral = status.tunnel?.state === "ready" && status.tunnel.stability === "ephemeral";
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("mcpServer.server.section")}>
|
||||
<SettingsCard>
|
||||
<SettingsSwitch
|
||||
label={t("mcpServer.server.enable")}
|
||||
hint={t("mcpServer.server.enableHint")}
|
||||
labelAccessory={statusBadge}
|
||||
value={enabled}
|
||||
onValueChange={configure.isPending ? undefined : setEnabled}
|
||||
error={
|
||||
configure.error
|
||||
? t("mcpServer.server.saveFailed", { message: configure.error.message })
|
||||
: undefined
|
||||
}
|
||||
testID="mcp-server-enabled"
|
||||
/>
|
||||
</SettingsCard>
|
||||
{listener.state === "error" && listener.error ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.server.listenerError", { message: listener.error })}
|
||||
testID="mcp-server-listener-error"
|
||||
/>
|
||||
) : null}
|
||||
{ephemeral ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
title={t("mcpServer.server.tunnelEphemeral")}
|
||||
testID="mcp-server-ephemeral"
|
||||
/>
|
||||
) : null}
|
||||
<SettingsCard testID="mcp-server-urls">
|
||||
{status.mcpUrls.length === 0 ? (
|
||||
<View style={settingsStyles.row}>
|
||||
<Text style={styles.emptyText}>{t("mcpServer.urls.none")}</Text>
|
||||
</View>
|
||||
) : (
|
||||
status.mcpUrls.map((url) => <UrlRow key={url} status={status} url={url} />)
|
||||
)}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
function UrlRow({ status, url }: { status: McpServerStatus; url: string }) {
|
||||
const { t } = useTranslation();
|
||||
const copy = useCopy();
|
||||
const onCopy = useCallback(() => copy(url), [copy, url]);
|
||||
return (
|
||||
<SettingsAction
|
||||
label={url}
|
||||
hint={t(`mcpServer.urls.${mcpUrlKind(status, url)}`)}
|
||||
actionLabel={t("common.actions.copy")}
|
||||
onPress={onCopy}
|
||||
testID="mcp-server-url"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Listen host/port, optional tunnel, and optional reverse-proxy public URL. */
|
||||
export function NetworkSection({
|
||||
serverId,
|
||||
model,
|
||||
status,
|
||||
}: {
|
||||
serverId: string;
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [editing, setEditing] = useState<"listener" | "publicUrl" | null>(null);
|
||||
const editListener = useCallback(() => setEditing("listener"), []);
|
||||
const editPublicUrl = useCallback(() => setEditing("publicUrl"), []);
|
||||
const stopEditing = useCallback(() => setEditing(null), []);
|
||||
const { listener } = status;
|
||||
const providers = useFetchQuery({
|
||||
queryKey: ["mcp-server-tunnel-providers", serverId],
|
||||
queryFn: () => model.listTunnelProviders(),
|
||||
staleTimeMs: 30_000,
|
||||
dataShape: "list",
|
||||
});
|
||||
const retryProviders = useCallback(() => {
|
||||
void providers.refetch();
|
||||
}, [providers]);
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("mcpServer.network.section")}>
|
||||
<SettingsCard>
|
||||
<SettingsDetailRow
|
||||
label={t("mcpServer.server.listener")}
|
||||
hint={
|
||||
listener.state === "error" && listener.error
|
||||
? t("mcpServer.server.listenerError", { message: listener.error })
|
||||
: t("mcpServer.server.listenerHint")
|
||||
}
|
||||
hintStatus={listener.state === "error" ? "error" : undefined}
|
||||
summary={`${listener.host}:${listener.port}`}
|
||||
onPress={editListener}
|
||||
testID="mcp-server-listener"
|
||||
/>
|
||||
<TunnelRow model={model} status={status} providers={providers} />
|
||||
<SettingsDetailRow
|
||||
label={t("mcpServer.server.publicUrl")}
|
||||
hint={t("mcpServer.server.publicUrlHint")}
|
||||
summary={status.publicUrl ?? t("mcpServer.server.publicUrlNone")}
|
||||
onPress={editPublicUrl}
|
||||
testID="mcp-server-public-url"
|
||||
/>
|
||||
</SettingsCard>
|
||||
{providers.isError ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.server.tunnelLoadFailed", { message: providers.error.message })}
|
||||
testID="mcp-server-tunnel-error"
|
||||
>
|
||||
<View style={styles.retryRow}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
loading={providers.isFetching}
|
||||
onPress={retryProviders}
|
||||
testID="mcp-server-tunnel-retry"
|
||||
>
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
</View>
|
||||
</InlineAlert>
|
||||
) : null}
|
||||
<ListenerSheet
|
||||
model={model}
|
||||
status={status}
|
||||
visible={editing === "listener"}
|
||||
onClose={stopEditing}
|
||||
/>
|
||||
<PublicUrlSheet
|
||||
model={model}
|
||||
status={status}
|
||||
visible={editing === "publicUrl"}
|
||||
onClose={stopEditing}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the tunnel row says under its label: saved-while-stopped, live URL, or progress. */
|
||||
function tunnelHint(status: McpServerStatus, t: TFunction): string {
|
||||
const { tunnel } = status;
|
||||
if (!tunnel || tunnel.state === "error") {
|
||||
return t("mcpServer.server.tunnelHint");
|
||||
}
|
||||
if (!status.enabled || tunnel.state === "closed") {
|
||||
return t("mcpServer.server.tunnelSavedStopped");
|
||||
}
|
||||
if (tunnel.state === "ready" && tunnel.url) return tunnel.url;
|
||||
return t("mcpServer.server.tunnelStarting");
|
||||
}
|
||||
|
||||
function TunnelRow({
|
||||
model,
|
||||
status,
|
||||
providers,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
providers: ReturnType<
|
||||
typeof useFetchQuery<Awaited<ReturnType<McpServerModel["listTunnelProviders"]>>>
|
||||
>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const choose = useMutation({
|
||||
mutationFn: (providerId: string) =>
|
||||
model.configure({ tunnelProviderId: providerId === NO_TUNNEL ? null : providerId }),
|
||||
});
|
||||
const current = status.tunnel?.providerId ?? NO_TUNNEL;
|
||||
const options = useMemo(() => {
|
||||
const list = [{ value: NO_TUNNEL, label: t("mcpServer.server.tunnelNone") }];
|
||||
for (const provider of providers.data ?? []) {
|
||||
list.push({ value: provider.id, label: provider.label });
|
||||
}
|
||||
// A provider that is saved while loading or from an unloaded plugin stays selectable so it
|
||||
// remains visible and can be cleared.
|
||||
if (!list.some((option) => option.value === current)) {
|
||||
list.push({ value: current, label: current });
|
||||
}
|
||||
return list;
|
||||
}, [current, providers.data, t]);
|
||||
const tunnelError =
|
||||
status.tunnel?.state === "error" && status.tunnel.error
|
||||
? t("mcpServer.server.tunnelError", { message: status.tunnel.error })
|
||||
: undefined;
|
||||
return (
|
||||
<SettingsSelect
|
||||
label={t("mcpServer.server.tunnel")}
|
||||
hint={providers.isPending ? t("mcpServer.server.tunnelLoading") : tunnelHint(status, t)}
|
||||
value={choose.isPending && choose.variables ? choose.variables : current}
|
||||
options={options}
|
||||
onValueChange={choose.mutate}
|
||||
disabled={choose.isPending}
|
||||
error={
|
||||
choose.error
|
||||
? t("mcpServer.server.saveFailed", { message: choose.error.message })
|
||||
: tunnelError
|
||||
}
|
||||
testID="mcp-server-tunnel"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function EditSheet({
|
||||
title,
|
||||
visible,
|
||||
onClose,
|
||||
children,
|
||||
testID,
|
||||
}: {
|
||||
title: string;
|
||||
visible: boolean;
|
||||
onClose(): void;
|
||||
children: ReactNode;
|
||||
testID: string;
|
||||
}) {
|
||||
const header = useMemo<SheetHeader>(() => ({ title }), [title]);
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
desktopMaxWidth={440}
|
||||
testID={testID}
|
||||
>
|
||||
{visible ? children : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function ListenerSheet({
|
||||
model,
|
||||
status,
|
||||
visible,
|
||||
onClose,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
visible: boolean;
|
||||
onClose(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<EditSheet
|
||||
title={t("mcpServer.server.listener")}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
testID="mcp-server-listener-sheet"
|
||||
>
|
||||
<ListenerForm model={model} status={status} onDone={onClose} />
|
||||
</EditSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function ListenerForm({
|
||||
model,
|
||||
status,
|
||||
onDone,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
onDone(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [host, setHost] = useState(status.listener.host);
|
||||
const [portText, setPortText] = useState(String(status.listener.port));
|
||||
const [invalidPort, setInvalidPort] = useState(false);
|
||||
const save = useMutation({
|
||||
mutationFn: (patch: McpServerConfigPatch) => model.configure(patch),
|
||||
onSuccess: onDone,
|
||||
});
|
||||
const { mutate } = save;
|
||||
const submit = useCallback(() => {
|
||||
const port = parsePort(portText);
|
||||
setInvalidPort(port === null);
|
||||
if (port !== null) mutate({ listenHost: host.trim(), port });
|
||||
}, [host, mutate, portText]);
|
||||
return (
|
||||
<View style={styles.stack}>
|
||||
<InlineAlert size="sm" variant="info" title={t("mcpServer.server.listenerHint")} />
|
||||
<Field label={t("mcpServer.server.host")}>
|
||||
<FormTextInput
|
||||
initialValue={status.listener.host}
|
||||
onChangeText={setHost}
|
||||
accessibilityLabel={t("mcpServer.server.host")}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
testID="mcp-server-listener-host"
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={t("mcpServer.server.port")}
|
||||
error={invalidPort ? t("mcpServer.server.invalidPort") : null}
|
||||
>
|
||||
<FormTextInput
|
||||
initialValue={String(status.listener.port)}
|
||||
onChangeText={setPortText}
|
||||
accessibilityLabel={t("mcpServer.server.port")}
|
||||
keyboardType="number-pad"
|
||||
invalid={invalidPort}
|
||||
testID="mcp-server-listener-port"
|
||||
/>
|
||||
</Field>
|
||||
{save.error ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.server.saveFailed", { message: save.error.message })}
|
||||
/>
|
||||
) : null}
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={submit}
|
||||
loading={save.isPending}
|
||||
disabled={save.isPending}
|
||||
testID="mcp-server-listener-save"
|
||||
>
|
||||
{t("common.actions.save")}
|
||||
</Button>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function PublicUrlSheet({
|
||||
model,
|
||||
status,
|
||||
visible,
|
||||
onClose,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
visible: boolean;
|
||||
onClose(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<EditSheet
|
||||
title={t("mcpServer.server.publicUrl")}
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
testID="mcp-server-public-url-sheet"
|
||||
>
|
||||
<PublicUrlForm model={model} status={status} onDone={onClose} />
|
||||
</EditSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function PublicUrlForm({
|
||||
model,
|
||||
status,
|
||||
onDone,
|
||||
}: {
|
||||
model: McpServerModel;
|
||||
status: McpServerStatus;
|
||||
onDone(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [url, setUrl] = useState(status.publicUrl ?? "");
|
||||
const save = useMutation({
|
||||
mutationFn: (publicUrl: string | null) => model.configure({ publicUrl }),
|
||||
onSuccess: onDone,
|
||||
});
|
||||
const { mutate } = save;
|
||||
const submit = useCallback(() => mutate(url.trim() || null), [mutate, url]);
|
||||
const clear = useCallback(() => mutate(null), [mutate]);
|
||||
return (
|
||||
<View style={styles.stack}>
|
||||
<InlineAlert size="sm" variant="info" title={t("mcpServer.server.publicUrlHint")} />
|
||||
<Field label={t("mcpServer.server.publicUrl")}>
|
||||
<FormTextInput
|
||||
initialValue={status.publicUrl ?? ""}
|
||||
onChangeText={setUrl}
|
||||
placeholder={t("mcpServer.server.publicUrlPlaceholder")}
|
||||
accessibilityLabel={t("mcpServer.server.publicUrl")}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
keyboardType="url"
|
||||
testID="mcp-server-public-url-input"
|
||||
/>
|
||||
</Field>
|
||||
{save.error ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.server.saveFailed", { message: save.error.message })}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
{status.publicUrl ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
style={styles.action}
|
||||
onPress={clear}
|
||||
disabled={save.isPending}
|
||||
>
|
||||
{t("mcpServer.server.clear")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant="default"
|
||||
style={styles.action}
|
||||
onPress={submit}
|
||||
loading={save.isPending}
|
||||
disabled={save.isPending}
|
||||
testID="mcp-server-public-url-save"
|
||||
>
|
||||
{t("common.actions.save")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
stack: { gap: theme.spacing[4] },
|
||||
retryRow: { flexDirection: "row", marginTop: theme.spacing[2] },
|
||||
actions: { flexDirection: "row", gap: theme.spacing[3] },
|
||||
action: { flex: 1 },
|
||||
emptyText: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
}));
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { McpServerStatus } from "@getpaseo/protocol/messages";
|
||||
import { SettingsCard, SettingsDetailRow, SettingsSection } from "@/components/settings";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { AccessSection } from "./access-section";
|
||||
import { ConnectAppSheet } from "./connect-app-sheet";
|
||||
import { mcpServerModelFor, useMcpServer } from "./host";
|
||||
import type { McpServerModel } from "./model";
|
||||
import { NetworkSection, ServerSection } from "./server-section";
|
||||
|
||||
/** Settings → MCP Server for one host. */
|
||||
export function McpServerSettings({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const model = mcpServerModelFor(serverId);
|
||||
const state = useMcpServer(model);
|
||||
|
||||
if (state.host === "offline" || state.host === "unsupported") {
|
||||
return (
|
||||
<View style={[settingsStyles.card, styles.emptyCard]}>
|
||||
<Text style={styles.emptyText} testID="mcp-server-unavailable">
|
||||
{t(state.host === "offline" ? "mcpServer.unavailable" : "mcpServer.unsupported")}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (state.status.kind === "error") {
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={t("mcpServer.loadFailed", { message: state.status.message })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (state.status.kind === "loading") return null;
|
||||
const status = state.status.value;
|
||||
return (
|
||||
<View>
|
||||
<ServerSection model={model} status={status} />
|
||||
<NetworkSection serverId={serverId} model={model} status={status} />
|
||||
<AccessSection model={model} status={status} access={state.access} />
|
||||
<SetupGuidesSection model={model} status={status} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupGuidesSection({ model, status }: { model: McpServerModel; status: McpServerStatus }) {
|
||||
const { t } = useTranslation();
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
const openConnect = useCallback(() => setConnecting(true), []);
|
||||
const closeConnect = useCallback(() => setConnecting(false), []);
|
||||
|
||||
return (
|
||||
<SettingsSection title={t("mcpServer.guides.section")}>
|
||||
<SettingsCard>
|
||||
{status.mcpUrls.length === 0 ? (
|
||||
<View style={settingsStyles.row}>
|
||||
<Text style={styles.emptyText}>{t("mcpServer.guides.none")}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<SettingsDetailRow
|
||||
label={t("mcpServer.urls.connect")}
|
||||
hint={t("mcpServer.urls.connectHint")}
|
||||
onPress={openConnect}
|
||||
testID="mcp-server-connect-app"
|
||||
/>
|
||||
)}
|
||||
</SettingsCard>
|
||||
<ConnectAppSheet model={model} status={status} visible={connecting} onClose={closeConnect} />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
emptyCard: { padding: theme.spacing[4] },
|
||||
emptyText: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
}));
|
||||
@@ -0,0 +1,69 @@
|
||||
import type {
|
||||
McpServerApproval,
|
||||
McpServerCredential,
|
||||
McpServerStatus,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
export function fakeStatus(overrides: Partial<McpServerStatus> = {}): McpServerStatus {
|
||||
return {
|
||||
enabled: true,
|
||||
listener: {
|
||||
host: "127.0.0.1",
|
||||
port: 6770,
|
||||
state: "listening",
|
||||
url: "http://127.0.0.1:6770/mcp",
|
||||
error: null,
|
||||
},
|
||||
tunnel: null,
|
||||
publicUrl: null,
|
||||
mcpUrls: ["http://127.0.0.1:6770/mcp"],
|
||||
auth: {
|
||||
oauth: true,
|
||||
bearerTokens: true,
|
||||
defaultPermissions: [],
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function fakeTunnelStatus(
|
||||
url: string,
|
||||
stability: "stable" | "ephemeral" = "stable",
|
||||
): McpServerStatus {
|
||||
return fakeStatus({
|
||||
tunnel: {
|
||||
providerId: "cloudflared",
|
||||
state: "ready",
|
||||
url,
|
||||
stability,
|
||||
detail: null,
|
||||
error: null,
|
||||
},
|
||||
mcpUrls: [`${url}/mcp`, "http://127.0.0.1:6770/mcp"],
|
||||
});
|
||||
}
|
||||
|
||||
export function fakeCredential(overrides: Partial<McpServerCredential> = {}): McpServerCredential {
|
||||
return {
|
||||
id: "cred-1",
|
||||
label: "Claude",
|
||||
authKind: "oauth",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
lastUsedAt: null,
|
||||
expiresAt: null,
|
||||
redirectHost: "claude.ai",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function fakeApproval(id = "approval-1"): McpServerApproval {
|
||||
return {
|
||||
id,
|
||||
clientName: `App ${id}`,
|
||||
redirectHost: "app.example",
|
||||
verificationCode: "123-456",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
expiresAt: "2026-01-01T00:10:00.000Z",
|
||||
};
|
||||
}
|
||||
@@ -36,8 +36,11 @@ import {
|
||||
ChevronRight,
|
||||
Layers,
|
||||
Laptop,
|
||||
Cable,
|
||||
} from "lucide-react-native";
|
||||
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
|
||||
import { McpServerSettings } from "@/mcp-server";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
import { ComboboxTrigger, type ComboboxTriggerState } from "@/components/ui/combobox-trigger";
|
||||
import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
|
||||
import { HostPicker as SharedHostPicker } from "@/components/hosts/host-picker";
|
||||
@@ -223,6 +226,7 @@ const HOST_SECTION_ITEMS: HostSectionItem[] = [
|
||||
{ id: "terminals", labelKey: "settings.hostSections.terminals", icon: SquareTerminal },
|
||||
{ id: "plugins", labelKey: "settings.hostSections.plugins", icon: Blocks },
|
||||
{ id: "devices", labelKey: "devices.title", icon: Smartphone },
|
||||
{ id: "mcp-server", labelKey: "mcpServer.title", icon: Cable },
|
||||
{ id: "daemon", labelKey: "settings.hostSections.daemon", icon: Server },
|
||||
];
|
||||
|
||||
@@ -249,6 +253,8 @@ function renderHostSettingsContent(view: Extract<SettingsView, { kind: "host" }>
|
||||
return <PluginGalleryPage serverId={view.serverId} />;
|
||||
case "devices":
|
||||
return <HostDevicesPage serverId={view.serverId} />;
|
||||
case "mcp-server":
|
||||
return <McpServerSettings serverId={view.serverId} />;
|
||||
case "daemon":
|
||||
return <HostDaemonPage serverId={view.serverId} />;
|
||||
}
|
||||
@@ -1111,9 +1117,13 @@ function SettingsSidebar({
|
||||
const enableBuiltInDaemonOption = useEnableBuiltInDaemonOption();
|
||||
const isDesktopApp = isElectronRuntime();
|
||||
const hardwareKeyboardPresent = useHardwareKeyboardPresent();
|
||||
const supportsMcpServer = useHostFeature(activeHostServerId, "mcpServer");
|
||||
const items = SIDEBAR_SECTION_ITEMS.filter((item) =>
|
||||
isSectionAvailable(item, isDesktopApp, hardwareKeyboardPresent),
|
||||
);
|
||||
const hostItems = HOST_SECTION_ITEMS.filter(
|
||||
(item) => item.id !== "mcp-server" || supportsMcpServer,
|
||||
);
|
||||
const insets = useSafeAreaInsets();
|
||||
const isDesktop = layout === "desktop";
|
||||
const sidebarScroll = useSettingsSidebarScroll(isDesktop);
|
||||
@@ -1161,7 +1171,7 @@ function SettingsSidebar({
|
||||
enableBuiltInDaemonOption={enableBuiltInDaemonOption}
|
||||
layout={layout}
|
||||
/>
|
||||
{HOST_SECTION_ITEMS.map((item) => (
|
||||
{hostItems.map((item) => (
|
||||
<SidebarHostSectionButton
|
||||
key={item.id}
|
||||
itemId={item.id}
|
||||
|
||||
@@ -534,6 +534,7 @@ export const HOST_SECTION_SLUGS = [
|
||||
"terminals",
|
||||
"plugins",
|
||||
"devices",
|
||||
"mcp-server",
|
||||
"daemon",
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ import {
|
||||
} from "@getpaseo/protocol/binary-frames/host-route";
|
||||
import { messageTooLargeError } from "./daemon-client-transport-utils.js";
|
||||
import type { HostAdd, HostUpdate, HostDirectory } from "@getpaseo/protocol/hosts";
|
||||
import type {
|
||||
DaemonPermission,
|
||||
McpServerAccess,
|
||||
McpServerConfigureAuthPatch,
|
||||
McpServerCredential,
|
||||
McpServerStatus,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { DaemonClientsSnapshot, HelloClientInfo } from "@getpaseo/protocol/daemon-clients";
|
||||
import type { PluginListingDetail, PluginListingIndex } from "@getpaseo/protocol/plugin-registry";
|
||||
import { legacyUsageIcon } from "./legacy-usage-icons.js";
|
||||
@@ -6670,6 +6677,139 @@ export class DaemonClientCore {
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MCP Server
|
||||
// ============================================================================
|
||||
|
||||
private requireMcpServer(): void {
|
||||
if (!this.isConnected) {
|
||||
throw this.unavailableError();
|
||||
}
|
||||
// COMPAT(mcpServer): added in v0.19.0, remove gate after 2027-06-01.
|
||||
if (this.getLastServerInfoMessage()?.features?.mcpServer !== true) {
|
||||
throw Object.assign(new Error("Update the daemon to connect outside apps over MCP"), {
|
||||
code: "unsupported_capability",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getMcpServerStatus(): Promise<McpServerStatus> {
|
||||
this.requireMcpServer();
|
||||
return (
|
||||
await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.get_status.request" },
|
||||
responseType: "mcp_server.get_status.response",
|
||||
})
|
||||
).status;
|
||||
}
|
||||
|
||||
observeMcpServerStatus(): OwnedSubscription<{ status: McpServerStatus }> {
|
||||
this.requireMcpServer();
|
||||
return this.owned.observe(async (accept) => {
|
||||
const result = await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.get_status.request", observe: true },
|
||||
responseType: "mcp_server.get_status.response",
|
||||
});
|
||||
if (!result.subscriptionId) throw new Error("Host omitted subscription identity");
|
||||
const snapshot = { status: result.status, subscriptionId: result.subscriptionId };
|
||||
accept(snapshot);
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
|
||||
/** Changes only the fields given. `null` clears the tunnel provider or public URL. */
|
||||
async configureMcpServer(patch: {
|
||||
enabled?: boolean;
|
||||
listenHost?: string;
|
||||
port?: number;
|
||||
tunnelProviderId?: string | null;
|
||||
publicUrl?: string | null;
|
||||
auth?: McpServerConfigureAuthPatch;
|
||||
}): Promise<McpServerStatus> {
|
||||
this.requireMcpServer();
|
||||
return (
|
||||
await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.configure.request", ...patch },
|
||||
responseType: "mcp_server.configure.response",
|
||||
})
|
||||
).status;
|
||||
}
|
||||
|
||||
async listMcpServerAccess(): Promise<McpServerAccess> {
|
||||
this.requireMcpServer();
|
||||
const { credentials, approvals } = await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.access.list.request" },
|
||||
responseType: "mcp_server.access.list.response",
|
||||
});
|
||||
return { credentials, approvals };
|
||||
}
|
||||
|
||||
observeMcpServerAccess(): OwnedSubscription<McpServerAccess> {
|
||||
this.requireMcpServer();
|
||||
return this.owned.observe(async (accept) => {
|
||||
const result = await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.access.list.request", observe: true },
|
||||
responseType: "mcp_server.access.list.response",
|
||||
});
|
||||
if (!result.subscriptionId) throw new Error("Host omitted subscription identity");
|
||||
const snapshot = {
|
||||
credentials: result.credentials,
|
||||
approvals: result.approvals,
|
||||
subscriptionId: result.subscriptionId,
|
||||
};
|
||||
accept(snapshot);
|
||||
return snapshot;
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates a static bearer token. The token is returned once; the daemon keeps only a hash. */
|
||||
async createMcpServerToken(input: {
|
||||
label: string;
|
||||
permissions: DaemonPermission[];
|
||||
expiresAt?: string;
|
||||
}): Promise<{ credential: McpServerCredential; token: string }> {
|
||||
this.requireMcpServer();
|
||||
const { credential, token } = await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.tokens.create.request", ...input },
|
||||
responseType: "mcp_server.tokens.create.response",
|
||||
});
|
||||
return { credential, token };
|
||||
}
|
||||
|
||||
async revokeMcpServerCredential(credentialId: string): Promise<boolean> {
|
||||
this.requireMcpServer();
|
||||
return (
|
||||
await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.credentials.revoke.request", credentialId },
|
||||
responseType: "mcp_server.credentials.revoke.response",
|
||||
})
|
||||
).revoked;
|
||||
}
|
||||
|
||||
async decideMcpServerApproval(
|
||||
input:
|
||||
| { approvalId: string; decision: "approve"; permissions: DaemonPermission[] }
|
||||
| { approvalId: string; decision: "deny" },
|
||||
): Promise<void> {
|
||||
this.requireMcpServer();
|
||||
await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.approvals.decide.request", ...input },
|
||||
responseType: "mcp_server.approvals.decide.response",
|
||||
});
|
||||
}
|
||||
|
||||
/** A one-time code that approves a sign-in from the browser, for when no Paseo app is at hand. */
|
||||
async createMcpServerApprovalCode(
|
||||
permissions: DaemonPermission[],
|
||||
): Promise<{ code: string; expiresAt: string }> {
|
||||
this.requireMcpServer();
|
||||
const { code, expiresAt } = await this.sendCorrelatedSessionRequest({
|
||||
message: { type: "mcp_server.approval_codes.create.request", permissions },
|
||||
responseType: "mcp_server.approval_codes.create.response",
|
||||
});
|
||||
return { code, expiresAt };
|
||||
}
|
||||
|
||||
async requestProjectIcon(
|
||||
cwd: string,
|
||||
requestId?: string,
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { DaemonClient, type DaemonTransport } from "./daemon-client.js";
|
||||
|
||||
function createFakeTransport(features: Record<string, boolean | undefined>): {
|
||||
transport: DaemonTransport;
|
||||
sent: unknown[];
|
||||
pushSessionMessage: (message: unknown) => void;
|
||||
} {
|
||||
const sent: unknown[] = [];
|
||||
const openHandlers = new Set<() => void>();
|
||||
const messageHandlers = new Set<(data: unknown, isBinary: boolean) => void | Promise<void>>();
|
||||
const closeHandlers = new Set<(event?: unknown) => void>();
|
||||
const errorHandlers = new Set<(event?: unknown) => void>();
|
||||
|
||||
const emitMessage = (text: string) => {
|
||||
queueMicrotask(() => {
|
||||
for (const handler of messageHandlers) {
|
||||
void handler(text, false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const pushSessionMessage = (message: unknown) => {
|
||||
emitMessage(JSON.stringify({ type: "session", message }));
|
||||
};
|
||||
|
||||
const statusPayload = {
|
||||
enabled: true,
|
||||
listener: {
|
||||
host: "127.0.0.1",
|
||||
port: 6770,
|
||||
state: "listening" as const,
|
||||
url: "http://127.0.0.1:6770/mcp",
|
||||
error: null,
|
||||
},
|
||||
tunnel: null,
|
||||
publicUrl: null,
|
||||
mcpUrls: ["http://127.0.0.1:6770/mcp"],
|
||||
auth: {
|
||||
oauth: true,
|
||||
bearerTokens: true,
|
||||
defaultPermissions: [],
|
||||
},
|
||||
};
|
||||
|
||||
const transport: DaemonTransport = {
|
||||
onOpen(handler) {
|
||||
openHandlers.add(handler);
|
||||
queueMicrotask(() => handler());
|
||||
return () => openHandlers.delete(handler);
|
||||
},
|
||||
onMessage(handler) {
|
||||
messageHandlers.add(handler);
|
||||
return () => messageHandlers.delete(handler);
|
||||
},
|
||||
onClose(handler) {
|
||||
closeHandlers.add(handler);
|
||||
return () => closeHandlers.delete(handler);
|
||||
},
|
||||
onError(handler) {
|
||||
errorHandlers.add(handler);
|
||||
return () => errorHandlers.delete(handler);
|
||||
},
|
||||
send(data) {
|
||||
if (typeof data !== "string") return;
|
||||
const parsed = JSON.parse(data) as {
|
||||
type: string;
|
||||
message?: Record<string, unknown>;
|
||||
};
|
||||
sent.push(parsed);
|
||||
|
||||
if (parsed.type === "hello") {
|
||||
emitMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "server_info",
|
||||
serverId: "srv_test",
|
||||
version: "0.19.1",
|
||||
features,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.type !== "session" || !parsed.message) return;
|
||||
const requestId = parsed.message.requestId;
|
||||
if (typeof requestId !== "string") return;
|
||||
|
||||
switch (parsed.message.type) {
|
||||
case "subscription.release.request":
|
||||
pushSessionMessage({
|
||||
type: "subscription.release.response",
|
||||
payload: {
|
||||
requestId,
|
||||
subscriptionId: parsed.message.subscriptionId,
|
||||
released: true,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.get_status.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.get_status.response",
|
||||
payload: {
|
||||
requestId,
|
||||
status: statusPayload,
|
||||
...(parsed.message.observe ? { subscriptionId: "sub_status" } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.configure.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.configure.response",
|
||||
payload: {
|
||||
requestId,
|
||||
status: {
|
||||
...statusPayload,
|
||||
...(parsed.message.auth
|
||||
? {
|
||||
auth: {
|
||||
...statusPayload.auth,
|
||||
...(parsed.message.auth as Record<string, unknown>),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.access.list.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.access.list.response",
|
||||
payload: {
|
||||
requestId,
|
||||
credentials: [],
|
||||
approvals: [],
|
||||
...(parsed.message.observe ? { subscriptionId: "sub_access" } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.tokens.create.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.tokens.create.response",
|
||||
payload: {
|
||||
requestId,
|
||||
credential: {
|
||||
id: "cred_1",
|
||||
label: String(parsed.message.label),
|
||||
authKind: "token",
|
||||
permissions: parsed.message.permissions,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
lastUsedAt: null,
|
||||
expiresAt: null,
|
||||
redirectHost: null,
|
||||
},
|
||||
token: "pmcp_0000000000000001_secret",
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.credentials.revoke.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.credentials.revoke.response",
|
||||
payload: {
|
||||
requestId,
|
||||
credentialId: parsed.message.credentialId,
|
||||
revoked: true,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.approvals.decide.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.approvals.decide.response",
|
||||
payload: {
|
||||
requestId,
|
||||
approvalId: parsed.message.approvalId,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mcp_server.approval_codes.create.request":
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.approval_codes.create.response",
|
||||
payload: {
|
||||
requestId,
|
||||
code: "ABCDE-FGHIJ",
|
||||
expiresAt: "2026-01-01T00:10:00.000Z",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return { transport, sent, pushSessionMessage };
|
||||
}
|
||||
|
||||
function createClient(features: Record<string, boolean | undefined>) {
|
||||
const { transport, sent, pushSessionMessage } = createFakeTransport(features);
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767",
|
||||
clientId: "test-mcp-server-client",
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => transport,
|
||||
});
|
||||
return { client, sent, pushSessionMessage };
|
||||
}
|
||||
|
||||
describe("DaemonClient MCP Server", () => {
|
||||
test("gates MCP Server calls on server_info.features.mcpServer", async () => {
|
||||
const { client } = createClient({ mcpServer: false });
|
||||
await client.connect();
|
||||
|
||||
await expect(client.getMcpServerStatus()).rejects.toMatchObject({
|
||||
code: "unsupported_capability",
|
||||
});
|
||||
await expect(client.configureMcpServer({ enabled: true })).rejects.toMatchObject({
|
||||
code: "unsupported_capability",
|
||||
});
|
||||
await expect(client.listMcpServerAccess()).rejects.toMatchObject({
|
||||
code: "unsupported_capability",
|
||||
});
|
||||
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("executes MCP Server RPCs and receives observed updates", async () => {
|
||||
const { client, pushSessionMessage } = createClient({
|
||||
mcpServer: true,
|
||||
ownedSubscriptions: true,
|
||||
});
|
||||
await client.connect();
|
||||
|
||||
const status = await client.getMcpServerStatus();
|
||||
expect(status.auth).toEqual({
|
||||
oauth: true,
|
||||
bearerTokens: true,
|
||||
defaultPermissions: [],
|
||||
});
|
||||
|
||||
const configured = await client.configureMcpServer({
|
||||
auth: { oauth: false, bearerTokens: false, defaultPermissions: ["daemon.read"] },
|
||||
});
|
||||
expect(configured.auth).toEqual({
|
||||
oauth: false,
|
||||
bearerTokens: false,
|
||||
defaultPermissions: ["daemon.read"],
|
||||
});
|
||||
|
||||
const issued = await client.createMcpServerToken({
|
||||
label: "CI",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
});
|
||||
expect(issued.token).toBe("pmcp_0000000000000001_secret");
|
||||
expect(await client.revokeMcpServerCredential("cred_1")).toBe(true);
|
||||
await client.decideMcpServerApproval({
|
||||
approvalId: "appr_1",
|
||||
decision: "approve",
|
||||
permissions: ["daemon.read"],
|
||||
});
|
||||
const code = await client.createMcpServerApprovalCode(["daemon.read"]);
|
||||
expect(code.code).toBe("ABCDE-FGHIJ");
|
||||
|
||||
const observedStatuses: boolean[] = [];
|
||||
const statusSub = client.observeMcpServerStatus();
|
||||
statusSub.subscribe({
|
||||
snapshot: (snapshot) => observedStatuses.push(snapshot.status.enabled),
|
||||
update: (message) => {
|
||||
if (message.type === "mcp_server.status.changed") {
|
||||
observedStatuses.push(message.payload.status.enabled);
|
||||
}
|
||||
},
|
||||
});
|
||||
await statusSub.ready;
|
||||
pushSessionMessage({
|
||||
type: "mcp_server.status.changed",
|
||||
payload: { subscriptionId: "sub_status", status: { ...status, enabled: false } },
|
||||
});
|
||||
await expect.poll(() => observedStatuses).toEqual([true, false]);
|
||||
await statusSub.release();
|
||||
|
||||
const observedAccessCount: number[] = [];
|
||||
const accessSub = client.observeMcpServerAccess();
|
||||
accessSub.subscribe({
|
||||
snapshot: (snapshot) => observedAccessCount.push(snapshot.credentials.length),
|
||||
update: (message) => {
|
||||
if (message.type === "mcp_server.access.changed") {
|
||||
observedAccessCount.push(message.payload.credentials.length);
|
||||
}
|
||||
},
|
||||
});
|
||||
await accessSub.ready;
|
||||
expect(observedAccessCount).toEqual([0]);
|
||||
await accessSub.release();
|
||||
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -1064,20 +1064,23 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
|
||||
};
|
||||
}
|
||||
|
||||
async function createMcpClient({ daemonPort, password, callerAgentId }) {
|
||||
const url = new URL(`http://127.0.0.1:${daemonPort}/mcp/agents`);
|
||||
async function createMcpClient({ daemonPort, password, paseoHome, callerAgentId }) {
|
||||
const url = new URL(`http://127.0.0.1:${daemonPort}/_internal/mcp/agents`);
|
||||
if (callerAgentId) {
|
||||
url.searchParams.set("callerAgentId", callerAgentId);
|
||||
}
|
||||
const token =
|
||||
password ??
|
||||
(paseoHome ? fs.readFileSync(path.join(paseoHome, "local-credential"), "utf8").trim() : null);
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
url,
|
||||
password ? { requestInit: { headers: { Authorization: `Bearer ${password}` } } } : undefined,
|
||||
token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined,
|
||||
);
|
||||
return await experimental_createMCPClient({ transport });
|
||||
}
|
||||
|
||||
async function createMcpCallerAgent({ daemonPort, password, workspaceId }) {
|
||||
const client = await createMcpClient({ daemonPort, password });
|
||||
async function createMcpCallerAgent({ daemonPort, password, paseoHome, workspaceId }) {
|
||||
const client = await createMcpClient({ daemonPort, password, paseoHome });
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "create_agent",
|
||||
@@ -1116,6 +1119,7 @@ async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
localDaemonPort,
|
||||
localDaemonPassword,
|
||||
remoteDaemonPort,
|
||||
remoteHome,
|
||||
sharedWorkspaceId,
|
||||
targetUrl,
|
||||
runtimeDir,
|
||||
@@ -1130,6 +1134,7 @@ async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
});
|
||||
const remoteAgentId = await createMcpCallerAgent({
|
||||
daemonPort: remoteDaemonPort,
|
||||
paseoHome: remoteHome,
|
||||
workspaceId: sharedWorkspaceId,
|
||||
});
|
||||
|
||||
@@ -1140,6 +1145,7 @@ async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
});
|
||||
const remoteClient = await createMcpClient({
|
||||
daemonPort: remoteDaemonPort,
|
||||
paseoHome: remoteHome,
|
||||
callerAgentId: remoteAgentId,
|
||||
});
|
||||
|
||||
@@ -1762,6 +1768,7 @@ async function main() {
|
||||
localDaemonPort,
|
||||
localDaemonPassword,
|
||||
remoteDaemonPort,
|
||||
remoteHome,
|
||||
sharedWorkspaceId,
|
||||
targetUrl,
|
||||
runtimeDir,
|
||||
|
||||
@@ -410,11 +410,17 @@ async function callBrowserTool(client, name, args = {}) {
|
||||
return mcpPayload(await client.callTool({ name, args }), name);
|
||||
}
|
||||
|
||||
async function connectBrowserToolClient(daemonPort, callerAgentId) {
|
||||
function readLocalCredentialHeaders(paseoHome) {
|
||||
const token = fs.readFileSync(path.join(paseoHome, "local-credential"), "utf8").trim();
|
||||
return { headers: { Authorization: `Bearer ${token}` } };
|
||||
}
|
||||
|
||||
async function connectBrowserToolClient(daemonPort, paseoHome, callerAgentId) {
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
new URL(
|
||||
`http://127.0.0.1:${daemonPort}/mcp/agents?callerAgentId=${encodeURIComponent(callerAgentId)}`,
|
||||
`http://127.0.0.1:${daemonPort}/_internal/mcp/agents?callerAgentId=${encodeURIComponent(callerAgentId)}`,
|
||||
),
|
||||
{ requestInit: readLocalCredentialHeaders(paseoHome) },
|
||||
);
|
||||
return experimental_createMCPClient({ transport });
|
||||
}
|
||||
@@ -661,9 +667,10 @@ async function verifyLocalUploadContainment({ client, targetUrl, workspaceDir, r
|
||||
}
|
||||
}
|
||||
|
||||
async function createCallerAgent(daemonPort, workspaceId = workspaceIds[0]) {
|
||||
async function createCallerAgent(daemonPort, paseoHome, workspaceId = workspaceIds[0]) {
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${daemonPort}/mcp/agents`),
|
||||
new URL(`http://127.0.0.1:${daemonPort}/_internal/mcp/agents`),
|
||||
{ requestInit: readLocalCredentialHeaders(paseoHome) },
|
||||
);
|
||||
const client = await experimental_createMCPClient({ transport });
|
||||
try {
|
||||
@@ -1651,8 +1658,8 @@ async function main() {
|
||||
}
|
||||
const { page, status } = await launchDesktop({ approveSeededPlugin: true });
|
||||
async function checkProfiles() {
|
||||
const caller = await createCallerAgent(daemonPort);
|
||||
const profileClient = await connectBrowserToolClient(daemonPort, caller);
|
||||
const caller = await createCallerAgent(daemonPort, paseoHome);
|
||||
const profileClient = await connectBrowserToolClient(daemonPort, paseoHome, caller);
|
||||
const inspect = (expression) => evaluateDesktopWindow(inspectorPort, expression);
|
||||
try {
|
||||
return await runProfileJourney({
|
||||
@@ -1727,20 +1734,20 @@ async function main() {
|
||||
browserWorkspaceId: workspaceIds[0],
|
||||
});
|
||||
if (process.env.PASEO_DESKTOP_BROWSER_PERMISSIONS_ONLY === "1") {
|
||||
const callerAgentId = await createCallerAgent(daemonPort);
|
||||
client = await connectBrowserToolClient(daemonPort, callerAgentId);
|
||||
const callerAgentId = await createCallerAgent(daemonPort, paseoHome);
|
||||
client = await connectBrowserToolClient(daemonPort, paseoHome, callerAgentId);
|
||||
const permissions = await checkPermissions(client);
|
||||
writeJson(path.join(artifactDir, "result.json"), { permissions });
|
||||
console.log("Desktop browser permissions regression passed.");
|
||||
return;
|
||||
}
|
||||
if (process.env.PASEO_DESKTOP_BROWSER_FOCUS_ONLY === "1") {
|
||||
const callerAgentId = await createCallerAgent(daemonPort);
|
||||
const callerAgentId = await createCallerAgent(daemonPort, paseoHome);
|
||||
const typingAgent = {
|
||||
workspaceId: workspaceIds.at(-1),
|
||||
agentId: await createCallerAgent(daemonPort, workspaceIds.at(-1)),
|
||||
agentId: await createCallerAgent(daemonPort, paseoHome, workspaceIds.at(-1)),
|
||||
};
|
||||
client = await connectBrowserToolClient(daemonPort, callerAgentId);
|
||||
client = await connectBrowserToolClient(daemonPort, paseoHome, callerAgentId);
|
||||
const focusIsolation = await checkFocusIsolation(client, callerAgentId, typingAgent);
|
||||
writeJson(path.join(artifactDir, "result.json"), { focusIsolation });
|
||||
console.log("Desktop browser focus isolation regression passed.");
|
||||
@@ -1772,12 +1779,12 @@ async function main() {
|
||||
const adaptiveTheme = await runAdaptiveThemeRegression(artifactDir);
|
||||
await runAppearanceFontSizeRegression(page);
|
||||
|
||||
const callerAgentId = await createCallerAgent(daemonPort);
|
||||
const callerAgentId = await createCallerAgent(daemonPort, paseoHome);
|
||||
const typingAgent = {
|
||||
workspaceId: workspaceIds.at(-1),
|
||||
agentId: await createCallerAgent(daemonPort, workspaceIds.at(-1)),
|
||||
agentId: await createCallerAgent(daemonPort, paseoHome, workspaceIds.at(-1)),
|
||||
};
|
||||
client = await connectBrowserToolClient(daemonPort, callerAgentId);
|
||||
client = await connectBrowserToolClient(daemonPort, paseoHome, callerAgentId);
|
||||
const report = await runRegression({
|
||||
page,
|
||||
client,
|
||||
@@ -1797,7 +1804,11 @@ async function main() {
|
||||
const focusIsolation = await checkFocusIsolation(client, callerAgentId, typingAgent);
|
||||
const permissions = await checkPermissions(client);
|
||||
const pluginLinks = await checkPluginLinks();
|
||||
const routingClient = await connectBrowserToolClient(daemonPort, typingAgent.agentId);
|
||||
const routingClient = await connectBrowserToolClient(
|
||||
daemonPort,
|
||||
paseoHome,
|
||||
typingAgent.agentId,
|
||||
);
|
||||
try {
|
||||
await verifyBrowserHostRouting({
|
||||
page,
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { z } from "zod";
|
||||
import { type DaemonPermission, DaemonPermissionSchema } from "./daemon-permissions.js";
|
||||
import { TunnelExposureStateSchema, TunnelStabilitySchema } from "./tunnels.js";
|
||||
|
||||
export const MCP_SERVER_DEFAULT_LISTEN_HOST = "127.0.0.1";
|
||||
export const MCP_SERVER_DEFAULT_PORT = 6770;
|
||||
|
||||
/**
|
||||
* The MCP Server listener. It always runs while the MCP Server is on and never shares the
|
||||
* daemon's own port. Binding 0.0.0.0 or putting a reverse proxy in front exposes it directly.
|
||||
*/
|
||||
export const McpServerListenerStatusSchema = z.object({
|
||||
host: z.string(),
|
||||
port: z.number().int(),
|
||||
state: z.enum(["stopped", "listening", "error"]),
|
||||
/** The MCP URL at the listener's own address. */
|
||||
url: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
});
|
||||
|
||||
/** An optional tunnel that adds a public URL for the running listener. */
|
||||
export const McpServerTunnelStatusSchema = z.object({
|
||||
providerId: z.string(),
|
||||
state: TunnelExposureStateSchema,
|
||||
url: z.string().nullable(),
|
||||
/** `ephemeral` URLs change when the tunnel restarts, which breaks saved app connections. */
|
||||
stability: TunnelStabilitySchema.nullable(),
|
||||
detail: z.string().nullable(),
|
||||
error: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const McpServerAuthSettingsSchema = z.object({
|
||||
oauth: z.boolean(),
|
||||
bearerTokens: z.boolean(),
|
||||
/** Permissions granted to unauthenticated requests when both OAuth and Bearer tokens are off. */
|
||||
defaultPermissions: z.array(DaemonPermissionSchema),
|
||||
});
|
||||
|
||||
export const McpServerStatusSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
listener: McpServerListenerStatusSchema,
|
||||
tunnel: McpServerTunnelStatusSchema.nullable(),
|
||||
/** The owner's own URL for a reverse proxy or domain in front of the listener. */
|
||||
publicUrl: z.string().nullable(),
|
||||
/** Every MCP URL that works now, most public first. All of them can be used at once. */
|
||||
mcpUrls: z.array(z.string()),
|
||||
auth: McpServerAuthSettingsSchema,
|
||||
});
|
||||
|
||||
export const McpServerAuthKindSchema = z.enum(["oauth", "token"]);
|
||||
|
||||
export const McpServerCredentialSchema = z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
authKind: McpServerAuthKindSchema,
|
||||
permissions: z.array(DaemonPermissionSchema),
|
||||
createdAt: z.string(),
|
||||
lastUsedAt: z.string().nullable(),
|
||||
expiresAt: z.string().nullable(),
|
||||
/** Host of the redirect URI an OAuth app registered. */
|
||||
redirectHost: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const McpServerApprovalSchema = z.object({
|
||||
id: z.string(),
|
||||
clientName: z.string(),
|
||||
redirectHost: z.string(),
|
||||
/** Shown on both the sign-in page and in Paseo so the owner approves the right browser. */
|
||||
verificationCode: z.string(),
|
||||
createdAt: z.string(),
|
||||
expiresAt: z.string(),
|
||||
});
|
||||
|
||||
const McpServerPermissionsSchema = z.array(DaemonPermissionSchema).min(1).max(32);
|
||||
const McpServerDefaultPermissionsSchema = z.array(DaemonPermissionSchema).max(32);
|
||||
|
||||
export const McpServerGetStatusRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.get_status.request"),
|
||||
requestId: z.string(),
|
||||
observe: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const McpServerGetStatusResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.get_status.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
status: McpServerStatusSchema,
|
||||
subscriptionId: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const McpServerStatusChangedSchema = z.object({
|
||||
type: z.literal("mcp_server.status.changed"),
|
||||
payload: z.object({ subscriptionId: z.string(), status: McpServerStatusSchema }),
|
||||
});
|
||||
|
||||
export const McpServerConfigureAuthPatchSchema = z.object({
|
||||
oauth: z.boolean().optional(),
|
||||
bearerTokens: z.boolean().optional(),
|
||||
defaultPermissions: McpServerDefaultPermissionsSchema.optional(),
|
||||
});
|
||||
|
||||
/** Changes only the fields it carries. `null` clears the tunnel or public URL. */
|
||||
export const McpServerConfigureRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.configure.request"),
|
||||
requestId: z.string(),
|
||||
enabled: z.boolean().optional(),
|
||||
listenHost: z.string().trim().min(1).max(256).optional(),
|
||||
port: z.number().int().min(1).max(65535).optional(),
|
||||
tunnelProviderId: z.string().min(1).max(256).nullable().optional(),
|
||||
publicUrl: z.string().min(1).max(2048).nullable().optional(),
|
||||
auth: McpServerConfigureAuthPatchSchema.optional(),
|
||||
});
|
||||
|
||||
export const McpServerConfigureResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.configure.response"),
|
||||
payload: z.object({ requestId: z.string(), status: McpServerStatusSchema }),
|
||||
});
|
||||
|
||||
export const McpServerAccessListRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.access.list.request"),
|
||||
requestId: z.string(),
|
||||
observe: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const McpServerAccessSchema = z.object({
|
||||
credentials: z.array(McpServerCredentialSchema),
|
||||
approvals: z.array(McpServerApprovalSchema),
|
||||
});
|
||||
|
||||
export const McpServerAccessListResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.access.list.response"),
|
||||
payload: McpServerAccessSchema.extend({
|
||||
requestId: z.string(),
|
||||
subscriptionId: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const McpServerAccessChangedSchema = z.object({
|
||||
type: z.literal("mcp_server.access.changed"),
|
||||
payload: McpServerAccessSchema.extend({ subscriptionId: z.string() }),
|
||||
});
|
||||
|
||||
export const McpServerTokensCreateRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.tokens.create.request"),
|
||||
requestId: z.string(),
|
||||
label: z.string().trim().min(1).max(100),
|
||||
permissions: McpServerPermissionsSchema,
|
||||
expiresAt: z.string().optional(),
|
||||
});
|
||||
|
||||
export const McpServerTokensCreateResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.tokens.create.response"),
|
||||
payload: z.object({
|
||||
requestId: z.string(),
|
||||
credential: McpServerCredentialSchema,
|
||||
/** Shown once. The daemon keeps only its hash. */
|
||||
token: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const McpServerCredentialsRevokeRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.credentials.revoke.request"),
|
||||
requestId: z.string(),
|
||||
credentialId: z.string().min(1).max(256),
|
||||
});
|
||||
|
||||
export const McpServerCredentialsRevokeResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.credentials.revoke.response"),
|
||||
payload: z.object({ requestId: z.string(), credentialId: z.string(), revoked: z.boolean() }),
|
||||
});
|
||||
|
||||
export const McpServerApprovalsDecideRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.approvals.decide.request"),
|
||||
requestId: z.string(),
|
||||
approvalId: z.string().min(1).max(256),
|
||||
decision: z.enum(["approve", "deny"]),
|
||||
/** Required to approve. */
|
||||
permissions: McpServerPermissionsSchema.optional(),
|
||||
});
|
||||
|
||||
export const McpServerApprovalsDecideResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.approvals.decide.response"),
|
||||
payload: z.object({ requestId: z.string(), approvalId: z.string() }),
|
||||
});
|
||||
|
||||
export const McpServerApprovalCodesCreateRequestSchema = z.object({
|
||||
type: z.literal("mcp_server.approval_codes.create.request"),
|
||||
requestId: z.string(),
|
||||
permissions: McpServerPermissionsSchema,
|
||||
});
|
||||
|
||||
export const McpServerApprovalCodesCreateResponseSchema = z.object({
|
||||
type: z.literal("mcp_server.approval_codes.create.response"),
|
||||
payload: z.object({ requestId: z.string(), code: z.string(), expiresAt: z.string() }),
|
||||
});
|
||||
|
||||
export type McpServerListenerStatus = z.infer<typeof McpServerListenerStatusSchema>;
|
||||
export type McpServerTunnelStatus = z.infer<typeof McpServerTunnelStatusSchema>;
|
||||
export type McpServerAuthSettings = z.infer<typeof McpServerAuthSettingsSchema>;
|
||||
export type McpServerConfigureAuthPatch = z.infer<typeof McpServerConfigureAuthPatchSchema>;
|
||||
export type McpServerStatus = z.infer<typeof McpServerStatusSchema>;
|
||||
export type McpServerAuthKind = z.infer<typeof McpServerAuthKindSchema>;
|
||||
export type McpServerCredential = z.infer<typeof McpServerCredentialSchema>;
|
||||
export type McpServerApproval = z.infer<typeof McpServerApprovalSchema>;
|
||||
export type McpServerAccess = z.infer<typeof McpServerAccessSchema>;
|
||||
|
||||
/**
|
||||
* Access presets the owner picks from. They expand into explicit permissions before they reach
|
||||
* the daemon, which stores only the permissions, so a preset that grows never widens old grants.
|
||||
*/
|
||||
export const MCP_SERVER_PERMISSION_PRESETS = {
|
||||
read: ["daemon.read", "workspace.read"],
|
||||
orchestrate: ["daemon.read", "workspace.read", "workspace.write"],
|
||||
full: [
|
||||
"daemon.read",
|
||||
"workspace.read",
|
||||
"workspace.write",
|
||||
"workspace.manage",
|
||||
"automation.manage",
|
||||
],
|
||||
} as const satisfies Record<string, readonly DaemonPermission[]>;
|
||||
|
||||
export type McpServerPermissionPreset = keyof typeof MCP_SERVER_PERMISSION_PRESETS;
|
||||
|
||||
export const MCP_SERVER_PERMISSION_PRESET_ORDER: readonly McpServerPermissionPreset[] = [
|
||||
"read",
|
||||
"orchestrate",
|
||||
"full",
|
||||
];
|
||||
|
||||
/** The preset whose permissions equal `permissions`, or null for a custom set. */
|
||||
export function matchMcpServerPermissionPreset(
|
||||
permissions: readonly DaemonPermission[],
|
||||
): McpServerPermissionPreset | null {
|
||||
const granted = new Set(permissions);
|
||||
for (const preset of MCP_SERVER_PERMISSION_PRESET_ORDER) {
|
||||
const expected: readonly DaemonPermission[] = MCP_SERVER_PERMISSION_PRESETS[preset];
|
||||
if (expected.length === granted.size && expected.every((p) => granted.has(p))) return preset;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -46,6 +46,25 @@ import {
|
||||
WorkspaceScriptTunnelSchema,
|
||||
} from "./tunnels.js";
|
||||
export * from "./tunnels.js";
|
||||
import {
|
||||
McpServerAccessChangedSchema,
|
||||
McpServerAccessListRequestSchema,
|
||||
McpServerAccessListResponseSchema,
|
||||
McpServerApprovalCodesCreateRequestSchema,
|
||||
McpServerApprovalCodesCreateResponseSchema,
|
||||
McpServerApprovalsDecideRequestSchema,
|
||||
McpServerApprovalsDecideResponseSchema,
|
||||
McpServerConfigureRequestSchema,
|
||||
McpServerConfigureResponseSchema,
|
||||
McpServerCredentialsRevokeRequestSchema,
|
||||
McpServerCredentialsRevokeResponseSchema,
|
||||
McpServerGetStatusRequestSchema,
|
||||
McpServerGetStatusResponseSchema,
|
||||
McpServerStatusChangedSchema,
|
||||
McpServerTokensCreateRequestSchema,
|
||||
McpServerTokensCreateResponseSchema,
|
||||
} from "./mcp-server.js";
|
||||
export * from "./mcp-server.js";
|
||||
import {
|
||||
PluginRegistryIdSchema,
|
||||
PluginRegistryIdentitySchema,
|
||||
@@ -3851,6 +3870,13 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
TunnelExposuresListRequestSchema,
|
||||
TunnelExposureOpenRequestSchema,
|
||||
TunnelExposureCloseRequestSchema,
|
||||
McpServerGetStatusRequestSchema,
|
||||
McpServerConfigureRequestSchema,
|
||||
McpServerAccessListRequestSchema,
|
||||
McpServerTokensCreateRequestSchema,
|
||||
McpServerCredentialsRevokeRequestSchema,
|
||||
McpServerApprovalsDecideRequestSchema,
|
||||
McpServerApprovalCodesCreateRequestSchema,
|
||||
NetworkTunnelCreateTicketRequestSchema,
|
||||
|
||||
BrowserHostRegisterRequestSchema,
|
||||
@@ -4374,6 +4400,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
pluginNotifications: z.boolean().optional(),
|
||||
// COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01.
|
||||
tunnelProviders: z.boolean().optional(),
|
||||
// COMPAT(mcpServer): added in v0.19.0, remove gate after 2027-06-01.
|
||||
mcpServer: z.boolean().optional(),
|
||||
// COMPAT(workspaceScriptTunnels): added in v0.19.0, remove gate after 2027-06-01.
|
||||
// Daemons with tunnelProviders but not this flag neither report a script's tunnel
|
||||
// nor close it when the service stops.
|
||||
@@ -8231,6 +8259,15 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
TunnelExposureChangedSchema,
|
||||
TunnelExposureOpenResponseSchema,
|
||||
TunnelExposureCloseResponseSchema,
|
||||
McpServerGetStatusResponseSchema,
|
||||
McpServerStatusChangedSchema,
|
||||
McpServerConfigureResponseSchema,
|
||||
McpServerAccessListResponseSchema,
|
||||
McpServerAccessChangedSchema,
|
||||
McpServerTokensCreateResponseSchema,
|
||||
McpServerCredentialsRevokeResponseSchema,
|
||||
McpServerApprovalsDecideResponseSchema,
|
||||
McpServerApprovalCodesCreateResponseSchema,
|
||||
NetworkTunnelCreateTicketResponseSchema,
|
||||
|
||||
BrowserHostRegisterResponseSchema,
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/daemon-e2e/mcp-server.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -4559,7 +4559,7 @@ test("createAgent injects paseo MCP server only into provider launch config", as
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000103",
|
||||
});
|
||||
|
||||
@@ -4587,7 +4587,8 @@ test("createAgent injects paseo MCP server only into provider launch config", as
|
||||
expect(client.lastConfig?.mcpServers).toEqual({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${snapshot.id}`,
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${manager.getAgentMcpToken(snapshot.id)}` },
|
||||
},
|
||||
custom: {
|
||||
type: "stdio",
|
||||
@@ -4807,7 +4808,7 @@ test("createAgent passes native Paseo tools through launch context without inter
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
paseoToolCatalogFactory: () => paseoTools,
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000106",
|
||||
});
|
||||
@@ -4871,8 +4872,7 @@ test("createAgent allows best-effort internal MCP when the provider session repo
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: "cap-token",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000104",
|
||||
});
|
||||
|
||||
@@ -4885,11 +4885,12 @@ test("createAgent allows best-effort internal MCP when the provider session repo
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
expect(manager.getMcpAuthToken()).toBe("cap-token");
|
||||
const token = manager.getAgentMcpToken(snapshot.id);
|
||||
expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
||||
expect(client.lastConfig?.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${snapshot.id}`,
|
||||
headers: { Authorization: "Bearer cap-token" },
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${token!}` },
|
||||
});
|
||||
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
@@ -4936,7 +4937,7 @@ test("uses each provider's current policy for new sessions and snapshots it by a
|
||||
clients: { codex, claude },
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
resolvePaseoToolPolicy: (provider) => policies.get(provider),
|
||||
paseoToolCatalogFactory: async (context) => {
|
||||
policyInputs.push(context);
|
||||
@@ -5016,7 +5017,7 @@ test("keeps the global Paseo-tools gate outside provider policy and MCP injectio
|
||||
clients: { codex: enabledClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
resolvePaseoToolPolicy: () => ({ disabledTools: ["list_agents"] }),
|
||||
});
|
||||
const enabledAgent = await enabledManager.createAgent(
|
||||
@@ -5027,7 +5028,8 @@ test("keeps the global Paseo-tools gate outside provider policy and MCP injectio
|
||||
|
||||
expect(enabledClient.lastConfig?.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${enabledAgent.id}`,
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${enabledManager.getAgentMcpToken(enabledAgent.id)}` },
|
||||
});
|
||||
|
||||
const disabledClient = new McpClient();
|
||||
@@ -5036,7 +5038,7 @@ test("keeps the global Paseo-tools gate outside provider policy and MCP injectio
|
||||
clients: { codex: disabledClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
paseoToolsEnabled: false,
|
||||
resolvePaseoToolPolicy: () => ({ enabled: true }),
|
||||
paseoToolCatalogFactory: () => {
|
||||
@@ -5147,8 +5149,7 @@ test("voice-only delivery injects internal paseo MCP and native voiceOnly catalo
|
||||
clients: { claude: mcpClient, opencode: nativeClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: "voice-token",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
paseoToolsEnabled: false,
|
||||
hasActiveVoiceTools: (agentId) => voiceActiveAgents.has(agentId),
|
||||
paseoToolCatalogFactory: (context) => {
|
||||
@@ -5183,10 +5184,12 @@ test("voice-only delivery injects internal paseo MCP and native voiceOnly catalo
|
||||
{ systemPrompt: "voice prompt" },
|
||||
{ requireVoiceSpeak: true },
|
||||
);
|
||||
const voiceToken = manager.getAgentMcpToken(claudeAgent.id);
|
||||
expect(voiceToken).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
||||
expect(mcpClient.configs.at(-1)?.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
headers: { Authorization: "Bearer voice-token" },
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${voiceToken!}` },
|
||||
});
|
||||
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBe(true);
|
||||
|
||||
@@ -5293,7 +5296,7 @@ test("reloadAgentSession rejects voice mode when the session cannot mount speak
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
paseoToolsEnabled: false,
|
||||
hasActiveVoiceTools: () => voiceActive,
|
||||
});
|
||||
@@ -5365,7 +5368,7 @@ test("resumeAgentFromPersistence replaces stored internal paseo MCP with current
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6768/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6768/_internal/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000105",
|
||||
});
|
||||
const handle: AgentPersistenceHandle = {
|
||||
@@ -5393,7 +5396,8 @@ test("resumeAgentFromPersistence replaces stored internal paseo MCP with current
|
||||
expect(client.resumeOverrides[0]?.mcpServers).toEqual({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:6768/mcp/agents?callerAgentId=${snapshot.id}`,
|
||||
url: "http://127.0.0.1:6768/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${manager.getAgentMcpToken(snapshot.id)}` },
|
||||
},
|
||||
custom: {
|
||||
type: "stdio",
|
||||
@@ -5463,7 +5467,7 @@ test("createAgent preserves a user-provided paseo MCP config", async () => {
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000104",
|
||||
});
|
||||
|
||||
|
||||
@@ -147,7 +147,9 @@ import {
|
||||
projectAgentMessages,
|
||||
} from "./agent-messages/index.js";
|
||||
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import { AgentMcpTokenRegistry } from "./mcp-token-registry.js";
|
||||
import {
|
||||
hasInternalPaseoMcpServer,
|
||||
PASEO_MCP_SERVER_NAME,
|
||||
stripInternalPaseoMcpServer,
|
||||
withRuntimePaseoMcpServer,
|
||||
@@ -568,7 +570,7 @@ export interface AgentManagerOptions {
|
||||
timeline?: AgentTimeline;
|
||||
terminalManager?: TerminalManager | null;
|
||||
mcpBaseUrl?: string;
|
||||
mcpAuthToken?: string;
|
||||
mcpTokenRegistry?: AgentMcpTokenRegistry;
|
||||
pluginSessions?: PluginSessionsRuntime;
|
||||
paseoToolsEnabled?: boolean;
|
||||
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
|
||||
@@ -1280,7 +1282,8 @@ export class AgentManager {
|
||||
>();
|
||||
private readonly agentStreamCoalescer: AgentStreamCoalescer;
|
||||
private mcpBaseUrl: string | null;
|
||||
private readonly mcpAuthToken: string | null;
|
||||
private readonly mcpTokenRegistry: AgentMcpTokenRegistry;
|
||||
private readonly launchingAgents = new Set<string>();
|
||||
private readonly pluginSessions: PluginSessionsRuntime | undefined;
|
||||
private paseoToolsEnabled = true;
|
||||
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
|
||||
@@ -1311,7 +1314,7 @@ export class AgentManager {
|
||||
this.onAgentAttention = options?.onAgentAttention;
|
||||
this.onWorkspaceStateMayHaveChanged = options?.onWorkspaceStateMayHaveChanged;
|
||||
this.mcpBaseUrl = options?.mcpBaseUrl ?? null;
|
||||
this.mcpAuthToken = options?.mcpAuthToken ?? null;
|
||||
this.mcpTokenRegistry = options?.mcpTokenRegistry ?? new AgentMcpTokenRegistry();
|
||||
this.configurePaseoTools(options);
|
||||
this.resolvePaseoToolPolicy = options.resolvePaseoToolPolicy ?? (() => undefined);
|
||||
this.resolveWorkspaceProjectResourceApproval = options.resolveWorkspaceProjectResourceApproval;
|
||||
@@ -1557,14 +1560,26 @@ export class AgentManager {
|
||||
return this.paseoToolPolicies.get(agentId);
|
||||
}
|
||||
|
||||
private syncAgentMcpTokenAfterLaunch(agentId: string, launchConfig: AgentSessionConfig): void {
|
||||
if (!hasInternalPaseoMcpServer(launchConfig)) {
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Capability token the daemon's own MCP clients must present to the Agent MCP
|
||||
* endpoint when a daemon password is configured. Read by the per-client
|
||||
* session to authenticate its own MCP connection. Stays in the daemon — never
|
||||
* sent to remote clients.
|
||||
* Returns the active per-agent MCP capability token if one is issued for the
|
||||
* agent, without minting a new token.
|
||||
*/
|
||||
getMcpAuthToken(): string | null {
|
||||
return this.mcpAuthToken;
|
||||
getAgentMcpToken(agentId: string): string | null {
|
||||
return this.mcpTokenRegistry.get(agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether `agentId` is currently launching or running as a live,
|
||||
* non-closed agent eligible to use a per-agent MCP capability token.
|
||||
*/
|
||||
isAgentMcpCallerActive(agentId: string): boolean {
|
||||
return this.launchingAgents.has(agentId) || this.agents.has(agentId);
|
||||
}
|
||||
|
||||
setAppendSystemPrompt(prompt: string | null | undefined): void {
|
||||
@@ -2239,6 +2254,7 @@ export class AgentManager {
|
||||
background: options.background,
|
||||
launchEnv: options.env ? { ...options.env } : undefined,
|
||||
});
|
||||
this.syncAgentMcpTokenAfterLaunch(resolvedAgentId, providerLaunchConfig);
|
||||
if (!agent.internal) {
|
||||
this.pluginLifecycle?.emit("agent.create.after", {
|
||||
agent: describeHookAgent({ ...agent, title: agent.config.title }),
|
||||
@@ -2383,6 +2399,7 @@ export class AgentManager {
|
||||
restoring: true,
|
||||
importMissingHistory: true,
|
||||
});
|
||||
this.syncAgentMcpTokenAfterLaunch(resolvedAgentId, providerLaunchConfig);
|
||||
return await this.settleStoredRewind(registered);
|
||||
}
|
||||
|
||||
@@ -2474,6 +2491,7 @@ export class AgentManager {
|
||||
initialTitle,
|
||||
publishWhenReady: true,
|
||||
});
|
||||
this.syncAgentMcpTokenAfterLaunch(resolvedAgentId, providerLaunchConfig);
|
||||
for (const event of imported.providerSubagentEvents ?? []) {
|
||||
const update = await this.providerSubagents.apply(agent.id, event.provider, event.event);
|
||||
if (update) this.publishProviderSubagent(update);
|
||||
@@ -3017,6 +3035,7 @@ export class AgentManager {
|
||||
previousSessions,
|
||||
restoring: true,
|
||||
});
|
||||
this.syncAgentMcpTokenAfterLaunch(agentId, providerLaunchConfig);
|
||||
|
||||
await this.timeline.completeProviderSwitch(scope, intent.id);
|
||||
|
||||
@@ -3057,7 +3076,10 @@ export class AgentManager {
|
||||
targetSession: AgentSession | undefined;
|
||||
}): Promise<void> {
|
||||
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
|
||||
if (params.closedExisting) this.detachPluginTools(params.agentId);
|
||||
if (params.closedExisting) {
|
||||
this.detachPluginTools(params.agentId);
|
||||
this.mcpTokenRegistry.revoke(params.agentId);
|
||||
}
|
||||
this.restoreToolPolicyOnSwitchFailure(
|
||||
params.agentId,
|
||||
params.hadPreviousPaseoToolPolicy,
|
||||
@@ -3094,11 +3116,17 @@ export class AgentManager {
|
||||
* running keeps its plugin tools.
|
||||
*/
|
||||
private async launchAgent<T>(agentId: string, launch: () => Promise<T>): Promise<T> {
|
||||
this.launchingAgents.add(agentId);
|
||||
try {
|
||||
return await launch();
|
||||
} catch (error) {
|
||||
this.pluginSessions?.sessionLaunchFailed(agentId);
|
||||
if (!this.agents.has(agentId)) {
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
this.launchingAgents.delete(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3199,6 +3227,9 @@ export class AgentManager {
|
||||
lastError: preservedLastError,
|
||||
attention: preservedAttention,
|
||||
restoring: true,
|
||||
}).then((snapshot) => {
|
||||
this.syncAgentMcpTokenAfterLaunch(agentId, providerLaunchConfig);
|
||||
return snapshot;
|
||||
});
|
||||
return settleRewind
|
||||
? registered.then((snapshot) => this.settleRewindAfterResume(snapshot))
|
||||
@@ -3216,7 +3247,10 @@ export class AgentManager {
|
||||
} finally {
|
||||
if (!handedToRegistration) {
|
||||
// The closed agent drops its plugin record; a launch that never closed it leaves the rollback to launchAgent.
|
||||
if (closedExisting) this.detachPluginTools(agentId);
|
||||
if (closedExisting) {
|
||||
this.detachPluginTools(agentId);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
}
|
||||
if (hadPreviousPaseoToolPolicy) {
|
||||
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
|
||||
} else {
|
||||
@@ -3508,6 +3542,7 @@ export class AgentManager {
|
||||
persistError = error;
|
||||
}
|
||||
this.detachPluginTools(agentId);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
this.emitClosedAgent(closedAgent, {
|
||||
persist: false,
|
||||
emitState: persistError !== undefined ? true : options?.emitState,
|
||||
@@ -4324,6 +4359,7 @@ export class AgentManager {
|
||||
|
||||
this.paseoToolPolicies.delete(agentId);
|
||||
this.detachPluginTools(agentId);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
if (!nextRecord.internal) this.dispatchStoredAgentState(nextRecord);
|
||||
|
||||
await this.fireAgentArchived(agentId);
|
||||
@@ -6665,6 +6701,7 @@ export class AgentManager {
|
||||
private discardRuntimeState(agentId: string): void {
|
||||
this.paseoToolPolicies.delete(agentId);
|
||||
this.detachPluginTools(agentId);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
this.clearProviderBackgroundWork(agentId);
|
||||
this.runs.discardAgentHistory(agentId);
|
||||
}
|
||||
@@ -8219,12 +8256,16 @@ export class AgentManager {
|
||||
? this.resolvePaseoToolPolicy(storedConfig.provider)
|
||||
: { enabled: false };
|
||||
const generalEnabled = this.paseoToolsEnabled && isPaseoToolPolicyEnabled(paseoToolPolicy);
|
||||
const shouldInjectMcp =
|
||||
Boolean(this.mcpBaseUrl) &&
|
||||
(generalEnabled || voiceActive) &&
|
||||
!storedConfig.mcpServers?.[PASEO_MCP_SERVER_NAME];
|
||||
const mcpAuthToken = shouldInjectMcp ? this.mcpTokenRegistry.issue(agentId) : null;
|
||||
const launchConfig = this.applyDaemonAppendSystemPrompt(
|
||||
withRuntimePaseoMcpServer({
|
||||
config: storedConfig,
|
||||
agentId,
|
||||
mcpBaseUrl: generalEnabled || voiceActive ? this.mcpBaseUrl : null,
|
||||
mcpAuthToken: this.mcpAuthToken,
|
||||
mcpBaseUrl: shouldInjectMcp ? this.mcpBaseUrl : null,
|
||||
mcpAuthToken,
|
||||
}),
|
||||
);
|
||||
return { storedConfig, launchConfig, paseoToolPolicy };
|
||||
|
||||
@@ -18,6 +18,7 @@ import pino from "pino";
|
||||
|
||||
import { withTimeout } from "../../utils/promise-timeout.js";
|
||||
import { hashDaemonPassword } from "../auth.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { createPaseoDaemon, type PaseoDaemonConfig } from "../bootstrap.js";
|
||||
import type { SpeechService } from "../speech/speech-runtime.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
@@ -102,6 +103,7 @@ async function createMcpClient(url: string, authToken?: string): Promise<McpClie
|
||||
|
||||
interface OfflineDaemon {
|
||||
mcpUrl: string;
|
||||
localToken: string;
|
||||
stop: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -140,7 +142,12 @@ async function startOfflineDaemon(logger = pino({ level: "silent" })): Promise<O
|
||||
await stop();
|
||||
throw error;
|
||||
}
|
||||
return { mcpUrl: `http://127.0.0.1:${port}/mcp/agents`, stop };
|
||||
const localToken = readLocalCredential(paseoHome);
|
||||
if (!localToken) {
|
||||
await stop();
|
||||
throw new Error("Expected daemon local-credential to be written on startup");
|
||||
}
|
||||
return { mcpUrl: `http://127.0.0.1:${port}/_internal/mcp/agents`, localToken, stop };
|
||||
}
|
||||
|
||||
interface OfflineMcpDaemon {
|
||||
@@ -151,7 +158,7 @@ interface OfflineMcpDaemon {
|
||||
async function startOfflineMcpDaemon(): Promise<OfflineMcpDaemon> {
|
||||
const daemon = await startOfflineDaemon();
|
||||
try {
|
||||
const client = await createMcpClient(daemon.mcpUrl);
|
||||
const client = await createMcpClient(daemon.mcpUrl, daemon.localToken);
|
||||
return {
|
||||
client,
|
||||
stop: async () => {
|
||||
@@ -192,12 +199,20 @@ interface StandardMcpSession {
|
||||
async function runStandardMcpSession(
|
||||
mcpUrl: string,
|
||||
mode: VersionNegotiationMode,
|
||||
authToken?: string,
|
||||
): Promise<StandardMcpSession> {
|
||||
const client = new StandardMcpClient(
|
||||
{ name: "agent-mcp-e2e", version: "0.0.0" },
|
||||
{ versionNegotiation: { mode } },
|
||||
);
|
||||
await client.connect(new StandardMcpHttpTransport(new URL(mcpUrl)));
|
||||
await client.connect(
|
||||
new StandardMcpHttpTransport(
|
||||
new URL(mcpUrl),
|
||||
authToken
|
||||
? { requestInit: { headers: { Authorization: `Bearer ${authToken}` } } }
|
||||
: undefined,
|
||||
),
|
||||
);
|
||||
try {
|
||||
const tools = await client.listTools();
|
||||
const workspaces = await client.callTool({ name: "list_workspaces", arguments: {} });
|
||||
@@ -326,7 +341,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const client = await createMcpClient(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -417,9 +435,9 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const mcpUrl = `http://127.0.0.1:${port}/mcp/agents`;
|
||||
const capabilityToken = daemon.agentManager.getMcpAuthToken();
|
||||
expect(typeof capabilityToken).toBe("string");
|
||||
const mcpUrl = `http://127.0.0.1:${port}/_internal/mcp/agents`;
|
||||
const localToken = readLocalCredential(paseoHome);
|
||||
expect(typeof localToken).toBe("string");
|
||||
|
||||
let agentId: string | null = null;
|
||||
let client: McpClient | null = null;
|
||||
@@ -433,12 +451,9 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
});
|
||||
expect(unauthorized.status).toBe(401);
|
||||
|
||||
// The injected capability token authenticates the full MCP handshake:
|
||||
// creating (and connecting) the client and driving a tool call both go
|
||||
// through the password-gated /mcp/agents route. (The exact bearer header
|
||||
// injected into a child agent's config is covered by the
|
||||
// runtime-mcp-config unit test.)
|
||||
client = await createMcpClient(mcpUrl, capabilityToken!);
|
||||
// The local credential authenticates owner calls through the password-gated
|
||||
// /_internal/mcp/agents route, and the created agent receives its own capability token.
|
||||
client = await createMcpClient(mcpUrl, localToken!);
|
||||
const result = await client.callTool({
|
||||
name: "create_agent",
|
||||
args: {
|
||||
@@ -452,6 +467,16 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const payload = getStructuredContent(result);
|
||||
agentId = typeof payload?.agentId === "string" ? payload.agentId : null;
|
||||
expect(agentId).toBeTruthy();
|
||||
|
||||
const agentToken = daemon.agentManager.getAgentMcpToken(agentId!);
|
||||
expect(agentToken).toBeTruthy();
|
||||
const agentClient = await createMcpClient(mcpUrl, agentToken!);
|
||||
try {
|
||||
const listed = await agentClient.callTool({ name: "list_workspaces", args: {} });
|
||||
expect(listed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await agentClient.close();
|
||||
}
|
||||
} finally {
|
||||
if (agentId) {
|
||||
await client?.callTool({ name: "kill_agent", args: { agentId } });
|
||||
@@ -486,7 +511,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const client = await createMcpClient(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
|
||||
const disabledPaseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-home-disabled-"));
|
||||
const disabledStaticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-disabled-"));
|
||||
@@ -508,7 +536,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const disabledDaemon = await createPaseoDaemon(disabledDaemonConfig, pino({ level: "silent" }));
|
||||
await disabledDaemon.start();
|
||||
|
||||
const disabledClient = await createMcpClient(`http://127.0.0.1:${disabledPort}/mcp/agents`);
|
||||
const disabledClient = await createMcpClient(
|
||||
`http://127.0.0.1:${disabledPort}/_internal/mcp/agents`,
|
||||
readLocalCredential(disabledPaseoHome)!,
|
||||
);
|
||||
|
||||
let agentId: string | null = null;
|
||||
let disabledAgentId: string | null = null;
|
||||
@@ -530,7 +561,8 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
expect(recorder.recordedLaunches.at(-1)?.mcpServers).toMatchObject({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:${port}/mcp/agents?callerAgentId=${agentId!}`,
|
||||
url: `http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
headers: { Authorization: `Bearer ${daemon.agentManager.getAgentMcpToken(agentId!)}` },
|
||||
},
|
||||
});
|
||||
const injectedAgent = daemon.agentManager.getAgent(agentId!);
|
||||
@@ -577,8 +609,8 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
test("tool settings saved by a client change the agent's MCP catalog without a restart", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const agentCwd = await mkdtemp(path.join(os.tmpdir(), "paseo-agent-cwd-tools-"));
|
||||
const mcpUrl = `http://127.0.0.1:${daemon.port}/mcp/agents`;
|
||||
const client = await createMcpClient(mcpUrl);
|
||||
const mcpUrl = `http://127.0.0.1:${daemon.port}/_internal/mcp/agents`;
|
||||
const client = await createMcpClient(mcpUrl, readLocalCredential(daemon.paseoHome)!);
|
||||
const settingsClient = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.18.2",
|
||||
@@ -586,8 +618,11 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
let agentId: string | null = null;
|
||||
async function agentToolNames(): Promise<string[]> {
|
||||
const agentClient = new StandardMcpClient({ name: "agent-mcp-e2e", version: "0.0.0" });
|
||||
const agentToken = daemon.daemon.agentManager.getAgentMcpToken(agentId!);
|
||||
await agentClient.connect(
|
||||
new StandardMcpHttpTransport(new URL(`${mcpUrl}?callerAgentId=${agentId!}`)),
|
||||
new StandardMcpHttpTransport(new URL(mcpUrl), {
|
||||
requestInit: { headers: { Authorization: `Bearer ${agentToken!}` } },
|
||||
}),
|
||||
);
|
||||
try {
|
||||
return (await agentClient.listTools()).tools.map((tool) => tool.name);
|
||||
@@ -653,7 +688,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const client = await createMcpClient(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -674,7 +712,8 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
expect(recorder.recordedLaunches.at(-1)?.mcpServers).toMatchObject({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:${port}/mcp/agents?callerAgentId=${agentId!}`,
|
||||
url: `http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
headers: { Authorization: `Bearer ${daemon.agentManager.getAgentMcpToken(agentId!)}` },
|
||||
},
|
||||
});
|
||||
const injectedAgent = daemon.agentManager.getAgent(agentId!);
|
||||
@@ -746,13 +785,13 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
|
||||
const mcpUrl = new URL(injectedMcp.url);
|
||||
expect(mcpUrl.hostname).toBe("127.0.0.1");
|
||||
expect(mcpUrl.pathname).toBe("/mcp/agents");
|
||||
expect(mcpUrl.searchParams.get("callerAgentId")).toBe(agentId);
|
||||
expect(mcpUrl.pathname).toBe("/_internal/mcp/agents");
|
||||
expect(mcpUrl.searchParams.has("callerAgentId")).toBe(false);
|
||||
loopbackPort = Number(mcpUrl.port);
|
||||
expect(loopbackPort).toBeGreaterThan(0);
|
||||
|
||||
// Capability token auth is enforced on the internal loopback endpoint.
|
||||
const unauthorized = await fetch(`http://127.0.0.1:${loopbackPort}/mcp/agents`, {
|
||||
const unauthorized = await fetch(`http://127.0.0.1:${loopbackPort}/_internal/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: "{}",
|
||||
@@ -769,7 +808,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port: loopbackPort!,
|
||||
path: "/mcp/agents",
|
||||
path: "/_internal/mcp/agents",
|
||||
method: "POST",
|
||||
headers: {
|
||||
host: `evil.example:${loopbackPort!}`,
|
||||
@@ -787,7 +826,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
expect(badHostStatus).toBe(403);
|
||||
|
||||
// Authenticated MCP calls work end-to-end against the loopback endpoint.
|
||||
const capabilityToken = daemon.agentManager.getMcpAuthToken();
|
||||
const capabilityToken = daemon.agentManager.getAgentMcpToken(agentId);
|
||||
expect(typeof capabilityToken).toBe("string");
|
||||
expect(injectedMcp.headers?.Authorization).toBe(`Bearer ${capabilityToken!}`);
|
||||
mcpClient = await createMcpClient(injectedMcp.url, capabilityToken!);
|
||||
@@ -893,7 +932,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const client = await createMcpClient(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -1073,7 +1115,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const client = await createMcpClient(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await client.callTool({
|
||||
@@ -1120,7 +1165,10 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
const daemon = await createPaseoDaemon(daemonConfig, pino({ level: "silent" }));
|
||||
await daemon.start();
|
||||
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const client = await createMcpClient(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -1216,7 +1264,11 @@ describe("agent MCP protocol negotiation", () => {
|
||||
test("a client pinned to 2026-07-28 lists and calls tools", async () => {
|
||||
const daemon = await startOfflineDaemon();
|
||||
try {
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, { pin: "2026-07-28" });
|
||||
const session = await runStandardMcpSession(
|
||||
daemon.mcpUrl,
|
||||
{ pin: "2026-07-28" },
|
||||
daemon.localToken,
|
||||
);
|
||||
expect(session.negotiatedProtocolVersion).toBe("2026-07-28");
|
||||
expect(session.toolNames).toEqual(expect.arrayContaining(["create_agent", "update_agent"]));
|
||||
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
|
||||
@@ -1229,7 +1281,7 @@ describe("agent MCP protocol negotiation", () => {
|
||||
const { logger, logs } = createCapturingLogger();
|
||||
const daemon = await startOfflineDaemon(logger);
|
||||
try {
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "auto");
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "auto", daemon.localToken);
|
||||
expect(session.negotiatedProtocolVersion).toBe("2026-07-28");
|
||||
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
|
||||
expect(logs.filter((log) => log.msg === "Agent MCP transport error")).toEqual([]);
|
||||
@@ -1241,7 +1293,7 @@ describe("agent MCP protocol negotiation", () => {
|
||||
test("a legacy client still initializes over a 2025 protocol version", async () => {
|
||||
const daemon = await startOfflineDaemon();
|
||||
try {
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "legacy");
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "legacy", daemon.localToken);
|
||||
expect(session.negotiatedProtocolVersion).toMatch(/^2025-/);
|
||||
expect(session.toolNames).toEqual(expect.arrayContaining(["create_agent", "update_agent"]));
|
||||
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
|
||||
@@ -1537,11 +1589,19 @@ describe("voice-only speak MCP delivery", () => {
|
||||
);
|
||||
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
|
||||
|
||||
// When mcp.enabled=false, non-voice /mcp/agents requests still get 404.
|
||||
// When mcp.enabled=false, authenticated non-voice /_internal/mcp/agents requests still get 404.
|
||||
const localToken = readLocalCredential(paseoHome)!;
|
||||
if (!mcpEnabled) {
|
||||
const nonVoiceRes = await fetch(
|
||||
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${localToken}`,
|
||||
},
|
||||
body: "{}",
|
||||
},
|
||||
);
|
||||
expect(nonVoiceRes.status).toBe(404);
|
||||
}
|
||||
@@ -1557,7 +1617,7 @@ describe("voice-only speak MCP delivery", () => {
|
||||
|
||||
const { toolNames } = await listMcpToolsAndCallSpeak(
|
||||
injected.url,
|
||||
daemon.agentManager.getMcpAuthToken(),
|
||||
daemon.agentManager.getAgentMcpToken(claudeAgent.id),
|
||||
"Hello from voice mode",
|
||||
);
|
||||
expect(toolNames).toEqual(["speak"]);
|
||||
@@ -1576,8 +1636,15 @@ describe("voice-only speak MCP delivery", () => {
|
||||
await expect(wsClient.setVoiceMode(true, unsupportedAgent.id)).rejects.toThrow(/speak/i);
|
||||
if (!mcpEnabled) {
|
||||
const rejectedRes = await fetch(
|
||||
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
|
||||
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${localToken}`,
|
||||
},
|
||||
body: "{}",
|
||||
},
|
||||
);
|
||||
expect(rejectedRes.status).toBe(404);
|
||||
}
|
||||
|
||||
@@ -132,9 +132,9 @@ async function startAgentMcpServer(logger: pino.Logger): Promise<AgentMcpServerH
|
||||
void runAgentMcpRequest(req, res);
|
||||
};
|
||||
|
||||
app.post("/mcp/agents", handleAgentMcpRequest);
|
||||
app.get("/mcp/agents", handleAgentMcpRequest);
|
||||
app.delete("/mcp/agents", handleAgentMcpRequest);
|
||||
app.post("/_internal/mcp/agents", handleAgentMcpRequest);
|
||||
app.get("/_internal/mcp/agents", handleAgentMcpRequest);
|
||||
app.delete("/_internal/mcp/agents", handleAgentMcpRequest);
|
||||
|
||||
const port = await new Promise<number>((resolve) => {
|
||||
httpServer.listen(0, () => {
|
||||
@@ -144,7 +144,7 @@ async function startAgentMcpServer(logger: pino.Logger): Promise<AgentMcpServerH
|
||||
});
|
||||
|
||||
mcpAllowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
|
||||
const url = `http://127.0.0.1:${port}/mcp/agents`;
|
||||
const url = `http://127.0.0.1:${port}/_internal/mcp/agents`;
|
||||
|
||||
return {
|
||||
url,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
AgentSnapshotPayloadSchema,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { CodexAppServerAgentClient } from "./providers/codex-app-server-agent.js";
|
||||
@@ -50,8 +51,14 @@ test.each(["codex", "claude"] as const)(
|
||||
StatusSchema.parse(await call("get_agent_status", { agentId })).snapshot;
|
||||
try {
|
||||
await client.connect();
|
||||
const localToken = readLocalCredential(daemon.paseoHome);
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${daemon.port}/mcp/agents`)),
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${daemon.port}/_internal/mcp/agents`),
|
||||
{
|
||||
requestInit: { headers: { Authorization: `Bearer ${localToken!}` } },
|
||||
},
|
||||
),
|
||||
);
|
||||
const realModel = provider === "codex" ? "gpt-5.6-sol" : "haiku";
|
||||
const agent = await client.createAgent({
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { AgentStreamEvent } from "../agent-sdk-types.js";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { parentAddressLabels } from "@getpaseo/protocol/agent-labels";
|
||||
import type { AgentActiveTurnBehavior, AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentActiveTurnBehavior,
|
||||
AgentSnapshotPayload,
|
||||
DaemonPermission,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
@@ -12,7 +16,6 @@ import {
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonTransportFactory } from "@getpaseo/client/internal/daemon-client-transport-types";
|
||||
import type { HostDirectory } from "@getpaseo/protocol/hosts";
|
||||
import { OWNER_PERMISSIONS } from "../../authorization/index.js";
|
||||
import type { ConnectedHosts } from "../../connected-hosts/index.js";
|
||||
import { resolveRequiredProviderModel } from "../mcp-shared.js";
|
||||
import { selectAgentListItems } from "../agent-projections.js";
|
||||
@@ -92,8 +95,15 @@ export interface ToolHosts {
|
||||
): Promise<T>;
|
||||
}
|
||||
|
||||
/** Daemon MCP has the daemon's authority, bounded by the destination's admission of its link. */
|
||||
export function createToolHosts(hosts: ConnectedHosts): ToolHosts {
|
||||
/**
|
||||
* Routes MCP tool calls to connected hosts with the caller's authority. The destination then
|
||||
* bounds it further by its admission of the link. Agent MCP holds every permission; MCP Server
|
||||
* passes the permissions of the caller's credential (or default permissions when auth is off).
|
||||
*/
|
||||
export function createToolHosts(
|
||||
hosts: ConnectedHosts,
|
||||
permissions: readonly DaemonPermission[],
|
||||
): ToolHosts {
|
||||
return {
|
||||
directory: () => hosts.list(),
|
||||
async use(serverId, action, signal) {
|
||||
@@ -112,7 +122,7 @@ export function createToolHosts(hosts: ConnectedHosts): ToolHosts {
|
||||
scopeId: randomUUID(),
|
||||
sourceId: "mcp",
|
||||
originSessionId: "mcp",
|
||||
permissions: OWNER_PERMISSIONS,
|
||||
permissions,
|
||||
signal: signal ? AbortSignal.any([lifetime.signal, signal]) : lifetime.signal,
|
||||
frame: (data) => {
|
||||
for (const listener of messages) listener(data, typeof data !== "string");
|
||||
|
||||
@@ -8,6 +8,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
|
||||
import { z } from "zod";
|
||||
|
||||
import { AGENT_WAIT_TIMEOUT_MS } from "./mcp-shared.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import type { AgentClient, AgentProvider, AgentSessionConfig } from "./agent-sdk-types.js";
|
||||
@@ -60,7 +61,7 @@ function formatHostForHttpUrl(host: string): string {
|
||||
|
||||
function buildExpectedAgentMcpUrl(params: { host: string; port: number; agentId: string }): string {
|
||||
const baseUrl = new URL(
|
||||
"/mcp/agents",
|
||||
"/_internal/mcp/agents",
|
||||
`http://${formatHostForHttpUrl(params.host)}:${params.port}`,
|
||||
);
|
||||
baseUrl.searchParams.set("callerAgentId", params.agentId);
|
||||
@@ -83,8 +84,10 @@ function getStructuredContent(result: McpToolResult): StructuredContent | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function createMcpClient(url: string): Promise<McpClient> {
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url));
|
||||
async function createMcpClient(url: string, authToken: string): Promise<McpClient> {
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: { headers: { Authorization: `Bearer ${authToken}` } },
|
||||
});
|
||||
const rawClient = await experimental_createMCPClient({ transport });
|
||||
const boundCallTool: McpClient["callTool"] = Reflect.get(rawClient, "callTool").bind(rawClient);
|
||||
const boundListTools: McpClient["listTools"] = Reflect.get(rawClient, "listTools").bind(
|
||||
@@ -281,7 +284,11 @@ beforeAll(async () => {
|
||||
agentClients: createRecordingAgentClients(),
|
||||
agentProfiles: [seededAgentProfile],
|
||||
});
|
||||
topLevelClient = await createMcpClient(`http://127.0.0.1:${daemonHandle.port}/mcp/agents`);
|
||||
const localToken = readLocalCredential(daemonHandle.paseoHome)!;
|
||||
topLevelClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents`,
|
||||
localToken,
|
||||
);
|
||||
|
||||
const parentPayload = await callToolStructured(topLevelClient, "create_agent", {
|
||||
relationship: { kind: "detached" },
|
||||
@@ -294,7 +301,8 @@ beforeAll(async () => {
|
||||
parentAgentId = str(parentPayload.agentId);
|
||||
|
||||
agentScopedClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${parentAgentId}`,
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${parentAgentId}`,
|
||||
localToken,
|
||||
);
|
||||
|
||||
execSync("git init -b main", { cwd: worktreeRepoCwd, stdio: "pipe" });
|
||||
@@ -366,6 +374,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
port: daemon.port,
|
||||
agentId: caller.id,
|
||||
}),
|
||||
readLocalCredential(daemon.paseoHome)!,
|
||||
);
|
||||
const created = await callToolStructured(mcp, "create_agent", {
|
||||
relationship: { kind: relationship },
|
||||
@@ -485,6 +494,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
});
|
||||
mcp = await createMcpClient(
|
||||
buildExpectedAgentMcpUrl({ host: "127.0.0.1", port: daemon.port, agentId: parent.id }),
|
||||
readLocalCredential(daemon.paseoHome)!,
|
||||
);
|
||||
const created = await callToolStructured(mcp, "create_agent", {
|
||||
relationship: { kind: "subagent" },
|
||||
@@ -655,11 +665,12 @@ describe("Suite A: Core Fixes", () => {
|
||||
);
|
||||
agentId = snapshot.id;
|
||||
|
||||
const expectedUrl = buildExpectedAgentMcpUrl({
|
||||
host: listenTarget!.host,
|
||||
port: listenTarget!.port,
|
||||
agentId,
|
||||
});
|
||||
const expectedUrl = new URL(
|
||||
"/_internal/mcp/agents",
|
||||
`http://${formatHostForHttpUrl(listenTarget!.host)}:${listenTarget!.port}`,
|
||||
).toString();
|
||||
const expectedToken = daemonHandle.daemon.agentManager.getAgentMcpToken(agentId);
|
||||
expect(expectedToken).toBeTruthy();
|
||||
|
||||
const launchConfig = launchConfigsByProvider.claude
|
||||
?.toReversed()
|
||||
@@ -668,6 +679,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: expectedUrl,
|
||||
headers: { Authorization: `Bearer ${expectedToken!}` },
|
||||
},
|
||||
});
|
||||
expect(snapshot.config.mcpServers?.paseo).toBeUndefined();
|
||||
@@ -695,7 +707,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
try {
|
||||
agentId = await createTopLevelAgent({ settings: { features: { test_feature: true } } });
|
||||
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
|
||||
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
|
||||
expect(internalSnapshot?.config.providerOptions).toEqual({ test_feature: true });
|
||||
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
|
||||
@@ -713,7 +725,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
settings: { features: { test_feature: true } },
|
||||
});
|
||||
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
|
||||
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
|
||||
expect(internalSnapshot?.config.providerOptions).toEqual({ test_feature: true });
|
||||
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
|
||||
@@ -733,7 +745,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
});
|
||||
expect(updated.success).toBe(true);
|
||||
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
|
||||
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
|
||||
expect(internalSnapshot?.config.providerOptions).toEqual({ test_feature: true });
|
||||
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
|
||||
@@ -1155,7 +1167,7 @@ describe("Suite D: Provider Tools", () => {
|
||||
test("list_profiles returns configured agent profiles, including notes", async () => {
|
||||
const payload = await callToolStructured(topLevelClient, "list_profiles");
|
||||
const profiles = recordArr(payload.profiles);
|
||||
expect(profiles).toEqual([seededAgentProfile]);
|
||||
expect(profiles).toEqual([{ ...seededAgentProfile, options: null, thinkingOptionId: null }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1219,7 +1231,8 @@ describe("Suite E: Workspace Tools", () => {
|
||||
});
|
||||
const agentId = str(child.agentId);
|
||||
const workerClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${agentId}`,
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${agentId}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
);
|
||||
let terminalId: string;
|
||||
try {
|
||||
@@ -1271,7 +1284,8 @@ describe("Suite E: Workspace Tools", () => {
|
||||
initialPrompt: "Say done.",
|
||||
});
|
||||
scoped = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${str(parent.agentId)}`,
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${str(parent.agentId)}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
);
|
||||
const inherited = await callToolStructured(scoped, "create_workspace", {
|
||||
isolation: "local",
|
||||
@@ -1362,7 +1376,8 @@ describe("Suite E: Workspace Tools", () => {
|
||||
initialPrompt: "Say done.",
|
||||
});
|
||||
scoped = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${str(child.agentId)}`,
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${str(child.agentId)}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
);
|
||||
|
||||
// Omit workspaceId to update caller's workspace; clear body with null and update issues.
|
||||
@@ -1440,7 +1455,8 @@ describe("Suite E: Workspace Tools", () => {
|
||||
daemonHandle.daemon.agentManager.getAgent(agentId)?.background;
|
||||
expect(background(callerId)).toBe(true);
|
||||
const scoped = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${callerId}`,
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${callerId}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
);
|
||||
const ownedWorkspaces: string[] = [];
|
||||
try {
|
||||
@@ -1501,6 +1517,7 @@ describe("Suite E: Workspace Tools", () => {
|
||||
});
|
||||
mcp = await createMcpClient(
|
||||
buildExpectedAgentMcpUrl({ host: "127.0.0.1", port: daemon.port, agentId: caller.id }),
|
||||
readLocalCredential(daemon.paseoHome)!,
|
||||
);
|
||||
const created = await callToolStructured(mcp, "create_agent", {
|
||||
relationship: { kind: "subagent" },
|
||||
|
||||
@@ -8663,7 +8663,7 @@ describe("modern MCP protocol (2026-07-28)", () => {
|
||||
// covers the modern path: widening the accepted version list alone would
|
||||
// keep the legacy tests green without serving it.
|
||||
const modernRequest = (id: number, method: string): Request =>
|
||||
new Request("http://localhost/mcp/agents", {
|
||||
new Request("http://localhost/_internal/mcp/agents", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
|
||||
import { addModelVisibleStructuredContent } from "./tools/paseo-tool-serialization.js";
|
||||
import { createPaseoToolCatalog, type PaseoToolHostDependencies } from "./tools/paseo-tools.js";
|
||||
import type { PaseoToolResult } from "./tools/types.js";
|
||||
import type { PaseoToolCatalog, PaseoToolResult } from "./tools/types.js";
|
||||
|
||||
export type AgentMcpServerOptions = PaseoToolHostDependencies;
|
||||
|
||||
@@ -28,11 +28,19 @@ function toMcpToolResult(result: PaseoToolResult): CallToolResult {
|
||||
}
|
||||
|
||||
export async function createAgentMcpServer(options: AgentMcpServerOptions): Promise<McpServer> {
|
||||
const catalog = await createPaseoToolCatalog(options);
|
||||
const server = new McpServer({
|
||||
return createPaseoMcpServer(await createPaseoToolCatalog(options), {
|
||||
name: "agent-mcp",
|
||||
version: "2.0.0",
|
||||
});
|
||||
}
|
||||
|
||||
/** An MCP server that serves exactly the tools in `catalog`, even when it has none. */
|
||||
export function createPaseoMcpServer(
|
||||
catalog: PaseoToolCatalog,
|
||||
info: { name: string; version: string },
|
||||
): McpServer {
|
||||
// Declaring the capability up front keeps tools/list answering with an empty list.
|
||||
const server = new McpServer(info, { capabilities: { tools: {} } });
|
||||
|
||||
for (const tool of catalog.tools.values()) {
|
||||
server.registerTool(
|
||||
|
||||
@@ -0,0 +1,415 @@
|
||||
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { hashDaemonPassword } from "../auth.js";
|
||||
import { DaemonPasswordStore } from "../auth/daemon-password-store.js";
|
||||
import { PasswordAttemptLimiter } from "../auth/password-attempt-limiter.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import type { AgentSessionConfig } from "./agent-sdk-types.js";
|
||||
|
||||
const MCP_INIT_BODY = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: "2025-03-26",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "mcp-auth-test", version: "1.0.0" },
|
||||
},
|
||||
});
|
||||
|
||||
async function connectMcpClient(url: string, token?: string): Promise<Client> {
|
||||
const client = new Client({ name: "mcp-token-auth-test", version: "1.0.0" });
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
new URL(url),
|
||||
token
|
||||
? {
|
||||
requestInit: {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
await client.connect(transport);
|
||||
return client;
|
||||
}
|
||||
|
||||
describe("Agent MCP per-agent capability token authentication", () => {
|
||||
const daemons: TestPaseoDaemon[] = [];
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (daemons.length > 0) {
|
||||
await daemons.pop()!.close();
|
||||
}
|
||||
while (tempDirs.length > 0) {
|
||||
await rm(tempDirs.pop()!, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
async function makeWorkdir(): Promise<string> {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-mcp-auth-"));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
test("rejects unauthenticated requests with 401 on passwordless, password-protected, and mcp-disabled daemons", async () => {
|
||||
const passwordless = await createTestPaseoDaemon({ mcpEnabled: true });
|
||||
const passwordProtected = await createTestPaseoDaemon({
|
||||
mcpEnabled: true,
|
||||
auth: { password: hashDaemonPassword("secret-pass") },
|
||||
});
|
||||
const disabledMcp = await createTestPaseoDaemon({ mcpEnabled: false });
|
||||
daemons.push(passwordless, passwordProtected, disabledMcp);
|
||||
|
||||
for (const daemon of [passwordless, passwordProtected, disabledMcp]) {
|
||||
const url = `http://127.0.0.1:${daemon.port}/_internal/mcp/agents`;
|
||||
const missingAuth = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(missingAuth.status).toBe(401);
|
||||
|
||||
const unknownAuth = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: "Bearer unknown-token",
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(unknownAuth.status).toBe(401);
|
||||
}
|
||||
|
||||
const ownerToken = readLocalCredential(passwordless.paseoHome);
|
||||
const legacy = await fetch(`http://127.0.0.1:${passwordless.port}/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", Authorization: `Bearer ${ownerToken}` },
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(legacy.status).toBe(404);
|
||||
|
||||
// Authenticated owner caller observes 404 when mcpEnabled=false.
|
||||
const disabledLocalToken = readLocalCredential(disabledMcp.paseoHome);
|
||||
expect(disabledLocalToken).toBeTruthy();
|
||||
const disabledAuth = await fetch(`http://127.0.0.1:${disabledMcp.port}/_internal/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${disabledLocalToken!}`,
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(disabledAuth.status).toBe(404);
|
||||
});
|
||||
|
||||
test("binds callerAgentId, paseoToolPolicy, and agent-caller-policy from the per-agent token without query params and rejects mismatched callerAgentId", async () => {
|
||||
const workdir = await makeWorkdir();
|
||||
const launches: Array<{ provider: string; config: AgentSessionConfig }> = [];
|
||||
const baseClients = createTestAgentClients();
|
||||
const wrappedClaude = new Proxy(baseClients.claude, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "createSession") {
|
||||
return (
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: Parameters<typeof target.createSession>[1],
|
||||
options?: Parameters<typeof target.createSession>[2],
|
||||
) => {
|
||||
launches.push({ provider: "claude", config });
|
||||
return target.createSession(config, launchContext, options);
|
||||
};
|
||||
}
|
||||
const value = Reflect.get(target, prop, receiver);
|
||||
return typeof value === "function" ? value.bind(target) : value;
|
||||
},
|
||||
});
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
mcpEnabled: true,
|
||||
agentClients: { ...baseClients, claude: wrappedClaude },
|
||||
providerOverrides: {
|
||||
claude: {
|
||||
paseoTools: {
|
||||
disabledTools: ["list_hosts"],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
daemons.push(daemon);
|
||||
|
||||
const agentA = await daemon.daemon.agentManager.createAgent(
|
||||
{ provider: "claude", cwd: workdir, modeId: "plan" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const agentB = await daemon.daemon.agentManager.createAgent(
|
||||
{ provider: "claude", cwd: workdir, modeId: "bypassPermissions" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
const tokenA = daemon.daemon.agentManager.getAgentMcpToken(agentA.id);
|
||||
const tokenB = daemon.daemon.agentManager.getAgentMcpToken(agentB.id);
|
||||
expect(tokenA).toBeTruthy();
|
||||
expect(tokenB).toBeTruthy();
|
||||
expect(tokenA).not.toBe(tokenB);
|
||||
|
||||
// Injected URL omits ?callerAgentId= and carries the per-agent bearer token.
|
||||
const launchA = launches[0]?.config.mcpServers?.paseo;
|
||||
expect(launchA).toEqual({
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:${daemon.port}/_internal/mcp/agents`,
|
||||
headers: { Authorization: `Bearer ${tokenA!}` },
|
||||
});
|
||||
|
||||
// Persisted agent JSON on disk must never contain capability tokens or internal paseo MCP server.
|
||||
await daemon.daemon.agentStorage.flush();
|
||||
const agentsDir = path.join(daemon.paseoHome, "agents");
|
||||
const agentFiles = (await readdir(agentsDir, { recursive: true })).filter((entry) =>
|
||||
entry.endsWith(".json"),
|
||||
);
|
||||
expect(agentFiles.length).toBeGreaterThanOrEqual(2);
|
||||
for (const file of agentFiles) {
|
||||
const content = await readFile(path.join(agentsDir, file), "utf8");
|
||||
expect(content).not.toContain(tokenA!);
|
||||
expect(content).not.toContain(tokenB!);
|
||||
expect(content).not.toContain("/_internal/mcp/agents");
|
||||
}
|
||||
|
||||
// Mismatched ?callerAgentId= is rejected with 403 Forbidden.
|
||||
const mismatched = await fetch(
|
||||
`http://127.0.0.1:${daemon.port}/_internal/mcp/agents?callerAgentId=${agentB.id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${tokenA!}`,
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
},
|
||||
);
|
||||
expect(mismatched.status).toBe(403);
|
||||
|
||||
// Connecting with ONLY Bearer <tokenA> (no query string) binds callerAgentId=agentA.id,
|
||||
// applies claude's paseoToolPolicy (list_hosts disabled), and enforces agent-caller-policy.
|
||||
const mcpA = await connectMcpClient(
|
||||
`http://127.0.0.1:${daemon.port}/_internal/mcp/agents`,
|
||||
tokenA!,
|
||||
);
|
||||
try {
|
||||
const { tools } = await mcpA.listTools();
|
||||
const toolNames = tools.map((tool) => tool.name);
|
||||
expect(toolNames).not.toContain("list_hosts");
|
||||
expect(toolNames).toContain("update_agent");
|
||||
expect(toolNames).toContain("set_agent_mode");
|
||||
|
||||
// Agent A cannot update unrelated Agent B (lineage enforced via token-bound callerAgentId).
|
||||
const updateOther = await mcpA.callTool({
|
||||
name: "update_agent",
|
||||
arguments: { agentId: agentB.id, name: "hijacked" },
|
||||
});
|
||||
expect(updateOther.isError).toBe(true);
|
||||
expect(JSON.stringify(updateOther.content)).toMatch(/descendant/i);
|
||||
|
||||
// Agent A (in "plan" mode) cannot escalate its own mode to "bypassPermissions" (ceiling enforced).
|
||||
const escalateSelf = await mcpA.callTool({
|
||||
name: "set_agent_mode",
|
||||
arguments: { agentId: agentA.id, modeId: "bypassPermissions" },
|
||||
});
|
||||
expect(escalateSelf.isError).toBe(true);
|
||||
expect(JSON.stringify(escalateSelf.content)).toMatch(/mode|ceiling|plan/i);
|
||||
} finally {
|
||||
await mcpA.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("revokes tokens immediately on close, archive, and delete, and mints a fresh token on resume", async () => {
|
||||
const workdir = await makeWorkdir();
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: true });
|
||||
daemons.push(daemon);
|
||||
|
||||
const mcpUrl = `http://127.0.0.1:${daemon.port}/_internal/mcp/agents`;
|
||||
|
||||
// 1. Close -> old token immediately returns 401; resume -> mints fresh working token.
|
||||
const closable = await daemon.daemon.agentManager.createAgent(
|
||||
{ provider: "claude", cwd: workdir },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const originalToken = daemon.daemon.agentManager.getAgentMcpToken(closable.id);
|
||||
expect(originalToken).toBeTruthy();
|
||||
const persistence = closable.persistence;
|
||||
expect(persistence).toBeTruthy();
|
||||
|
||||
await daemon.daemon.agentManager.closeAgent(closable.id);
|
||||
expect(daemon.daemon.agentManager.getAgentMcpToken(closable.id)).toBeNull();
|
||||
|
||||
const afterClose = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${originalToken!}`,
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(afterClose.status).toBe(401);
|
||||
|
||||
await daemon.daemon.agentManager.resumeAgentFromPersistence(
|
||||
persistence!,
|
||||
{ cwd: workdir },
|
||||
closable.id,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const resumedToken = daemon.daemon.agentManager.getAgentMcpToken(closable.id);
|
||||
expect(resumedToken).toBeTruthy();
|
||||
expect(resumedToken).not.toBe(originalToken);
|
||||
|
||||
// Old token still rejected after resume.
|
||||
const oldAfterResume = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${originalToken!}`,
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(oldAfterResume.status).toBe(401);
|
||||
|
||||
// New token authenticates cleanly.
|
||||
const resumedClient = await connectMcpClient(mcpUrl, resumedToken!);
|
||||
try {
|
||||
const { tools } = await resumedClient.listTools();
|
||||
expect(tools.length).toBeGreaterThan(0);
|
||||
} finally {
|
||||
await resumedClient.close();
|
||||
}
|
||||
|
||||
// 2. Archive -> token immediately returns 401.
|
||||
await daemon.daemon.agentManager.archiveAgent(closable.id);
|
||||
expect(daemon.daemon.agentManager.getAgentMcpToken(closable.id)).toBeNull();
|
||||
const afterArchive = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${resumedToken!}`,
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(afterArchive.status).toBe(401);
|
||||
|
||||
// 3. Delete state -> token immediately returns 401.
|
||||
const deletable = await daemon.daemon.agentManager.createAgent(
|
||||
{ provider: "claude", cwd: workdir },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const deletableToken = daemon.daemon.agentManager.getAgentMcpToken(deletable.id);
|
||||
expect(deletableToken).toBeTruthy();
|
||||
await daemon.daemon.agentManager.deleteAgentState(deletable.id);
|
||||
expect(daemon.daemon.agentManager.getAgentMcpToken(deletable.id)).toBeNull();
|
||||
const afterDelete = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${deletableToken!}`,
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(afterDelete.status).toBe(401);
|
||||
});
|
||||
|
||||
test("authenticates localCredential and daemon password as owner and returns 429 when password verification is throttled", async () => {
|
||||
let releaseCompare!: () => void;
|
||||
let compareStarted!: () => void;
|
||||
const compareStartedPromise = new Promise<void>((resolve) => {
|
||||
compareStarted = resolve;
|
||||
});
|
||||
const compareGate = new Promise<void>((resolve) => {
|
||||
releaseCompare = resolve;
|
||||
});
|
||||
|
||||
const passwordHash = hashDaemonPassword("owner-secret");
|
||||
const limiter = new PasswordAttemptLimiter({ maxConcurrent: 1, maxQueued: 0 });
|
||||
let holdFirstWrong = false;
|
||||
const passwordStore = new DaemonPasswordStore({
|
||||
initialHash: passwordHash,
|
||||
limiter,
|
||||
comparePassword: async (candidate, hash) => {
|
||||
if (holdFirstWrong && candidate === "slow-wrong") {
|
||||
holdFirstWrong = false;
|
||||
compareStarted();
|
||||
await compareGate;
|
||||
return false;
|
||||
}
|
||||
return candidate === "owner-secret" && hash === passwordHash;
|
||||
},
|
||||
});
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
mcpEnabled: true,
|
||||
auth: {
|
||||
password: passwordHash,
|
||||
passwordStore,
|
||||
getPasswordHash: () => passwordStore.getPasswordHash(),
|
||||
verifyPassword: (candidate) => passwordStore.verify(candidate),
|
||||
},
|
||||
});
|
||||
daemons.push(daemon);
|
||||
|
||||
const mcpUrl = `http://127.0.0.1:${daemon.port}/_internal/mcp/agents`;
|
||||
const localToken = readLocalCredential(daemon.paseoHome);
|
||||
expect(localToken).toBeTruthy();
|
||||
|
||||
// Local credential authenticates as owner.
|
||||
const localClient = await connectMcpClient(mcpUrl, localToken!);
|
||||
try {
|
||||
const { tools } = await localClient.listTools();
|
||||
expect(tools.some((tool) => tool.name === "list_agents")).toBe(true);
|
||||
} finally {
|
||||
await localClient.close();
|
||||
}
|
||||
|
||||
// Daemon password authenticates as owner.
|
||||
const passwordClient = await connectMcpClient(mcpUrl, "owner-secret");
|
||||
try {
|
||||
const { tools } = await passwordClient.listTools();
|
||||
expect(tools.some((tool) => tool.name === "list_agents")).toBe(true);
|
||||
} finally {
|
||||
await passwordClient.close();
|
||||
}
|
||||
|
||||
// Throttled password attempt returns 429 Too Many Requests.
|
||||
holdFirstWrong = true;
|
||||
const firstAttempt = fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: "Bearer slow-wrong",
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
await compareStartedPromise;
|
||||
|
||||
const throttledAttempt = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: "Bearer owner-secret",
|
||||
},
|
||||
body: MCP_INIT_BODY,
|
||||
});
|
||||
expect(throttledAttempt.status).toBe(429);
|
||||
|
||||
releaseCompare();
|
||||
expect((await firstAttempt).status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { AgentMcpTokenRegistry } from "./mcp-token-registry.js";
|
||||
|
||||
const BASE64URL_256_BIT_RE = /^[A-Za-z0-9_-]{43}$/;
|
||||
|
||||
describe("AgentMcpTokenRegistry", () => {
|
||||
test("mints a 256-bit random base64url token per agent and reuses it while active", () => {
|
||||
const registry = new AgentMcpTokenRegistry();
|
||||
|
||||
expect(registry.get("agent-1")).toBeNull();
|
||||
|
||||
const first = registry.issue("agent-1");
|
||||
expect(first).toMatch(BASE64URL_256_BIT_RE);
|
||||
expect(registry.issue("agent-1")).toBe(first);
|
||||
expect(registry.get("agent-1")).toBe(first);
|
||||
|
||||
const second = registry.issue("agent-2");
|
||||
expect(second).toMatch(BASE64URL_256_BIT_RE);
|
||||
expect(second).not.toBe(first);
|
||||
|
||||
expect(registry.resolve(first)).toBe("agent-1");
|
||||
expect(registry.resolve(second)).toBe("agent-2");
|
||||
});
|
||||
|
||||
test("returns null for empty, unknown, or tampered tokens", () => {
|
||||
const registry = new AgentMcpTokenRegistry();
|
||||
const token = registry.issue("agent-1");
|
||||
|
||||
expect(registry.resolve("")).toBeNull();
|
||||
expect(registry.resolve("not-a-valid-token")).toBeNull();
|
||||
const tampered = `${token.slice(0, -1)}${token.endsWith("A") ? "B" : "A"}`;
|
||||
expect(registry.resolve(tampered)).toBeNull();
|
||||
});
|
||||
|
||||
test("revokes an agent token immediately and mints a fresh token on subsequent issue", () => {
|
||||
const registry = new AgentMcpTokenRegistry();
|
||||
const tokenA = registry.issue("agent-a");
|
||||
const tokenB = registry.issue("agent-b");
|
||||
|
||||
registry.revoke("agent-a");
|
||||
expect(registry.get("agent-a")).toBeNull();
|
||||
expect(registry.resolve(tokenA)).toBeNull();
|
||||
// Other agents stay unaffected.
|
||||
expect(registry.resolve(tokenB)).toBe("agent-b");
|
||||
|
||||
// Revoking an already-absent agent is a no-op.
|
||||
registry.revoke("agent-a");
|
||||
registry.revoke("unknown-agent");
|
||||
|
||||
const rotatedA = registry.issue("agent-a");
|
||||
expect(rotatedA).toMatch(BASE64URL_256_BIT_RE);
|
||||
expect(rotatedA).not.toBe(tokenA);
|
||||
expect(registry.resolve(tokenA)).toBeNull();
|
||||
expect(registry.resolve(rotatedA)).toBe("agent-a");
|
||||
});
|
||||
|
||||
test("clear invalidates every active token", () => {
|
||||
const registry = new AgentMcpTokenRegistry();
|
||||
const token1 = registry.issue("agent-1");
|
||||
const token2 = registry.issue("agent-2");
|
||||
|
||||
registry.clear();
|
||||
|
||||
expect(registry.get("agent-1")).toBeNull();
|
||||
expect(registry.get("agent-2")).toBeNull();
|
||||
expect(registry.resolve(token1)).toBeNull();
|
||||
expect(registry.resolve(token2)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
interface TokenEntry {
|
||||
token: string;
|
||||
hash: string;
|
||||
}
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns per-agent capability tokens authenticating local agent processes to the
|
||||
* daemon's `/_internal/mcp/agents` endpoint. Tokens are 256-bit random values indexed by
|
||||
* SHA-256 hash for O(1) lookup, kept strictly in memory, and invalidated as
|
||||
* soon as the bound agent closes, archives, deletes, or the daemon stops.
|
||||
*/
|
||||
export class AgentMcpTokenRegistry {
|
||||
private readonly byHash = new Map<string, string>();
|
||||
private readonly byAgent = new Map<string, TokenEntry>();
|
||||
|
||||
issue(agentId: string): string {
|
||||
const existing = this.byAgent.get(agentId);
|
||||
if (existing) {
|
||||
return existing.token;
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const hash = hashToken(token);
|
||||
this.byAgent.set(agentId, { token, hash });
|
||||
this.byHash.set(hash, agentId);
|
||||
return token;
|
||||
}
|
||||
|
||||
get(agentId: string): string | null {
|
||||
return this.byAgent.get(agentId)?.token ?? null;
|
||||
}
|
||||
|
||||
resolve(token: string): string | null {
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hash = hashToken(token);
|
||||
const agentId = this.byHash.get(hash);
|
||||
if (!agentId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const entry = this.byAgent.get(agentId);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const provided = Buffer.from(token);
|
||||
const expected = Buffer.from(entry.token);
|
||||
if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return agentId;
|
||||
}
|
||||
|
||||
revoke(agentId: string): void {
|
||||
const existing = this.byAgent.get(agentId);
|
||||
if (!existing) {
|
||||
return;
|
||||
}
|
||||
this.byAgent.delete(agentId);
|
||||
this.byHash.delete(existing.hash);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.byAgent.clear();
|
||||
this.byHash.clear();
|
||||
}
|
||||
}
|
||||
@@ -204,7 +204,7 @@ describe("exact MCP preapproval mappings", () => {
|
||||
expect(
|
||||
applyCodexMcpToolApproval(
|
||||
{
|
||||
"mcp_servers.paseo": { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
|
||||
"mcp_servers.paseo": { url: "http://127.0.0.1/_internal/mcp/agents?callerAgentId=a1" },
|
||||
"mcp_servers.other": { command: "node" },
|
||||
},
|
||||
"paseo",
|
||||
@@ -212,7 +212,7 @@ describe("exact MCP preapproval mappings", () => {
|
||||
),
|
||||
).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
|
||||
url: "http://127.0.0.1/_internal/mcp/agents?callerAgentId=a1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
"mcp_servers.other": { command: "node" },
|
||||
@@ -222,7 +222,7 @@ describe("exact MCP preapproval mappings", () => {
|
||||
applyCodexMcpToolApproval(
|
||||
{
|
||||
mcp_servers: {
|
||||
paseo: { url: "http://127.0.0.1/mcp/agents?callerAgentId=a1" },
|
||||
paseo: { url: "http://127.0.0.1/_internal/mcp/agents?callerAgentId=a1" },
|
||||
"my.dotted": { url: "http://127.0.0.1/other" },
|
||||
},
|
||||
},
|
||||
@@ -232,7 +232,7 @@ describe("exact MCP preapproval mappings", () => {
|
||||
).toEqual({
|
||||
mcp_servers: {
|
||||
paseo: {
|
||||
url: "http://127.0.0.1/mcp/agents?callerAgentId=a1",
|
||||
url: "http://127.0.0.1/_internal/mcp/agents?callerAgentId=a1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
"my.dotted": { url: "http://127.0.0.1/other" },
|
||||
|
||||
@@ -3637,7 +3637,7 @@ describe("ACPAgentSession", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -3705,7 +3705,10 @@ describe("ACPAgentSession", () => {
|
||||
}
|
||||
|
||||
const mcpServers: AgentSessionConfig["mcpServers"] = {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
local: { type: "stdio", command: "node", args: ["mcp.js"] },
|
||||
};
|
||||
|
||||
@@ -3738,7 +3741,7 @@ describe("ACPAgentSession", () => {
|
||||
{
|
||||
type: "http",
|
||||
name: "paseo",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
headers: [],
|
||||
},
|
||||
{ name: "local", command: "node", args: ["mcp.js"], env: [] },
|
||||
|
||||
@@ -149,7 +149,7 @@ describe("Claude spawn override", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
headers: { Authorization: "Bearer secret-token" },
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1119,7 +1119,7 @@ describe("ClaudeAgentSession features", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
headers: { Authorization: "Bearer secret-token" },
|
||||
},
|
||||
},
|
||||
@@ -1152,7 +1152,7 @@ describe("ClaudeAgentSession features", () => {
|
||||
{
|
||||
provider: "claude",
|
||||
cwd,
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/_internal/mcp/agents" } },
|
||||
},
|
||||
{ env: { TEST_CLAUDE_WORKSPACE_VERSION: "2.1.325" } },
|
||||
);
|
||||
@@ -1179,7 +1179,7 @@ describe("ClaudeAgentSession features", () => {
|
||||
const config = {
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/_internal/mcp/agents" } },
|
||||
} as const;
|
||||
const existing = await client.createSession(config);
|
||||
try {
|
||||
@@ -1227,7 +1227,7 @@ describe("ClaudeAgentSession features", () => {
|
||||
|
||||
const withMcp = {
|
||||
...config,
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/_internal/mcp/agents" } },
|
||||
} as const;
|
||||
await expect(launch(withMcp)).rejects.toThrow("Update Claude Code to 2.1.326 or later");
|
||||
});
|
||||
|
||||
@@ -1832,7 +1832,10 @@ describe("Codex app-server provider", () => {
|
||||
const session = await createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
"plugin-tool": { type: "stdio", command: "node", args: ["server.js"] },
|
||||
},
|
||||
}),
|
||||
@@ -1844,7 +1847,7 @@ describe("Codex app-server provider", () => {
|
||||
?.config;
|
||||
expect(startConfig).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
"mcp_servers.plugin-tool": {
|
||||
command: "node",
|
||||
@@ -1882,7 +1885,10 @@ describe("Codex app-server provider", () => {
|
||||
const session = await createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
"my.dotted": { type: "http", url: "http://127.0.0.1:8080/mcp" },
|
||||
},
|
||||
}),
|
||||
@@ -1895,7 +1901,7 @@ describe("Codex app-server provider", () => {
|
||||
expect(startConfig).toEqual({
|
||||
mcp_servers: {
|
||||
paseo: {
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
"my.dotted": {
|
||||
url: "http://127.0.0.1:8080/mcp",
|
||||
@@ -1916,7 +1922,10 @@ describe("Codex app-server provider", () => {
|
||||
createConfig({
|
||||
modeId: "auto",
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ voiceToolsEnabled: true },
|
||||
@@ -1928,7 +1937,7 @@ describe("Codex app-server provider", () => {
|
||||
?.config;
|
||||
expect(startConfig).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
});
|
||||
@@ -3544,7 +3553,10 @@ describe("Codex app-server provider", () => {
|
||||
daemonAppendSystemPrompt: "Daemon instructions",
|
||||
pluginAppendSystemPrompt: ["Plugin instructions"],
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
},
|
||||
}),
|
||||
null,
|
||||
@@ -3600,7 +3612,7 @@ describe("Codex app-server provider", () => {
|
||||
expect.objectContaining({
|
||||
...customCodexConfig,
|
||||
"mcp_servers.paseo": expect.objectContaining({
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -1497,7 +1497,7 @@ describe("OpenCode adapter startTurn error handling", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=test-agent",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=test-agent",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1510,7 +1510,7 @@ describe("OpenCode adapter startTurn error handling", () => {
|
||||
name: "paseo",
|
||||
config: {
|
||||
type: "remote",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=test-agent",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=test-agent",
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
@@ -1548,7 +1548,7 @@ describe("OpenCode adapter startTurn error handling", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=test-agent",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=test-agent",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4226,7 +4226,7 @@ describe("PiRpcAgentClient", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
localSecret: {
|
||||
type: "stdio",
|
||||
@@ -4270,7 +4270,7 @@ describe("PiRpcAgentClient", () => {
|
||||
directTools: ["brave_llm_context"],
|
||||
},
|
||||
paseo: {
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
auth: false,
|
||||
oauth: false,
|
||||
},
|
||||
@@ -4299,7 +4299,7 @@ describe("PiRpcAgentClient", () => {
|
||||
client.createSession(
|
||||
createConfig({
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" },
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/_internal/mcp/agents" },
|
||||
},
|
||||
}),
|
||||
{ env: { PI_CODING_AGENT_DIR: agentDir } },
|
||||
@@ -4321,7 +4321,7 @@ describe("PiRpcAgentClient", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
headers: { Authorization: "Bearer token" },
|
||||
},
|
||||
local: { type: "stdio", command: "node", args: ["server.js"], env: { KEY: "`${x}`" } },
|
||||
@@ -4335,7 +4335,7 @@ describe("PiRpcAgentClient", () => {
|
||||
const extensionPath = actualLaunch.extensionPaths[0]!;
|
||||
expect(await readRegisteredMcpServers(extensionPath)).toEqual({
|
||||
paseo: {
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
headers: { Authorization: "Bearer token" },
|
||||
},
|
||||
local: { command: "node", args: ["server.js"], env: { KEY: "`${x}`" } },
|
||||
@@ -4355,7 +4355,10 @@ describe("PiRpcAgentClient", () => {
|
||||
pi.queueCommands([{ name: "mcp", source: "extension", sourceInfo: { path: "builtin:mcp" } }]);
|
||||
const session = await client.resumeSession(persistence, {
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:7777/mcp/agents?callerAgentId=agent-2" },
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:7777/_internal/mcp/agents?callerAgentId=agent-2",
|
||||
},
|
||||
},
|
||||
});
|
||||
onTestFinished(() => session.close());
|
||||
@@ -4365,7 +4368,7 @@ describe("PiRpcAgentClient", () => {
|
||||
expect(actualLaunch.session).toBe(persistence.nativeHandle);
|
||||
expect(actualLaunch.argv).not.toContain("--mcp-config");
|
||||
expect(await readRegisteredMcpServers(actualLaunch.extensionPaths[0]!)).toEqual({
|
||||
paseo: { url: "http://127.0.0.1:7777/mcp/agents?callerAgentId=agent-2" },
|
||||
paseo: { url: "http://127.0.0.1:7777/_internal/mcp/agents?callerAgentId=agent-2" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4379,7 +4382,7 @@ describe("PiRpcAgentClient", () => {
|
||||
]);
|
||||
const session = await createClient(pi).createSession(
|
||||
createConfig({
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1:6767/_internal/mcp/agents" } },
|
||||
}),
|
||||
{ env: { PI_CODING_AGENT_DIR: agentDir } },
|
||||
);
|
||||
@@ -4413,7 +4416,7 @@ describe("PiRpcAgentClient", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -4442,7 +4445,7 @@ describe("PiRpcAgentClient history resume", () => {
|
||||
sourceInfo: { path: "builtin:mcp" },
|
||||
} as const;
|
||||
const PASEO_MCP_SERVERS = {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" },
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/_internal/mcp/agents" },
|
||||
} as const;
|
||||
|
||||
interface ArchivedPiSession {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { AgentSessionConfig } from "./agent-sdk-types.js";
|
||||
import { withRuntimePaseoMcpServer } from "./runtime-mcp-config.js";
|
||||
import {
|
||||
hasInternalPaseoMcpServer,
|
||||
stripInternalPaseoMcpServer,
|
||||
withRuntimePaseoMcpServer,
|
||||
} from "./runtime-mcp-config.js";
|
||||
|
||||
const BASE_CONFIG: AgentSessionConfig = {
|
||||
provider: "claude",
|
||||
@@ -9,43 +13,74 @@ const BASE_CONFIG: AgentSessionConfig = {
|
||||
};
|
||||
|
||||
describe("withRuntimePaseoMcpServer", () => {
|
||||
test("injects the paseo MCP server with a bearer header when a token is provided", () => {
|
||||
test("injects the paseo MCP server without callerAgentId in the URL and with a bearer header", () => {
|
||||
const result = withRuntimePaseoMcpServer({
|
||||
config: BASE_CONFIG,
|
||||
agentId: "agent-1",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpAuthToken: "cap-token",
|
||||
});
|
||||
|
||||
expect(result.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: "Bearer cap-token" },
|
||||
});
|
||||
expect(hasInternalPaseoMcpServer(result)).toBe(true);
|
||||
});
|
||||
|
||||
test("omits the header when no token is available", () => {
|
||||
const result = withRuntimePaseoMcpServer({
|
||||
config: BASE_CONFIG,
|
||||
agentId: "agent-1",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpAuthToken: null,
|
||||
});
|
||||
|
||||
expect(result.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
});
|
||||
});
|
||||
|
||||
test("does not inject when no MCP base URL is configured", () => {
|
||||
const result = withRuntimePaseoMcpServer({
|
||||
config: BASE_CONFIG,
|
||||
agentId: "agent-1",
|
||||
mcpBaseUrl: null,
|
||||
mcpAuthToken: "cap-token",
|
||||
});
|
||||
|
||||
expect(result.mcpServers).toBeUndefined();
|
||||
expect(hasInternalPaseoMcpServer(result)).toBe(false);
|
||||
});
|
||||
|
||||
test("strips internal paseo MCP servers with or without query params and bearer headers", () => {
|
||||
const strippedNew = stripInternalPaseoMcpServer({
|
||||
...BASE_CONFIG,
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: "Bearer secret-agent-token" },
|
||||
},
|
||||
custom: {
|
||||
type: "stdio",
|
||||
command: "custom-mcp",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(strippedNew.mcpServers).toEqual({
|
||||
custom: { type: "stdio", command: "custom-mcp" },
|
||||
});
|
||||
|
||||
const strippedLegacy = stripInternalPaseoMcpServer({
|
||||
...BASE_CONFIG,
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
headers: { Authorization: "Bearer legacy-token" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(strippedLegacy.mcpServers).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import type { AgentSessionConfig, McpServerConfig } from "./agent-sdk-types.js";
|
||||
|
||||
export const PASEO_MCP_SERVER_NAME = "paseo";
|
||||
const PASEO_MCP_PATHNAME = "/mcp/agents";
|
||||
const PASEO_MCP_PATHNAMES = new Set(["/_internal/mcp/agents", "/mcp/agents"]);
|
||||
|
||||
export function hasInternalPaseoMcpServer(config: AgentSessionConfig): boolean {
|
||||
const paseoServer = config.mcpServers?.[PASEO_MCP_SERVER_NAME];
|
||||
return paseoServer !== undefined && isInternalPaseoMcpServer(paseoServer);
|
||||
}
|
||||
|
||||
export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSessionConfig {
|
||||
const mcpServers = config.mcpServers;
|
||||
@@ -28,12 +33,10 @@ export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSe
|
||||
|
||||
export function withRuntimePaseoMcpServer(params: {
|
||||
config: AgentSessionConfig;
|
||||
agentId: string;
|
||||
mcpBaseUrl: string | null;
|
||||
/**
|
||||
* Capability token authenticating the injected connection to the daemon's
|
||||
* Agent MCP endpoint. The daemon password is gated off this route, so without
|
||||
* this header the agent's MCP requests are rejected when a password is set.
|
||||
* Per-agent capability token authenticating the injected connection to the
|
||||
* daemon's `/_internal/mcp/agents` endpoint and binding the caller identity server-side.
|
||||
*/
|
||||
mcpAuthToken: string | null;
|
||||
}): AgentSessionConfig {
|
||||
@@ -47,7 +50,7 @@ export function withRuntimePaseoMcpServer(params: {
|
||||
mcpServers: {
|
||||
[PASEO_MCP_SERVER_NAME]: {
|
||||
type: "http",
|
||||
url: `${params.mcpBaseUrl}?callerAgentId=${params.agentId}`,
|
||||
url: params.mcpBaseUrl,
|
||||
...(params.mcpAuthToken
|
||||
? { headers: { Authorization: `Bearer ${params.mcpAuthToken}` } }
|
||||
: {}),
|
||||
@@ -63,7 +66,7 @@ function isInternalPaseoMcpServer(config: McpServerConfig): boolean {
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(config.url).pathname === PASEO_MCP_PATHNAME;
|
||||
return PASEO_MCP_PATHNAMES.has(new URL(config.url).pathname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
extractWsBearerProtocol,
|
||||
extractWsBearerToken,
|
||||
hashDaemonPassword,
|
||||
isAgentMcpRequestAuthorized,
|
||||
isBearerTokenValidAsync,
|
||||
resolveAgentMcpCaller,
|
||||
shouldBypassBearerAuth,
|
||||
} from "./auth.js";
|
||||
import { resolveSessionAdmission } from "./session-admission-auth.js";
|
||||
@@ -68,9 +68,9 @@ describe("daemon bearer validator", () => {
|
||||
expect(shouldBypassBearerAuth("GET", "/api/health")).toBe(true);
|
||||
// Guarded by its own single-use download token, not the daemon password.
|
||||
expect(shouldBypassBearerAuth("GET", "/api/files/download")).toBe(true);
|
||||
// Guarded by its own per-daemon-run capability token (see
|
||||
// isAgentMcpRequestAuthorized), not the daemon password.
|
||||
expect(shouldBypassBearerAuth("POST", "/mcp/agents")).toBe(true);
|
||||
// Guarded by its own per-agent capability tokens and owner credentials
|
||||
// (see resolveAgentMcpCaller), not the global daemon password middleware.
|
||||
expect(shouldBypassBearerAuth("POST", "/_internal/mcp/agents")).toBe(true);
|
||||
// Everything else stays behind the daemon password.
|
||||
expect(shouldBypassBearerAuth("GET", "/api/status")).toBe(false);
|
||||
expect(shouldBypassBearerAuth("POST", "/api/files/upload")).toBe(false);
|
||||
@@ -109,54 +109,146 @@ describe("daemon bearer validator", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent MCP request authorizer", () => {
|
||||
const CAPABILITY_TOKEN = "cap-token-abc123";
|
||||
describe("agent MCP caller resolver", () => {
|
||||
const AGENT_TOKEN = "agent-cap-token-abc123";
|
||||
const LOCAL_CREDENTIAL = "local-cred-token-xyz789";
|
||||
const resolveAgentToken = (token: string) => (token === AGENT_TOKEN ? "agent-1" : null);
|
||||
|
||||
test("allows any request when no daemon password is configured", async () => {
|
||||
test("fails closed when Authorization is missing or unknown even on passwordless daemons", async () => {
|
||||
expect(
|
||||
await isAgentMcpRequestAuthorized({
|
||||
password: undefined,
|
||||
capabilityToken: CAPABILITY_TOKEN,
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: undefined,
|
||||
queryCallerAgentId: undefined,
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toBe(true);
|
||||
).toEqual({ kind: "unauthorized" });
|
||||
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: "Basic dXNlcjpwYXNz",
|
||||
queryCallerAgentId: undefined,
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toEqual({ kind: "unauthorized" });
|
||||
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: "Bearer unknown-token",
|
||||
queryCallerAgentId: "agent-1",
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toEqual({ kind: "unauthorized" });
|
||||
});
|
||||
|
||||
test("accepts the injected capability token", async () => {
|
||||
test("resolves a valid per-agent capability token to its bound agentId", async () => {
|
||||
expect(
|
||||
await isAgentMcpRequestAuthorized({
|
||||
password: CORRECT_PASSWORD_HASH,
|
||||
capabilityToken: CAPABILITY_TOKEN,
|
||||
authorizationHeader: `Bearer ${CAPABILITY_TOKEN}`,
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: `Bearer ${AGENT_TOKEN}`,
|
||||
queryCallerAgentId: undefined,
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toBe(true);
|
||||
).toEqual({ kind: "agent", agentId: "agent-1" });
|
||||
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: `Bearer ${AGENT_TOKEN}`,
|
||||
queryCallerAgentId: "agent-1",
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: CORRECT_PASSWORD_HASH,
|
||||
}),
|
||||
).toEqual({ kind: "agent", agentId: "agent-1" });
|
||||
});
|
||||
|
||||
test("still accepts a valid daemon-password bearer", async () => {
|
||||
test("forbids a per-agent capability token when query callerAgentId does not match", async () => {
|
||||
expect(
|
||||
await isAgentMcpRequestAuthorized({
|
||||
password: CORRECT_PASSWORD_HASH,
|
||||
capabilityToken: CAPABILITY_TOKEN,
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: `Bearer ${AGENT_TOKEN}`,
|
||||
queryCallerAgentId: "agent-2",
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "forbidden",
|
||||
reason: "callerAgentId does not match token",
|
||||
});
|
||||
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: `Bearer ${AGENT_TOKEN}`,
|
||||
queryCallerAgentId: "",
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "forbidden",
|
||||
reason: "callerAgentId does not match token",
|
||||
});
|
||||
});
|
||||
|
||||
test("authenticates localCredential as owner on both passwordless and password-protected daemons", async () => {
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: `Bearer ${LOCAL_CREDENTIAL}`,
|
||||
queryCallerAgentId: undefined,
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: undefined,
|
||||
}),
|
||||
).toEqual({ kind: "owner", callerAgentId: undefined });
|
||||
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: `Bearer ${LOCAL_CREDENTIAL}`,
|
||||
queryCallerAgentId: "agent-2",
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: CORRECT_PASSWORD_HASH,
|
||||
}),
|
||||
).toEqual({ kind: "owner", callerAgentId: "agent-2" });
|
||||
});
|
||||
|
||||
test("authenticates daemon password as owner and surfaces throttled verification", async () => {
|
||||
expect(
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: "Bearer correct-password",
|
||||
queryCallerAgentId: "agent-2",
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: CORRECT_PASSWORD_HASH,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
).toEqual({ kind: "owner", callerAgentId: "agent-2" });
|
||||
|
||||
test("rejects requests presenting neither the token nor a valid password", async () => {
|
||||
expect(
|
||||
await isAgentMcpRequestAuthorized({
|
||||
password: CORRECT_PASSWORD_HASH,
|
||||
capabilityToken: CAPABILITY_TOKEN,
|
||||
authorizationHeader: undefined,
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: "Bearer wrong-password",
|
||||
queryCallerAgentId: undefined,
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: CORRECT_PASSWORD_HASH,
|
||||
}),
|
||||
).toBe(false);
|
||||
).toEqual({ kind: "unauthorized" });
|
||||
|
||||
expect(
|
||||
await isAgentMcpRequestAuthorized({
|
||||
password: CORRECT_PASSWORD_HASH,
|
||||
capabilityToken: CAPABILITY_TOKEN,
|
||||
authorizationHeader: "Bearer wrong-token",
|
||||
await resolveAgentMcpCaller({
|
||||
authorizationHeader: "Bearer guess",
|
||||
queryCallerAgentId: undefined,
|
||||
resolveAgentToken,
|
||||
localCredential: LOCAL_CREDENTIAL,
|
||||
passwordHash: CORRECT_PASSWORD_HASH,
|
||||
verifyPassword: async () => ({ ok: false, throttled: true }),
|
||||
}),
|
||||
).toBe(false);
|
||||
).toEqual({ kind: "throttled" });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { compare, hash, hashSync } from "bcryptjs";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import type { RequestHandler } from "express";
|
||||
import type { DaemonPasswordStore } from "./auth/daemon-password-store.js";
|
||||
import { matchesLocalCredential } from "./local-credential.js";
|
||||
@@ -150,7 +149,7 @@ export function createRequireBearerMiddleware(
|
||||
};
|
||||
}
|
||||
|
||||
const SELF_AUTHENTICATING_ROUTES = new Set(["/api/files/download", "/mcp/agents"]);
|
||||
const SELF_AUTHENTICATING_ROUTES = new Set(["/api/files/download", "/_internal/mcp/agents"]);
|
||||
|
||||
function isBearerFreeRoute(path: string): boolean {
|
||||
return path === "/api/health" || SELF_AUTHENTICATING_ROUTES.has(path);
|
||||
@@ -163,38 +162,65 @@ export function shouldBypassBearerAuth(method: string, path: string): boolean {
|
||||
return isBearerFreeRoute(path);
|
||||
}
|
||||
|
||||
export type AgentMcpCaller =
|
||||
| { kind: "agent"; agentId: string }
|
||||
| { kind: "owner"; callerAgentId: string | undefined }
|
||||
| { kind: "forbidden"; reason: string }
|
||||
| { kind: "throttled" }
|
||||
| { kind: "unauthorized" };
|
||||
|
||||
/**
|
||||
* Authorizes a request to the Agent MCP endpoint (/mcp/agents), which is exempt
|
||||
* from the global daemon-password middleware. Accepts either the per-daemon-run
|
||||
* capability token the daemon injects into its own agents' configs and MCP
|
||||
* client, or a valid daemon-password bearer (so existing password-authenticated
|
||||
* callers keep working). When no daemon password is configured the endpoint is
|
||||
* open, matching the global middleware's behavior.
|
||||
* Resolves the authenticated caller for `/_internal/mcp/agents`, which is exempt from the
|
||||
* global daemon-password middleware and enforces its own auth boundary. Fails
|
||||
* closed even when no daemon password is configured so callers cannot drop
|
||||
* credentials to become an unrestricted owner.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. Per-agent capability token -> agent caller strictly bound to its agentId
|
||||
* (rejects mismatched `?callerAgentId=` with `forbidden`).
|
||||
* 2. Daemon `localCredential` (`$PASEO_HOME/local-credential`) -> owner caller.
|
||||
* 3. Configured daemon password -> owner caller (or `throttled` under rate limit).
|
||||
* 4. Anything else -> `unauthorized`.
|
||||
*/
|
||||
export async function isAgentMcpRequestAuthorized(input: {
|
||||
password: string | undefined;
|
||||
verifyPassword?: (token: string) => Promise<{ ok: boolean; throttled: boolean }>;
|
||||
capabilityToken: string | null;
|
||||
export async function resolveAgentMcpCaller(input: {
|
||||
authorizationHeader: string | undefined;
|
||||
}): Promise<boolean> {
|
||||
if (!input.password) {
|
||||
return true;
|
||||
}
|
||||
queryCallerAgentId: string | undefined;
|
||||
resolveAgentToken: (token: string) => string | null;
|
||||
localCredential: string | null;
|
||||
passwordHash: string | undefined;
|
||||
verifyPassword?: (token: string) => Promise<{ ok: boolean; throttled: boolean }>;
|
||||
}): Promise<AgentMcpCaller> {
|
||||
const token = extractHttpBearerToken(input.authorizationHeader);
|
||||
if (input.capabilityToken !== null && token !== null) {
|
||||
// Constant-time compare; length-guard first because timingSafeEqual throws
|
||||
// on differing buffer lengths.
|
||||
const provided = Buffer.from(token);
|
||||
const expected = Buffer.from(input.capabilityToken);
|
||||
if (provided.length === expected.length && timingSafeEqual(provided, expected)) {
|
||||
return true;
|
||||
if (token === null) {
|
||||
return { kind: "unauthorized" };
|
||||
}
|
||||
|
||||
const boundAgentId = input.resolveAgentToken(token);
|
||||
if (boundAgentId !== null) {
|
||||
if (input.queryCallerAgentId !== undefined && input.queryCallerAgentId !== boundAgentId) {
|
||||
return {
|
||||
kind: "forbidden",
|
||||
reason: "callerAgentId does not match token",
|
||||
};
|
||||
}
|
||||
return { kind: "agent", agentId: boundAgentId };
|
||||
}
|
||||
|
||||
if (input.localCredential !== null && matchesLocalCredential(input.localCredential, token)) {
|
||||
return { kind: "owner", callerAgentId: input.queryCallerAgentId || undefined };
|
||||
}
|
||||
|
||||
if (input.passwordHash) {
|
||||
const verification = input.verifyPassword
|
||||
? await input.verifyPassword(token)
|
||||
: { ok: await compare(token, input.passwordHash), throttled: false };
|
||||
if (verification.ok) {
|
||||
return { kind: "owner", callerAgentId: input.queryCallerAgentId || undefined };
|
||||
}
|
||||
if (verification.throttled) {
|
||||
return { kind: "throttled" };
|
||||
}
|
||||
}
|
||||
if (token === null) {
|
||||
return false;
|
||||
}
|
||||
if (input.verifyPassword) {
|
||||
return (await input.verifyPassword(token)).ok;
|
||||
}
|
||||
return isBearerTokenValidAsync({ password: input.password, token });
|
||||
|
||||
return { kind: "unauthorized" };
|
||||
}
|
||||
|
||||
@@ -18,6 +18,13 @@ const INBOUND_PERMISSION = {
|
||||
"tunnel.exposures.list.request": ["daemon.read", "tunnel.manage"],
|
||||
"tunnel.exposure.open.request": "tunnel.manage",
|
||||
"tunnel.exposure.close.request": "tunnel.manage",
|
||||
"mcp_server.get_status.request": ["daemon.read", "tunnel.manage"],
|
||||
"mcp_server.configure.request": ["tunnel.manage", "access.manage"],
|
||||
"mcp_server.access.list.request": "access.manage",
|
||||
"mcp_server.tokens.create.request": "access.manage",
|
||||
"mcp_server.credentials.revoke.request": "access.manage",
|
||||
"mcp_server.approvals.decide.request": "access.manage",
|
||||
"mcp_server.approval_codes.create.request": "access.manage",
|
||||
"hosts.link.open.request": null,
|
||||
"hosts.link.ack.request": null,
|
||||
"hosts.route.open.request": null,
|
||||
@@ -275,6 +282,15 @@ const OUTBOUND_PERMISSION = {
|
||||
"tunnel.exposure.changed": ["daemon.read", "tunnel.manage"],
|
||||
"tunnel.exposure.open.response": "tunnel.manage",
|
||||
"tunnel.exposure.close.response": "tunnel.manage",
|
||||
"mcp_server.get_status.response": ["daemon.read", "tunnel.manage"],
|
||||
"mcp_server.status.changed": ["daemon.read", "tunnel.manage"],
|
||||
"mcp_server.configure.response": ["tunnel.manage", "access.manage"],
|
||||
"mcp_server.access.list.response": "access.manage",
|
||||
"mcp_server.access.changed": "access.manage",
|
||||
"mcp_server.tokens.create.response": "access.manage",
|
||||
"mcp_server.credentials.revoke.response": "access.manage",
|
||||
"mcp_server.approvals.decide.response": "access.manage",
|
||||
"mcp_server.approval_codes.create.response": "access.manage",
|
||||
"hosts.link.open.response": null,
|
||||
"hosts.route.open.response": null,
|
||||
"hosts.route.frame": null,
|
||||
|
||||
@@ -91,7 +91,9 @@ describe("daemon web UI bootstrap", () => {
|
||||
webUi: { enabled: true, distDir },
|
||||
});
|
||||
const origin = `http://127.0.0.1:${daemonHandle.port}`;
|
||||
const metadata = await fetch(`${origin}/.well-known/oauth-protected-resource/mcp/agents`);
|
||||
const metadata = await fetch(
|
||||
`${origin}/.well-known/oauth-protected-resource/_internal/mcp/agents`,
|
||||
);
|
||||
expect(metadata.status).toBe(404);
|
||||
expect(metadata.headers.get("content-type")).toBe("application/json; charset=utf-8");
|
||||
expect(await metadata.json()).toEqual({ error: "Not found" });
|
||||
|
||||
@@ -26,6 +26,7 @@ import { AgentStorage, type StoredAgentRecord } from "./agent/agent-storage.js";
|
||||
import { ensureAgentLoaded, loadAgentHistory } from "./agent/agent-loading.js";
|
||||
import { AgentManagerShuttingDownError } from "./agent/agent-manager.js";
|
||||
import { generateLocalPairingOffer } from "./pairing-offer.js";
|
||||
import { readLocalCredential } from "./local-credential.js";
|
||||
import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js";
|
||||
import { createTestAgentClients } from "./test-utils/fake-agent-client.js";
|
||||
import { DaemonClient } from "./test-utils/daemon-client.js";
|
||||
@@ -551,8 +552,11 @@ describe("paseo daemon bootstrap", () => {
|
||||
expect(beforeCors.headers.get("access-control-allow-origin")).toBe(
|
||||
"https://before.example.test",
|
||||
);
|
||||
const beforeMcp = await fetch(`http://127.0.0.1:${target.port}/mcp/agents`, {
|
||||
const localToken = readLocalCredential(paseoHome);
|
||||
expect(localToken).toBeTruthy();
|
||||
const beforeMcp = await fetch(`http://127.0.0.1:${target.port}/_internal/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${localToken!}` },
|
||||
});
|
||||
// Any answer from the agent MCP handler proves the route is live; the handler
|
||||
// rejects a body-less POST as an unsupported media type.
|
||||
@@ -622,8 +626,9 @@ describe("paseo daemon bootstrap", () => {
|
||||
).resolves.toEqual({ status: "rejected", statusCode: 403 });
|
||||
expect(
|
||||
(
|
||||
await fetch(`http://127.0.0.1:${target.port}/mcp/agents`, {
|
||||
await fetch(`http://127.0.0.1:${target.port}/_internal/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${localToken!}` },
|
||||
})
|
||||
).status,
|
||||
).toBe(404);
|
||||
@@ -1217,10 +1222,12 @@ export default function contribute(plugin: unknown) {
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await fetch(`http://127.0.0.1:${daemonHandle.port}/mcp/agents`, {
|
||||
const localToken = readLocalCredential(daemonHandle.paseoHome);
|
||||
expect(localToken).toBeTruthy();
|
||||
const response = await fetch(`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer secret-debug-token",
|
||||
Authorization: `Bearer ${localToken!}`,
|
||||
Accept: "application/json, text/event-stream",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
@@ -1240,7 +1247,7 @@ export default function contribute(plugin: unknown) {
|
||||
expect(logs).toContain("[redacted]");
|
||||
expect(logs).toContain('"method":"tools/call"');
|
||||
expect(logs).toContain('"hasParams":true');
|
||||
expect(logs).not.toContain("secret-debug-token");
|
||||
expect(logs).not.toContain(localToken!);
|
||||
expect(logs).not.toContain("secret-body-token");
|
||||
expect(logs).not.toContain("apiKey");
|
||||
} finally {
|
||||
|
||||
@@ -23,7 +23,6 @@ import express from "express";
|
||||
import { createServer as createHTTPServer, type IncomingMessage, type ServerResponse } from "http";
|
||||
import { constants, existsSync, unlinkSync } from "fs";
|
||||
import { mkdir, open, rm, stat } from "fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
getCachedHostMachineKind,
|
||||
primeHostMachineKind,
|
||||
@@ -124,7 +123,9 @@ import {
|
||||
import { openDaemonDatabase, type DaemonDatabase } from "./database/index.js";
|
||||
import { AgentStorage } from "./agent/agent-storage.js";
|
||||
import { attachAgentStoragePersistence } from "./persistence-hooks.js";
|
||||
import { createAgentMcpServer } from "./agent/mcp-server.js";
|
||||
import { createAgentMcpServer, createPaseoMcpServer } from "./agent/mcp-server.js";
|
||||
import { PaseoMcpServer } from "./mcp-server/index.js";
|
||||
import { OWNER_PERMISSIONS } from "./authorization/index.js";
|
||||
import {
|
||||
createPaseoToolCatalog,
|
||||
createPaseoAgentToolManifest,
|
||||
@@ -212,9 +213,10 @@ import { withTimeout } from "../utils/promise-timeout.js";
|
||||
import { isHostnameAllowed, type HostnamesConfig } from "./hostnames.js";
|
||||
import {
|
||||
createRequireBearerMiddleware,
|
||||
isAgentMcpRequestAuthorized,
|
||||
resolveAgentMcpCaller,
|
||||
type DaemonAuthConfig,
|
||||
} from "./auth.js";
|
||||
import { AgentMcpTokenRegistry } from "./agent/mcp-token-registry.js";
|
||||
import { DaemonPasswordStore } from "./auth/daemon-password-store.js";
|
||||
import { deleteLocalCredential, writeLocalCredential } from "./local-credential.js";
|
||||
import { createWebUiMiddleware } from "./web-ui.js";
|
||||
@@ -746,14 +748,10 @@ async function assemblePaseoDaemon({
|
||||
ttlMs: downloadTokenTtlMs,
|
||||
});
|
||||
|
||||
// Capability token authenticating the daemon's own agents to the loopback
|
||||
// Agent MCP endpoint (/mcp/agents). Random per daemon run, injected only into
|
||||
// local agent configs and the daemon's own MCP client — never sent to remote
|
||||
// clients — so it cannot be replayed off-box. This lets the injected MCP
|
||||
// authenticate even when the daemon password is set via the app (hash only,
|
||||
// no plaintext available). Mirrors the /api/files/download capability-token
|
||||
// pattern.
|
||||
const agentMcpAuthToken = randomUUID();
|
||||
// Per-agent capability tokens authenticating local agent processes to the
|
||||
// Agent MCP endpoint (/_internal/mcp/agents). Random 256-bit tokens kept strictly in
|
||||
// memory and revoked on close, archive, delete, or daemon shutdown.
|
||||
const agentMcpTokens = new AgentMcpTokenRegistry();
|
||||
|
||||
const listenTarget = parseListenString(splitListen(config.listen)[0]);
|
||||
|
||||
@@ -1088,7 +1086,7 @@ async function assemblePaseoDaemon({
|
||||
onWorkspaceStateMayHaveChanged: ({ cwd }) => {
|
||||
workspaceGitService.onWorkspaceStateMayHaveChanged(cwd);
|
||||
},
|
||||
mcpAuthToken: agentMcpAuthToken,
|
||||
mcpTokenRegistry: agentMcpTokens,
|
||||
hasActiveVoiceTools,
|
||||
resolvePaseoToolPolicy: (provider) =>
|
||||
resolvePaseoToolPolicy(provider, daemonConfigStore.get().providers),
|
||||
@@ -1631,7 +1629,7 @@ async function assemblePaseoDaemon({
|
||||
},
|
||||
hosts: () => {
|
||||
if (!wsServer) throw new Error("Daemon is not accepting host operations");
|
||||
return wsServer.toolHosts();
|
||||
return wsServer.toolHosts(OWNER_PERMISSIONS);
|
||||
},
|
||||
}),
|
||||
});
|
||||
@@ -1682,7 +1680,7 @@ async function assemblePaseoDaemon({
|
||||
serverId,
|
||||
hosts: () => {
|
||||
if (!wsServer) throw new Error("Daemon is not accepting host operations");
|
||||
return wsServer.toolHosts();
|
||||
return wsServer.toolHosts(OWNER_PERMISSIONS);
|
||||
},
|
||||
agentManager,
|
||||
agentStorage,
|
||||
@@ -1755,6 +1753,28 @@ async function assemblePaseoDaemon({
|
||||
const createAgentToolCatalog = (runtime: PaseoToolRuntimeContext) =>
|
||||
createPaseoToolCatalog(createAgentToolHostDependencies(runtime));
|
||||
const getCurrentToolsConfig = () => resolveDaemonToolsFromMutableConfig(daemonConfigStore.get());
|
||||
const mcpServer = new PaseoMcpServer({
|
||||
paseoHome: config.paseoHome,
|
||||
config: {
|
||||
read: () => daemonConfigStore.readMcpServer(),
|
||||
write: (next) => daemonConfigStore.writeMcpServer(next),
|
||||
},
|
||||
tunnels: tunnelManager,
|
||||
createMcpServer: (permissions) =>
|
||||
createPaseoMcpServer(
|
||||
createPaseoToolCatalog({
|
||||
...createAgentToolHostDependencies({}),
|
||||
toolsConfig: undefined,
|
||||
allowedPermissions: new Set(permissions),
|
||||
hosts: () => {
|
||||
if (!wsServer) throw new Error("Daemon is not accepting host operations");
|
||||
return wsServer.toolHosts(permissions);
|
||||
},
|
||||
}),
|
||||
{ name: "paseo", version: daemonVersion },
|
||||
),
|
||||
logger: logger.child({ module: "mcp-server" }),
|
||||
});
|
||||
let mcpEnabled = config.mcpEnabled ?? true;
|
||||
const setAgentProviderToolsEnabled = (enabled: boolean) => {
|
||||
agentProviderRuntime.setPaseoToolCatalogFactory(
|
||||
@@ -1768,7 +1788,7 @@ async function assemblePaseoDaemon({
|
||||
setAgentProviderToolsEnabled(initialInject);
|
||||
|
||||
{
|
||||
const agentMcpRoute = "/mcp/agents";
|
||||
const agentMcpRoute = "/_internal/mcp/agents";
|
||||
|
||||
// Stateless serving: createMcpHandler builds a fresh server per request and
|
||||
// serves both protocol eras — modern 2026-07-28 (per-request envelope) and
|
||||
@@ -1801,17 +1821,49 @@ async function assemblePaseoDaemon({
|
||||
return { handler };
|
||||
};
|
||||
|
||||
const parseQueryCallerAgentId = (raw: unknown): string | undefined => {
|
||||
if (typeof raw === "string") return raw;
|
||||
if (Array.isArray(raw)) {
|
||||
const strings = raw.filter((value): value is string => typeof value === "string");
|
||||
if (strings.length === 0) return undefined;
|
||||
return new Set(strings).size === 1 ? strings[0] : strings.join(",");
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const runAgentMcpRequest = async (
|
||||
req: express.Request,
|
||||
res: express.Response,
|
||||
): Promise<void> => {
|
||||
const callerAgentIdRaw = req.query.callerAgentId;
|
||||
let callerAgentId: string | undefined;
|
||||
if (typeof callerAgentIdRaw === "string") {
|
||||
callerAgentId = callerAgentIdRaw;
|
||||
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
|
||||
callerAgentId = callerAgentIdRaw[0];
|
||||
// Authenticate before inspecting endpoint enablement or voice state so
|
||||
// unauthenticated requests cannot probe daemon state or drop credentials
|
||||
// to become owner callers.
|
||||
const caller = await resolveAgentMcpCaller({
|
||||
authorizationHeader: req.header("authorization"),
|
||||
queryCallerAgentId: parseQueryCallerAgentId(req.query.callerAgentId),
|
||||
resolveAgentToken: (token) => agentMcpTokens.resolve(token),
|
||||
localCredential,
|
||||
passwordHash: passwordStore.getPasswordHash(),
|
||||
verifyPassword: (token) => passwordStore.verify(token),
|
||||
});
|
||||
if (caller.kind === "unauthorized") {
|
||||
res.status(401).json({ error: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
if (caller.kind === "forbidden") {
|
||||
res.status(403).json({ error: caller.reason });
|
||||
return;
|
||||
}
|
||||
if (caller.kind === "throttled") {
|
||||
res.status(429).json({ error: "Too many authentication attempts" });
|
||||
return;
|
||||
}
|
||||
if (caller.kind === "agent" && !agentManager.isAgentMcpCallerActive(caller.agentId)) {
|
||||
res.status(401).json({ error: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
|
||||
const callerAgentId = caller.kind === "agent" ? caller.agentId : caller.callerAgentId;
|
||||
const voiceActive = Boolean(callerAgentId && hasActiveVoiceTools(callerAgentId));
|
||||
const isActiveLoopbackVoiceRequest =
|
||||
voiceActive && isLoopbackRemoteAddress(req.socket.remoteAddress);
|
||||
@@ -1819,21 +1871,6 @@ async function assemblePaseoDaemon({
|
||||
res.status(404).json({ error: "Agent MCP endpoint disabled" });
|
||||
return;
|
||||
}
|
||||
// This route is exempt from the global daemon-password middleware, so it
|
||||
// authenticates here using the injected capability token (or a valid
|
||||
// daemon password). Without this, a password-protected daemon would be
|
||||
// wide open on its agent control plane.
|
||||
if (
|
||||
!(await isAgentMcpRequestAuthorized({
|
||||
password: passwordStore.getPasswordHash(),
|
||||
verifyPassword: (token) => passwordStore.verify(token),
|
||||
capabilityToken: agentMcpAuthToken,
|
||||
authorizationHeader: req.header("authorization"),
|
||||
}))
|
||||
) {
|
||||
res.status(401).json({ error: "Unauthorized" });
|
||||
return;
|
||||
}
|
||||
if (config.mcpDebug) {
|
||||
logger.debug(
|
||||
{
|
||||
@@ -2086,6 +2123,7 @@ async function assemblePaseoDaemon({
|
||||
config.pushNotifications,
|
||||
tunnelManager,
|
||||
agentMessageQueueStore,
|
||||
mcpServer,
|
||||
);
|
||||
pluginRuntime.bindPaseoSessionHost(wsServer);
|
||||
await pluginRuntime.start();
|
||||
@@ -2099,6 +2137,9 @@ async function assemblePaseoDaemon({
|
||||
restartRecovery.resumePending();
|
||||
await finishSubscriptions.start();
|
||||
await changeRequestWatches.start();
|
||||
await mcpServer.start().catch((error) => {
|
||||
logger.error({ err: error }, "MCP Server failed to start");
|
||||
});
|
||||
await listeners.apply(config.listen);
|
||||
wsServer.beginAcceptingConnections();
|
||||
const relaySecurityLogger = logger.child({ module: "relay-security" });
|
||||
@@ -2157,10 +2198,12 @@ async function assemblePaseoDaemon({
|
||||
speechService.start();
|
||||
scriptHealthMonitor.start();
|
||||
} catch (error) {
|
||||
agentMcpTokens.clear();
|
||||
localCredential = null;
|
||||
await deleteLocalCredential(config.paseoHome);
|
||||
unsubscribePluginProviders();
|
||||
unsubscribeServiceTunnelStatus();
|
||||
await mcpServer.stop().catch(() => undefined);
|
||||
await tunnelManager.closeAll().catch(() => undefined);
|
||||
unsubscribeObservedUsage();
|
||||
await pluginRuntime.stopAllPlugins().catch(() => undefined);
|
||||
@@ -2182,6 +2225,7 @@ async function assemblePaseoDaemon({
|
||||
try {
|
||||
const keepTerminals = options?.keepTerminals === true;
|
||||
let terminalShutdownError: unknown = null;
|
||||
agentMcpTokens.clear();
|
||||
localCredential = null;
|
||||
await deleteLocalCredential(config.paseoHome);
|
||||
// Stop tracking plugin provider registrations before anything tears plugins
|
||||
@@ -2191,6 +2235,10 @@ async function assemblePaseoDaemon({
|
||||
unsubscribePluginProviders();
|
||||
unsubscribeObservedUsage();
|
||||
unsubscribeServiceTunnelStatus();
|
||||
// Stop outside apps before agents close, so no tool call starts work mid-shutdown.
|
||||
await mcpServer
|
||||
.stop()
|
||||
.catch((error) => logger.warn({ err: error }, "Failed to stop MCP Server"));
|
||||
await hubRelationships.stop();
|
||||
workspaceReconciliation.dispose();
|
||||
scriptHealthMonitor.stop();
|
||||
|
||||
@@ -7,6 +7,7 @@ import { afterEach, expect, test } from "vitest";
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import { createHostClient, createHostChannelTransport } from "@getpaseo/client/node";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import type { HostDirectory } from "@getpaseo/protocol/hosts";
|
||||
import { createServer as createTcpServer, type AddressInfo } from "node:net";
|
||||
import {
|
||||
@@ -18,6 +19,18 @@ import {
|
||||
|
||||
const cleanup: (() => Promise<unknown>)[] = [];
|
||||
|
||||
function mcpTransport(
|
||||
host: Pick<TestPaseoDaemon, "port" | "paseoHome">,
|
||||
callerAgentId?: string,
|
||||
): StreamableHTTPClientTransport {
|
||||
const url = new URL(`http://127.0.0.1:${host.port}/_internal/mcp/agents`);
|
||||
if (callerAgentId) url.searchParams.set("callerAgentId", callerAgentId);
|
||||
const token = readLocalCredential(host.paseoHome);
|
||||
return new StreamableHTTPClientTransport(url, {
|
||||
requestInit: { headers: { Authorization: `Bearer ${token!}` } },
|
||||
});
|
||||
}
|
||||
|
||||
// These asynchronous failures otherwise disappear into the fixture's silent logger.
|
||||
// Only completion errors and filesystem metadata belong in CI, never prompts or credentials.
|
||||
function completionLogger() {
|
||||
@@ -1583,11 +1596,7 @@ test(
|
||||
});
|
||||
const mcp = new Client({ name: "fleet-delegation", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
const result = await mcp.callTool({ name: "list_hosts", arguments: {} });
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
@@ -1768,11 +1777,7 @@ test(
|
||||
});
|
||||
const mcp = new Client({ name: "background-delegation", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
const call = async (name: string, args: Record<string, unknown>) => {
|
||||
const response = await mcp.callTool({ name, arguments: args });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
@@ -1873,11 +1878,7 @@ test(
|
||||
});
|
||||
const caller = async (host: TestPaseoDaemon, agentId: string) => {
|
||||
const mcp = new Client({ name: "batching-agent", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${host.port}/mcp/agents?callerAgentId=${agentId}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(host, agentId));
|
||||
cleanup.push(() => mcp.close());
|
||||
return mcp;
|
||||
};
|
||||
@@ -2034,9 +2035,7 @@ test(
|
||||
});
|
||||
const mcp = new Client({ name: "human-mode-send", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${a.port}/mcp/agents`)),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a));
|
||||
const response = await mcp.callTool({
|
||||
name: "send_agent_prompt",
|
||||
arguments: { serverId, agentId: agent.id, prompt: "Human task", sessionMode: "full-access" },
|
||||
@@ -2110,11 +2109,7 @@ test(
|
||||
title: "Remote parent",
|
||||
});
|
||||
const mcp = new Client({ name: "durable-remote-parent", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
cleanup.push(() => mcp.close());
|
||||
const response = await mcp.callTool({
|
||||
name: "create_agent",
|
||||
@@ -2184,11 +2179,7 @@ test(
|
||||
});
|
||||
const mcp = new Client({ name: "mode-parent", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
const remoteMode = async (provider: string, settings?: { modeId: string }) => {
|
||||
const response = await mcp.callTool({
|
||||
name: "create_agent",
|
||||
@@ -2251,11 +2242,7 @@ test(
|
||||
});
|
||||
const mcp = new Client({ name: "permission-parent", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
const response = await mcp.callTool({
|
||||
name: "create_agent",
|
||||
arguments: {
|
||||
@@ -2335,11 +2322,7 @@ test(
|
||||
});
|
||||
const mcp = new Client({ name: "offline-parent", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
await origin.paseo.hosts.update(saved.registrationId, { enabled: false });
|
||||
const response = await mcp.callTool({
|
||||
name: "send_agent_prompt",
|
||||
@@ -2400,11 +2383,7 @@ test.each(["removed", "disabled"] as const)(
|
||||
});
|
||||
const mcp = new Client({ name: "removed-host-parent", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
const response = await mcp.callTool({
|
||||
name: "create_agent",
|
||||
arguments: {
|
||||
@@ -2732,11 +2711,7 @@ test.each([false, true])(
|
||||
else await b.daemon.agentManager.closeAgent(child.id);
|
||||
expect((await destination.client.fetchAgent(child.id))?.agent.status).toBe("closed");
|
||||
const mcp = new Client({ name: "closed-target-caller", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
cleanup.push(() => mcp.close());
|
||||
const result = await mcp.callTool({
|
||||
name: "send_agent_prompt",
|
||||
@@ -2993,11 +2968,7 @@ test(
|
||||
|
||||
const mcp = new Client({ name: "remote-shortid-caller", version: "1" });
|
||||
cleanup.push(() => mcp.close());
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${a.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
await mcp.connect(mcpTransport(a, parent.id));
|
||||
|
||||
const status = await mcp.callTool({
|
||||
name: "get_agent_status",
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
loadPersistedConfig,
|
||||
savePersistedConfigAsync,
|
||||
loadPersistedConfigAsync,
|
||||
type DaemonMcpServerConfig,
|
||||
type PersistedConfig,
|
||||
} from "./persisted-config.js";
|
||||
import { ProviderOverrideSchema } from "./agent/provider-launch-config.js";
|
||||
@@ -1029,6 +1030,23 @@ export class DaemonConfigStore {
|
||||
);
|
||||
}
|
||||
|
||||
/** MCP Server settings stay out of the mutable config: its own RPCs own them. */
|
||||
public readMcpServer(): DaemonMcpServerConfig {
|
||||
return this.lastKnownPersisted.daemon?.mcpServer ?? {};
|
||||
}
|
||||
|
||||
public writeMcpServer(config: DaemonMcpServerConfig): Promise<void> {
|
||||
return this.enqueue(async () => {
|
||||
const persisted = await loadPersistedConfigAsync(this.paseoHome, this.logger);
|
||||
const withMcpServer = (source: PersistedConfig): PersistedConfig => ({
|
||||
...source,
|
||||
daemon: { ...source.daemon, mcpServer: config },
|
||||
});
|
||||
await savePersistedConfigAsync(this.paseoHome, withMcpServer(persisted), this.logger);
|
||||
this.lastKnownPersisted = withMcpServer(this.lastKnownPersisted);
|
||||
});
|
||||
}
|
||||
|
||||
private async persistConfig(
|
||||
patch: Omit<SupportedMutableConfigPatch, "removeProviders">,
|
||||
removeProviders: readonly string[],
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { PaseoToolCatalog } from "../agent/tools/types.js";
|
||||
import { parseAgentMessages } from "../agent/agent-messages/index.js";
|
||||
import { createTestAgentClient } from "../test-utils/fake-agent-client.js";
|
||||
import { createDaemonTestContext } from "../test-utils/index.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { githubWatchFixture } from "./test-utils/github-watch-fixture.js";
|
||||
|
||||
const subscribe = "subscribe_change_request";
|
||||
@@ -97,9 +98,11 @@ test("GitHub PR watches batch with child messages and survive restart", async ({
|
||||
async function connectMcp(port: number, agentId: string) {
|
||||
const mcp = new Client({ name: "change-request-watch-test", version: "1" });
|
||||
connections.add(mcp);
|
||||
const token = readLocalCredential(context!.daemon.paseoHome)!;
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${agentId}`),
|
||||
new URL(`http://127.0.0.1:${port}/_internal/mcp/agents?callerAgentId=${agentId}`),
|
||||
{ requestInit: { headers: { Authorization: `Bearer ${token}` } } },
|
||||
),
|
||||
);
|
||||
return mcp;
|
||||
|
||||
+13
-4
@@ -11,17 +11,26 @@ import { parseAgentMessage } from "../agent/agent-messages/index.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { canRunRealProvider, createRealProviderClients } from "./real-provider-test-config.js";
|
||||
|
||||
const CallToolResultSchema = z.object({
|
||||
structuredContent: z.object({ agentId: z.string() }),
|
||||
});
|
||||
|
||||
async function createAgentAs(port: number, callerAgentId: string, args: Record<string, unknown>) {
|
||||
const url = new URL(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
async function createAgentAs(
|
||||
port: number,
|
||||
paseoHome: string,
|
||||
callerAgentId: string,
|
||||
args: Record<string, unknown>,
|
||||
) {
|
||||
const url = new URL(`http://127.0.0.1:${port}/_internal/mcp/agents`);
|
||||
url.searchParams.set("callerAgentId", callerAgentId);
|
||||
const token = readLocalCredential(paseoHome)!;
|
||||
const mcp = await experimental_createMCPClient({
|
||||
transport: new StreamableHTTPClientTransport(url),
|
||||
transport: new StreamableHTTPClientTransport(url, {
|
||||
requestInit: { headers: { Authorization: `Bearer ${token}` } },
|
||||
}),
|
||||
});
|
||||
try {
|
||||
const callTool = Reflect.get(mcp, "callTool").bind(mcp);
|
||||
@@ -70,7 +79,7 @@ describe("daemon E2E (real claude) - finish notification across a background wak
|
||||
title: "Finish caller",
|
||||
modeId: "full-access",
|
||||
});
|
||||
const childId = await createAgentAs(daemon.port, caller.id, {
|
||||
const childId = await createAgentAs(daemon.port, daemon.paseoHome, caller.id, {
|
||||
relationship: { kind: "subagent" },
|
||||
workspace: { kind: "current" },
|
||||
provider: "claude/haiku",
|
||||
|
||||
@@ -11,6 +11,7 @@ import { parseAgentMessage } from "../agent/agent-messages/index.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { canRunRealProvider, createRealProviderClients } from "./real-provider-test-config.js";
|
||||
|
||||
const CallToolResultSchema = z.object({
|
||||
@@ -19,15 +20,21 @@ const CallToolResultSchema = z.object({
|
||||
|
||||
async function callAgentTool(
|
||||
port: number,
|
||||
paseoHome: string,
|
||||
callerAgentId: string,
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
) {
|
||||
const url = new URL(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
const url = new URL(`http://127.0.0.1:${port}/_internal/mcp/agents`);
|
||||
url.searchParams.set("callerAgentId", callerAgentId);
|
||||
const token = readLocalCredential(paseoHome)!;
|
||||
const mcp = new Client({ name: "claude-steer-finish-test", version: "1.0.0" });
|
||||
try {
|
||||
await mcp.connect(new StreamableHTTPClientTransport(url));
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(url, {
|
||||
requestInit: { headers: { Authorization: `Bearer ${token}` } },
|
||||
}),
|
||||
);
|
||||
return await mcp.callTool({ name, arguments: args });
|
||||
} finally {
|
||||
await mcp.close();
|
||||
@@ -84,7 +91,7 @@ test("notifies the parent after a Claude steer runs in its own turn", async ({ s
|
||||
title: "Finish caller",
|
||||
modeId: "full-access",
|
||||
});
|
||||
const created = await callAgentTool(daemon.port, caller.id, "create_agent", {
|
||||
const created = await callAgentTool(daemon.port, daemon.paseoHome, caller.id, "create_agent", {
|
||||
relationship: { kind: "subagent" },
|
||||
workspace: { kind: "current" },
|
||||
provider: "claude/haiku",
|
||||
@@ -101,11 +108,17 @@ test("notifies the parent after a Claude steer runs in its own turn", async ({ s
|
||||
{ timeout: 45_000, interval: 50 },
|
||||
);
|
||||
|
||||
const steer = await callAgentTool(daemon.port, caller.id, "send_agent_prompt", {
|
||||
agentId: childId,
|
||||
activeTurnBehavior: "steer",
|
||||
prompt: `Reply with exactly ${token}. Use no tools.`,
|
||||
});
|
||||
const steer = await callAgentTool(
|
||||
daemon.port,
|
||||
daemon.paseoHome,
|
||||
caller.id,
|
||||
"send_agent_prompt",
|
||||
{
|
||||
agentId: childId,
|
||||
activeTurnBehavior: "steer",
|
||||
prompt: `Reply with exactly ${token}. Use no tools.`,
|
||||
},
|
||||
);
|
||||
expect(steer.isError).not.toBe(true);
|
||||
expect(steer.structuredContent).toMatchObject({ deliveryStatus: "queued" });
|
||||
writeFileSync(hookReleasePath, "");
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { expect, test } from "vitest";
|
||||
import { createDaemonTestContext } from "../test-utils/index.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
|
||||
test("an attended MCP caller can discover and supply a cross-provider child mode", async () => {
|
||||
const artifacts = path.join(process.cwd(), ".artifacts");
|
||||
@@ -18,9 +19,13 @@ test("an attended MCP caller can discover and supply a cross-provider child mode
|
||||
modeId: "auto",
|
||||
title: "Attended parent",
|
||||
});
|
||||
const localToken = readLocalCredential(ctx.daemon.paseoHome)!;
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${ctx.daemon.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
new URL(
|
||||
`http://127.0.0.1:${ctx.daemon.port}/_internal/mcp/agents?callerAgentId=${parent.id}`,
|
||||
),
|
||||
{ requestInit: { headers: { Authorization: `Bearer ${localToken}` } } },
|
||||
),
|
||||
);
|
||||
const { tools } = await mcp.listTools();
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "../agent/agent-messages/index.js";
|
||||
import { openDaemonDatabase } from "../database/index.js";
|
||||
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import type { PersistenceHandle } from "@getpaseo/protocol/messages";
|
||||
|
||||
function tmpCwd(): string {
|
||||
@@ -153,7 +154,12 @@ test.each([false, true])(
|
||||
mcp = new Client({ name: "durable-parent", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${first.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
new URL(`http://127.0.0.1:${first.port}/_internal/mcp/agents?callerAgentId=${parent.id}`),
|
||||
{
|
||||
requestInit: {
|
||||
headers: { Authorization: `Bearer ${readLocalCredential(first.paseoHome)!}` },
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
const result = await mcp.callTool({
|
||||
@@ -458,7 +464,12 @@ test.each([false, true])(
|
||||
const mcp = new Client({ name: "queue-parent", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${first.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
new URL(`http://127.0.0.1:${first.port}/_internal/mcp/agents?callerAgentId=${parent.id}`),
|
||||
{
|
||||
requestInit: {
|
||||
headers: { Authorization: `Bearer ${readLocalCredential(first.paseoHome)!}` },
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
const sent = await mcp.callTool({
|
||||
@@ -503,7 +514,12 @@ test("Stop holds the queue and its finish notice across a restart until the next
|
||||
const mcp = new Client({ name: "held-parent", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${first.port}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
new URL(`http://127.0.0.1:${first.port}/_internal/mcp/agents?callerAgentId=${parent.id}`),
|
||||
{
|
||||
requestInit: {
|
||||
headers: { Authorization: `Bearer ${readLocalCredential(first.paseoHome)!}` },
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
await mcp.callTool({
|
||||
|
||||
@@ -0,0 +1,725 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { createServer as createHttpServer, request as httpRequest } from "node:http";
|
||||
import net from "node:net";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import {
|
||||
Client as McpClient,
|
||||
StreamableHTTPClientTransport,
|
||||
UnauthorizedError,
|
||||
type OAuthClientProvider,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import { createPaseoApi } from "@getpaseo/client";
|
||||
import { createHostClient } from "@getpaseo/client/node";
|
||||
import { MCP_SERVER_PERMISSION_PRESETS, type DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
|
||||
const APP_REDIRECT = "http://127.0.0.1:9/callback";
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
const server = net.createServer();
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
if (typeof address !== "object" || !address) throw new Error("No port");
|
||||
return address.port;
|
||||
}
|
||||
|
||||
/** An MCP app's OAuth state, kept in memory the way a real app keeps it on disk. */
|
||||
class AppOAuthProvider implements OAuthClientProvider {
|
||||
authorizationUrl: URL | null = null;
|
||||
private information: Awaited<ReturnType<OAuthClientProvider["clientInformation"]>>;
|
||||
private saved: Awaited<ReturnType<OAuthClientProvider["tokens"]>>;
|
||||
private verifier = "";
|
||||
|
||||
get redirectUrl() {
|
||||
return APP_REDIRECT;
|
||||
}
|
||||
get clientMetadata() {
|
||||
return {
|
||||
client_name: "Test App",
|
||||
redirect_uris: [APP_REDIRECT],
|
||||
grant_types: ["authorization_code"],
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "none",
|
||||
};
|
||||
}
|
||||
clientInformation() {
|
||||
return this.information;
|
||||
}
|
||||
saveClientInformation(information: NonNullable<typeof this.information>) {
|
||||
this.information = information;
|
||||
}
|
||||
tokens() {
|
||||
return this.saved;
|
||||
}
|
||||
saveTokens(tokens: NonNullable<typeof this.saved>) {
|
||||
this.saved = tokens;
|
||||
}
|
||||
redirectToAuthorization(url: URL) {
|
||||
this.authorizationUrl = url;
|
||||
}
|
||||
saveCodeVerifier(verifier: string) {
|
||||
this.verifier = verifier;
|
||||
}
|
||||
codeVerifier() {
|
||||
return this.verifier;
|
||||
}
|
||||
}
|
||||
|
||||
async function browserGet(url: string | URL): Promise<Response> {
|
||||
return fetch(url, { redirect: "manual" });
|
||||
}
|
||||
|
||||
async function connectApp(mcpUrl: string, provider: AppOAuthProvider): Promise<McpClient> {
|
||||
const client = new McpClient({ name: "test-app", version: "0.0.0" });
|
||||
await client.connect(
|
||||
new StreamableHTTPClientTransport(new URL(mcpUrl), { authProvider: provider }),
|
||||
);
|
||||
return client;
|
||||
}
|
||||
|
||||
function pkcePair(): { verifier: string; challenge: string } {
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
|
||||
}
|
||||
|
||||
async function connectMcpWithHeaders(
|
||||
mcpUrl: string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<McpClient> {
|
||||
const client = new McpClient({ name: "direct-app", version: "0.0.0" });
|
||||
await client.connect(
|
||||
new StreamableHTTPClientTransport(new URL(mcpUrl), {
|
||||
requestInit: headers ? { headers } : undefined,
|
||||
}),
|
||||
);
|
||||
return client;
|
||||
}
|
||||
|
||||
async function listToolsWithHeaders(
|
||||
mcpUrl: string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<string[]> {
|
||||
const client = await connectMcpWithHeaders(mcpUrl, headers);
|
||||
try {
|
||||
return (await client.listTools()).tools.map((tool) => tool.name);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function rawGet(
|
||||
base: string,
|
||||
pathname: string,
|
||||
headers: Record<string, string>,
|
||||
): Promise<{ status: number; body: string }> {
|
||||
const url = new URL(pathname, base);
|
||||
return await new Promise((resolve, reject) => {
|
||||
const req = httpRequest(
|
||||
{ host: url.hostname, port: url.port, path: url.pathname, method: "GET", headers },
|
||||
(res) => {
|
||||
let body = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk: string) => (body += chunk));
|
||||
res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function forwardWireFrame(
|
||||
data: unknown,
|
||||
binary: boolean,
|
||||
upstream: WebSocket,
|
||||
pending: Array<() => void>,
|
||||
routedHellos: Array<{ sessionPermissions?: DaemonPermission[] }>,
|
||||
getForcedPermissions: () => DaemonPermission[] | null,
|
||||
): void {
|
||||
let bytes = Buffer.from(data as Buffer);
|
||||
if (!binary) {
|
||||
const envelope = JSON.parse(bytes.toString()) as {
|
||||
type?: string;
|
||||
message?: { type?: string; data?: string };
|
||||
};
|
||||
if (envelope.type === "session" && envelope.message?.type === "hosts.route.frame.request") {
|
||||
const inner = JSON.parse(envelope.message.data ?? "{}") as {
|
||||
type?: string;
|
||||
sessionPermissions?: DaemonPermission[];
|
||||
};
|
||||
if (inner.type === "hello") {
|
||||
routedHellos.push({ sessionPermissions: inner.sessionPermissions });
|
||||
}
|
||||
}
|
||||
const forced = getForcedPermissions();
|
||||
if (forced && envelope.type === "hello") {
|
||||
(envelope as { sessionPermissions?: DaemonPermission[] }).sessionPermissions = forced;
|
||||
bytes = Buffer.from(JSON.stringify(envelope));
|
||||
}
|
||||
}
|
||||
const send = () => {
|
||||
if (upstream.readyState === 1) upstream.send(bytes, { binary });
|
||||
};
|
||||
if (upstream.readyState === 0) pending.push(send);
|
||||
else send();
|
||||
}
|
||||
|
||||
function closeWireServer(wireWss: WebSocketServer, wireHttp: ReturnType<typeof createHttpServer>) {
|
||||
return async () => {
|
||||
for (const socket of wireWss.clients) socket.terminate();
|
||||
await new Promise<void>((resolve) => {
|
||||
wireWss.close(() => resolve());
|
||||
});
|
||||
await new Promise<void>((resolve) => {
|
||||
wireHttp.close(() => resolve());
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function attachWireConnection(
|
||||
downstream: WebSocket,
|
||||
targetPort: number,
|
||||
routedHellos: Array<{ sessionPermissions?: DaemonPermission[] }>,
|
||||
getForcedPermissions: () => DaemonPermission[] | null,
|
||||
): void {
|
||||
const upstream = new WebSocket(`ws://127.0.0.1:${targetPort}/ws`);
|
||||
const pending: Array<() => void> = [];
|
||||
upstream.on("open", () => {
|
||||
for (const send of pending.splice(0)) send();
|
||||
});
|
||||
downstream.on("message", (data, binary) =>
|
||||
forwardWireFrame(data, binary, upstream, pending, routedHellos, getForcedPermissions),
|
||||
);
|
||||
upstream.on("message", (data, binary) => {
|
||||
if (downstream.readyState === 1) downstream.send(Buffer.from(data as Buffer), { binary });
|
||||
});
|
||||
const closeBoth = () => {
|
||||
downstream.close();
|
||||
upstream.close();
|
||||
};
|
||||
upstream.on("error", closeBoth);
|
||||
upstream.on("close", closeBoth);
|
||||
downstream.on("close", closeBoth);
|
||||
}
|
||||
|
||||
async function createInspectingHostWire(
|
||||
targetPort: number,
|
||||
cleanup: Array<() => Promise<unknown>>,
|
||||
) {
|
||||
let forceLinkPermissions: DaemonPermission[] | null = null;
|
||||
const routedHellos: Array<{ sessionPermissions?: DaemonPermission[] }> = [];
|
||||
const wireHttp = createHttpServer();
|
||||
const wireWss = new WebSocketServer({ server: wireHttp });
|
||||
wireWss.on("connection", (downstream) =>
|
||||
attachWireConnection(downstream, targetPort, routedHellos, () => forceLinkPermissions),
|
||||
);
|
||||
wireHttp.listen(0, "127.0.0.1");
|
||||
await once(wireHttp, "listening");
|
||||
cleanup.push(closeWireServer(wireWss, wireHttp));
|
||||
const wireAddr = wireHttp.address();
|
||||
if (!wireAddr || typeof wireAddr === "string") throw new Error("Missing wire address");
|
||||
return {
|
||||
port: wireAddr.port,
|
||||
routedHellos,
|
||||
setForceLinkPermissions: (permissions: DaemonPermission[] | null) => {
|
||||
forceLinkPermissions = permissions;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("MCP Server", () => {
|
||||
let daemon: TestPaseoDaemon;
|
||||
let owner: DaemonClient;
|
||||
let base: string;
|
||||
let mcpUrl: string;
|
||||
const extraCleanup: Array<() => Promise<unknown>> = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
daemon = await createTestPaseoDaemon();
|
||||
owner = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
await owner.connect();
|
||||
const port = await freePort();
|
||||
const status = await owner.configureMcpServer({ enabled: true, port });
|
||||
expect(status.listener).toMatchObject({ state: "listening", port });
|
||||
expect(status.auth).toEqual({
|
||||
oauth: true,
|
||||
bearerTokens: true,
|
||||
defaultPermissions: [],
|
||||
});
|
||||
base = `http://127.0.0.1:${port}`;
|
||||
mcpUrl = `${base}/mcp`;
|
||||
expect(status.mcpUrls).toEqual([mcpUrl]);
|
||||
}, 60_000);
|
||||
|
||||
afterEach(async () => {
|
||||
for (const close of extraCleanup.splice(0).toReversed()) {
|
||||
await close();
|
||||
}
|
||||
await owner?.close();
|
||||
await daemon?.close();
|
||||
}, 60_000);
|
||||
|
||||
test("(a) serves top-level tools even when daemon.tools.enabled is false", async () => {
|
||||
await owner.patchDaemonConfig({ tools: { enabled: false } });
|
||||
const { token } = await owner.createMcpServerToken({
|
||||
label: "Tools-off client",
|
||||
permissions: [...MCP_SERVER_PERMISSION_PRESETS.read],
|
||||
});
|
||||
|
||||
const client = await connectMcpWithHeaders(mcpUrl, { Authorization: `Bearer ${token}` });
|
||||
try {
|
||||
const tools = (await client.listTools()).tools.map((tool) => tool.name);
|
||||
expect(tools).toContain("list_agents");
|
||||
expect(tools).toContain("list_hosts");
|
||||
expect(tools).toContain("list_workspaces");
|
||||
expect(tools).not.toContain("create_agent");
|
||||
const listed = await client.callTool({ name: "list_agents", arguments: {} });
|
||||
expect(listed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("(b) oauth=false, bearerTokens=false serves unauthenticated /mcp with defaultPermissions, skips 421, and rejects Origin", async () => {
|
||||
const status = await owner.configureMcpServer({
|
||||
auth: {
|
||||
oauth: false,
|
||||
bearerTokens: false,
|
||||
defaultPermissions: ["daemon.read", "workspace.read"],
|
||||
},
|
||||
});
|
||||
expect(status.auth).toEqual({
|
||||
oauth: false,
|
||||
bearerTokens: false,
|
||||
defaultPermissions: ["daemon.read", "workspace.read"],
|
||||
});
|
||||
|
||||
// Direct unauthenticated client connects and receives only defaultPermissions tools.
|
||||
const client = await connectMcpWithHeaders(mcpUrl);
|
||||
try {
|
||||
const tools = (await client.listTools()).tools.map((tool) => tool.name);
|
||||
expect(tools).toContain("list_agents");
|
||||
expect(tools).toContain("list_hosts");
|
||||
expect(tools).not.toContain("create_agent");
|
||||
const listed = await client.callTool({ name: "list_agents", arguments: {} });
|
||||
expect(listed.isError).not.toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
|
||||
// Updating defaultPermissions updates subsequent tool calls live.
|
||||
await owner.configureMcpServer({
|
||||
auth: { defaultPermissions: ["daemon.read"] },
|
||||
});
|
||||
const narrowedTools = await listToolsWithHeaders(mcpUrl);
|
||||
expect(narrowedTools).toContain("list_hosts");
|
||||
expect(narrowedTools).not.toContain("list_agents");
|
||||
|
||||
// OAuth endpoints are unmounted, unknown Host does not 421, and browser Origin still gets 403.
|
||||
expect((await fetch(`${base}/.well-known/oauth-authorization-server`)).status).toBe(404);
|
||||
expect((await fetch(`${base}/oauth/register`, { method: "POST" })).status).toBe(404);
|
||||
expect((await rawGet(base, "/mcp", { Host: "custom-proxy.internal:6770" })).status).toBe(405);
|
||||
|
||||
const fromBrowser = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: { Origin: "https://evil.example", "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
|
||||
});
|
||||
expect(fromBrowser.status).toBe(403);
|
||||
}, 60_000);
|
||||
|
||||
test("(c) bearerTokens=true, oauth=false enforces static tokens, rejects OAuth credentials, skips 421, and omits resource_metadata", async () => {
|
||||
// Mint an OAuth credential before turning OAuth off.
|
||||
const app = new AppOAuthProvider();
|
||||
await expect(connectApp(mcpUrl, app)).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
const waitingUrl = new URL(
|
||||
(await browserGet(app.authorizationUrl!)).headers.get("location")!,
|
||||
base,
|
||||
);
|
||||
const { approvals } = await owner.listMcpServerAccess();
|
||||
await owner.decideMcpServerApproval({
|
||||
approvalId: approvals[0]!.id,
|
||||
decision: "approve",
|
||||
permissions: ["daemon.read"],
|
||||
});
|
||||
const callback = new URL((await browserGet(waitingUrl)).headers.get("location")!);
|
||||
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), { authProvider: app });
|
||||
await transport.finishAuth(callback.searchParams);
|
||||
const oauthAccessToken = app.tokens()!.access_token;
|
||||
|
||||
// Disable OAuth while keeping static Bearer tokens on.
|
||||
await owner.configureMcpServer({ auth: { oauth: false, bearerTokens: true } });
|
||||
|
||||
// OAuth routes are unmounted and unknown Host is not rejected with 421.
|
||||
expect((await fetch(`${base}/.well-known/oauth-protected-resource/mcp`)).status).toBe(404);
|
||||
expect((await fetch(`${base}/oauth/register`, { method: "POST" })).status).toBe(404);
|
||||
expect((await rawGet(base, "/mcp", { Host: "custom-proxy.internal" })).status).toBe(401);
|
||||
|
||||
// 401 omits resource_metadata when OAuth is off.
|
||||
const unauth = await fetch(mcpUrl, { method: "POST" });
|
||||
expect(unauth.status).toBe(401);
|
||||
expect(unauth.headers.get("www-authenticate")).toBe("Bearer");
|
||||
|
||||
// Existing OAuth credential is rejected while oauth=false.
|
||||
const rejectedOAuth = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${oauthAccessToken}` },
|
||||
});
|
||||
expect(rejectedOAuth.status).toBe(401);
|
||||
expect(rejectedOAuth.headers.get("www-authenticate")).toBe('Bearer error="invalid_token"');
|
||||
|
||||
// Static Bearer token works until revoked, and credentials file stays hashed with mode 0600.
|
||||
const { credential, token } = await owner.createMcpServerToken({
|
||||
label: "CI",
|
||||
permissions: [...MCP_SERVER_PERMISSION_PRESETS.full],
|
||||
});
|
||||
expect(credential).toMatchObject({ label: "CI", authKind: "token", redirectHost: null });
|
||||
const tools = await listToolsWithHeaders(mcpUrl, { Authorization: `Bearer ${token}` });
|
||||
expect(tools).toContain("create_workspace");
|
||||
expect(tools).not.toContain("speak");
|
||||
|
||||
const file = path.join(daemon.paseoHome, "mcp-server", "credentials.json");
|
||||
// Windows exposes inherited ACLs rather than POSIX mode bits.
|
||||
if (process.platform !== "win32") {
|
||||
expect((await stat(file)).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
expect(await readFile(file, "utf8")).not.toContain(token.slice(-43));
|
||||
|
||||
await owner.revokeMcpServerCredential(credential.id);
|
||||
await expect(
|
||||
listToolsWithHeaders(mcpUrl, { Authorization: `Bearer ${token}` }),
|
||||
).rejects.toThrow();
|
||||
}, 60_000);
|
||||
|
||||
test("(d) oauth=true, bearerTokens=false rejects static Bearer tokens and completes OAuth 2.1 + PKCE + live approval + one-time code fallback", async () => {
|
||||
const { token: staticToken } = await owner.createMcpServerToken({
|
||||
label: "Static",
|
||||
permissions: ["daemon.read"],
|
||||
});
|
||||
await owner.configureMcpServer({ auth: { oauth: true, bearerTokens: false } });
|
||||
|
||||
const rejectedStatic = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${staticToken}` },
|
||||
});
|
||||
expect(rejectedStatic.status).toBe(401);
|
||||
expect(rejectedStatic.headers.get("www-authenticate")).toBe(
|
||||
`Bearer error="invalid_token", resource_metadata="${base}/.well-known/oauth-protected-resource/mcp"`,
|
||||
);
|
||||
|
||||
// 1. Live in-app approval + PKCE + revocation.
|
||||
const app = new AppOAuthProvider();
|
||||
await expect(connectApp(mcpUrl, app)).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
expect(app.authorizationUrl?.origin).toBe(base);
|
||||
|
||||
const authorize = await browserGet(app.authorizationUrl!);
|
||||
expect(authorize.status).toBe(303);
|
||||
const waitingUrl = new URL(authorize.headers.get("location")!, base);
|
||||
const waiting = await browserGet(waitingUrl);
|
||||
expect(waiting.status).toBe(200);
|
||||
expect(waiting.headers.get("content-security-policy")).toContain("frame-ancestors 'none'");
|
||||
expect(waiting.headers.get("x-frame-options")).toBe("DENY");
|
||||
expect(waiting.headers.get("cache-control")).toBe("no-store");
|
||||
const page = await waiting.text();
|
||||
|
||||
const { approvals } = await owner.listMcpServerAccess();
|
||||
expect(approvals).toHaveLength(1);
|
||||
expect(approvals[0]).toMatchObject({ clientName: "Test App", redirectHost: "127.0.0.1:9" });
|
||||
expect(page).toContain(approvals[0]!.verificationCode);
|
||||
|
||||
await owner.decideMcpServerApproval({
|
||||
approvalId: approvals[0]!.id,
|
||||
decision: "approve",
|
||||
permissions: [...MCP_SERVER_PERMISSION_PRESETS.read],
|
||||
});
|
||||
const handoff = await browserGet(waitingUrl);
|
||||
expect(handoff.status).toBe(303);
|
||||
const callback = new URL(handoff.headers.get("location")!);
|
||||
expect(`${callback.origin}${callback.pathname}`).toBe(APP_REDIRECT);
|
||||
expect(callback.searchParams.get("iss")).toBe(base);
|
||||
|
||||
const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), { authProvider: app });
|
||||
await transport.finishAuth(callback.searchParams);
|
||||
const client = await connectApp(mcpUrl, app);
|
||||
try {
|
||||
const tools = (await client.listTools()).tools.map((tool) => tool.name);
|
||||
expect(tools).toContain("list_agents");
|
||||
expect(tools).toContain("list_hosts");
|
||||
expect(tools).not.toContain("create_agent");
|
||||
expect(tools).not.toContain("speak");
|
||||
const listed = await client.callTool({ name: "list_agents", arguments: {} });
|
||||
expect(listed.isError).not.toBe(true);
|
||||
await expect(client.callTool({ name: "create_agent", arguments: {} })).rejects.toThrow(
|
||||
"Tool create_agent not found",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
|
||||
const access = await owner.listMcpServerAccess();
|
||||
expect(access.approvals).toEqual([]);
|
||||
expect(access.credentials).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
label: "Test App",
|
||||
authKind: "oauth",
|
||||
permissions: [...MCP_SERVER_PERMISSION_PRESETS.read],
|
||||
redirectHost: "127.0.0.1:9",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const oauthCred = access.credentials.find((c) => c.authKind === "oauth")!;
|
||||
expect(oauthCred.lastUsedAt).not.toBeNull();
|
||||
expect(await owner.revokeMcpServerCredential(oauthCred.id)).toBe(true);
|
||||
const revoked = new AppOAuthProvider();
|
||||
revoked.saveTokens(app.tokens()!);
|
||||
await expect(connectApp(mcpUrl, revoked)).rejects.toBeInstanceOf(UnauthorizedError);
|
||||
|
||||
// 2. Flood /oauth/authorize past the per-IP pending limit -> one-time approval code still works
|
||||
// by bypassing the pending queue to /oauth/authorize/code.
|
||||
const reg = await fetch(`${base}/oauth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ client_name: "Code App", redirect_uris: [APP_REDIRECT] }),
|
||||
});
|
||||
expect(reg.status).toBe(201);
|
||||
const { client_id: clientId } = (await reg.json()) as { client_id: string };
|
||||
const floodPkce = pkcePair();
|
||||
const buildAuthorize = (state: string, challenge = floodPkce.challenge) => {
|
||||
const u = new URL(`${base}/oauth/authorize`);
|
||||
u.search = new URLSearchParams({
|
||||
response_type: "code",
|
||||
client_id: clientId,
|
||||
redirect_uri: APP_REDIRECT,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
state,
|
||||
resource: mcpUrl,
|
||||
}).toString();
|
||||
return u;
|
||||
};
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
await browserGet(buildAuthorize(`flood_${i}`));
|
||||
}
|
||||
// Per-IP limit caps pending approvals created from 127.0.0.1 at 5 per 60s (1 was opened above).
|
||||
expect((await owner.listMcpServerAccess()).approvals).toHaveLength(4);
|
||||
|
||||
const ownerPkce = pkcePair();
|
||||
const ownerAuthRes = await browserGet(buildAuthorize("owner_code", ownerPkce.challenge));
|
||||
expect(ownerAuthRes.status).toBe(303);
|
||||
const directCodeUrl = new URL(ownerAuthRes.headers.get("location")!, base);
|
||||
expect(directCodeUrl.pathname).toBe("/oauth/authorize/code");
|
||||
|
||||
const { code } = await owner.createMcpServerApprovalCode([
|
||||
...MCP_SERVER_PERMISSION_PRESETS.orchestrate,
|
||||
]);
|
||||
const codeSubmit = await fetch(directCodeUrl, {
|
||||
method: "POST",
|
||||
redirect: "manual",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ code: code.toLowerCase() }),
|
||||
});
|
||||
expect(codeSubmit.status).toBe(303);
|
||||
const codeCallback = new URL(codeSubmit.headers.get("location")!);
|
||||
expect(codeCallback.searchParams.get("state")).toBe("owner_code");
|
||||
|
||||
const tokenRes = await fetch(`${base}/oauth/token`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: codeCallback.searchParams.get("code")!,
|
||||
redirect_uri: APP_REDIRECT,
|
||||
client_id: clientId,
|
||||
code_verifier: ownerPkce.verifier,
|
||||
resource: mcpUrl,
|
||||
}),
|
||||
});
|
||||
expect(tokenRes.status).toBe(200);
|
||||
const { access_token: codeAccessToken } = (await tokenRes.json()) as { access_token: string };
|
||||
const codeTools = await listToolsWithHeaders(mcpUrl, {
|
||||
Authorization: `Bearer ${codeAccessToken}`,
|
||||
});
|
||||
expect(codeTools).toContain("create_agent");
|
||||
expect(codeTools).not.toContain("create_workspace");
|
||||
}, 60_000);
|
||||
|
||||
test("(e) connected-host calls enforce narrower credential permissions and link intersection", async () => {
|
||||
const b = await createTestPaseoDaemon();
|
||||
extraCleanup.push(() => b.close());
|
||||
const bAdmin = createHostClient(`127.0.0.1:${b.port}`, {
|
||||
clientId: "b-admin",
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await bAdmin.connect();
|
||||
extraCleanup.push(() => bAdmin.close());
|
||||
const bApi = createPaseoApi(bAdmin);
|
||||
extraCleanup.push(() => bApi.dispose());
|
||||
const bWorkspace = await bApi.workspaces.create({
|
||||
source: { kind: "directory", path: b.staticDir },
|
||||
title: "Host B Workspace",
|
||||
});
|
||||
|
||||
const wire = await createInspectingHostWire(b.port, extraCleanup);
|
||||
|
||||
const aAdmin = createHostClient(`127.0.0.1:${daemon.port}`, {
|
||||
clientId: "a-admin",
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await aAdmin.connect();
|
||||
extraCleanup.push(() => aAdmin.close());
|
||||
const aApi = createPaseoApi(aAdmin);
|
||||
extraCleanup.push(() => aApi.dispose());
|
||||
const savedHost = await aApi.hosts.add({
|
||||
connection: `127.0.0.1:${wire.port}`,
|
||||
label: "Fleet B",
|
||||
});
|
||||
|
||||
let bServerId!: string;
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const dir = await aApi.hosts.list();
|
||||
bServerId = dir.hosts[0]?.serverId ?? "";
|
||||
return dir.hosts[0]?.status;
|
||||
},
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toBe("online");
|
||||
|
||||
// 1. Credential narrower than full link: A->B link holds owner permissions, but MCP credential
|
||||
// holds only ["daemon.read", "workspace.read"]. Routed hello forwards only credential grants.
|
||||
const { token: readToken } = await owner.createMcpServerToken({
|
||||
label: "Read only fleet",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
});
|
||||
const readClient = await connectMcpWithHeaders(mcpUrl, {
|
||||
Authorization: `Bearer ${readToken}`,
|
||||
});
|
||||
try {
|
||||
const listed = await readClient.callTool({
|
||||
name: "list_workspaces",
|
||||
arguments: { serverId: bServerId },
|
||||
});
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(JSON.stringify(listed.structuredContent)).toContain(bWorkspace.id);
|
||||
expect(wire.routedHellos).toEqual([
|
||||
{ sessionPermissions: ["daemon.read", "workspace.read"] },
|
||||
]);
|
||||
await expect(
|
||||
readClient.callTool({
|
||||
name: "create_agent",
|
||||
arguments: {
|
||||
serverId: bServerId,
|
||||
workspaceId: bWorkspace.id,
|
||||
provider: "claude/claude-test",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("Tool create_agent not found");
|
||||
} finally {
|
||||
await readClient.close();
|
||||
}
|
||||
|
||||
// 2. Link narrower than credential: reconnect physical link with only ["daemon.read", "workspace.read"]
|
||||
// while MCP credential holds ["daemon.read", "workspace.read", "workspace.write"].
|
||||
// B intersects forwarded grants with the link's authority and denies create_agent on B.
|
||||
wire.setForceLinkPermissions(["daemon.read", "workspace.read"]);
|
||||
await aApi.hosts.update(savedHost.registrationId, { enabled: false });
|
||||
await aApi.hosts.update(savedHost.registrationId, { enabled: true });
|
||||
await expect
|
||||
.poll(async () => (await aApi.hosts.list()).hosts[0]?.status, { timeout: 15_000 })
|
||||
.toBe("online");
|
||||
|
||||
const { token: writeToken } = await owner.createMcpServerToken({
|
||||
label: "Write local only",
|
||||
permissions: ["daemon.read", "workspace.read", "workspace.write"],
|
||||
});
|
||||
const writeClient = await connectMcpWithHeaders(mcpUrl, {
|
||||
Authorization: `Bearer ${writeToken}`,
|
||||
});
|
||||
try {
|
||||
const readB = await writeClient.callTool({
|
||||
name: "list_workspaces",
|
||||
arguments: { serverId: bServerId },
|
||||
});
|
||||
expect(readB.isError).not.toBe(true);
|
||||
|
||||
const deniedOnB = await writeClient.callTool({
|
||||
name: "create_agent",
|
||||
arguments: {
|
||||
serverId: bServerId,
|
||||
workspaceId: bWorkspace.id,
|
||||
provider: "claude/claude-test",
|
||||
},
|
||||
});
|
||||
expect(deniedOnB.isError).toBe(true);
|
||||
} finally {
|
||||
await writeClient.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("(f) refuses browser Origin, unknown hosts in OAuth mode, and unregistered redirects, and stays isolated from daemon port", async () => {
|
||||
const { token } = await owner.createMcpServerToken({
|
||||
label: "browser",
|
||||
permissions: ["daemon.read"],
|
||||
});
|
||||
const fromBrowser = await fetch(mcpUrl, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}`, Origin: "https://evil.example" },
|
||||
});
|
||||
expect(fromBrowser.status).toBe(403);
|
||||
|
||||
const spoofed = await rawGet(base, "/.well-known/oauth-authorization-server", {
|
||||
Host: "evil.example",
|
||||
});
|
||||
expect(spoofed.status).toBe(421);
|
||||
|
||||
const forwardedSpoof = await rawGet(base, "/.well-known/oauth-authorization-server", {
|
||||
Host: new URL(base).host,
|
||||
"X-Forwarded-Host": "evil.example",
|
||||
});
|
||||
expect(JSON.parse(forwardedSpoof.body)).toMatchObject({ issuer: base });
|
||||
|
||||
await owner.configureMcpServer({ publicUrl: "https://mcp.example.com" });
|
||||
const viaProxy = await rawGet(base, "/.well-known/oauth-protected-resource/mcp", {
|
||||
Host: new URL(base).host,
|
||||
"X-Forwarded-Host": "mcp.example.com",
|
||||
});
|
||||
expect(JSON.parse(viaProxy.body)).toMatchObject({
|
||||
resource: "https://mcp.example.com/mcp",
|
||||
authorization_servers: ["https://mcp.example.com"],
|
||||
});
|
||||
expect((await owner.getMcpServerStatus()).mcpUrls).toEqual([
|
||||
"https://mcp.example.com/mcp",
|
||||
mcpUrl,
|
||||
]);
|
||||
|
||||
const insecure = await fetch(`${base}/oauth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ redirect_uris: ["http://evil.example/callback"] }),
|
||||
});
|
||||
expect(insecure.status).toBe(400);
|
||||
|
||||
// The listener serves nothing of the daemon's own API, and the daemon port never serves /mcp or /oauth/*.
|
||||
expect((await fetch(`${base}/api/health`)).status).toBe(404);
|
||||
expect((await fetch(`http://127.0.0.1:${daemon.port}/oauth/register`)).status).not.toBe(201);
|
||||
expect(
|
||||
(await fetch(`http://127.0.0.1:${daemon.port}/mcp`, { method: "POST" })).status,
|
||||
).not.toBe(200);
|
||||
|
||||
// Turning MCP Server off closes the listener and keeps the config.
|
||||
const stopped = await owner.configureMcpServer({ enabled: false });
|
||||
expect(stopped.listener.state).toBe("stopped");
|
||||
expect(stopped.mcpUrls).toEqual([]);
|
||||
await expect(fetch(mcpUrl, { method: "POST" })).rejects.toThrow();
|
||||
const restarted = await owner.configureMcpServer({ enabled: true });
|
||||
expect(restarted.listener).toMatchObject({ state: "listening", port: stopped.listener.port });
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../agent/providers/omp/agent.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { readLocalCredential } from "../local-credential.js";
|
||||
import { createRealProviderClients, getRealProviderConfig } from "./real-provider-test-config.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -409,11 +410,13 @@ describe("daemon E2E (real OMP)", () => {
|
||||
try {
|
||||
const parent = await createAgent(harness, "follow-up-parent");
|
||||
const child = await createAgent(harness, "follow-up-child");
|
||||
const token = readLocalCredential(harness.daemon.paseoHome)!;
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(
|
||||
`http://127.0.0.1:${harness.daemon.port}/mcp/agents?callerAgentId=${parent.id}`,
|
||||
`http://127.0.0.1:${harness.daemon.port}/_internal/mcp/agents?callerAgentId=${parent.id}`,
|
||||
),
|
||||
{ requestInit: { headers: { Authorization: `Bearer ${token}` } } },
|
||||
),
|
||||
);
|
||||
const response = await mcp.callTool({
|
||||
|
||||
@@ -70,7 +70,7 @@ describe("createLoopbackAgentEndpoint", () => {
|
||||
target: { type: "tcp", host: "127.0.0.1", port: 6767 },
|
||||
dedicated: false,
|
||||
});
|
||||
expect(endpoint.getMcpBaseUrl()).toBe("http://127.0.0.1:6767/mcp/agents");
|
||||
expect(endpoint.getMcpBaseUrl()).toBe("http://127.0.0.1:6767/_internal/mcp/agents");
|
||||
expect(endpoint.getTerminalActivityUrl()).toBe("http://127.0.0.1:6767/api/terminal-activity");
|
||||
|
||||
await endpoint.stop();
|
||||
@@ -130,6 +130,10 @@ describe("createLoopbackAgentEndpoint", () => {
|
||||
expect(activityBodies).toEqual([{ terminalId: "t1", token: "tok", state: "running" }]);
|
||||
|
||||
// Unmounted daemon routes are never served on the internal loopback server.
|
||||
const legacyResponse = await fetch(`http://127.0.0.1:${started.target.port}/mcp/agents`, {
|
||||
method: "POST",
|
||||
});
|
||||
expect(legacyResponse.status).toBe(404);
|
||||
const statusResponse = await fetch(`http://127.0.0.1:${started.target.port}/api/status`);
|
||||
expect(statusResponse.status).toBe(404);
|
||||
const healthResponse = await fetch(`http://127.0.0.1:${started.target.port}/api/health`);
|
||||
@@ -141,7 +145,7 @@ describe("createLoopbackAgentEndpoint", () => {
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port: started.target.port,
|
||||
path: "/mcp/agents",
|
||||
path: "/_internal/mcp/agents",
|
||||
method: "POST",
|
||||
headers: {
|
||||
host: `attacker.invalid:${started.target.port}`,
|
||||
|
||||
@@ -70,7 +70,7 @@ export function createAgentMcpBaseUrl(listenTarget: ListenTarget | null): string
|
||||
return null;
|
||||
}
|
||||
return new URL(
|
||||
"/mcp/agents",
|
||||
"/_internal/mcp/agents",
|
||||
`http://${formatHostForHttpUrl(loopbackTarget.host)}:${loopbackTarget.port}`,
|
||||
).toString();
|
||||
}
|
||||
@@ -149,9 +149,9 @@ export function createLoopbackAgentEndpoint(
|
||||
});
|
||||
internalApp.use(express.json());
|
||||
|
||||
internalApp.post("/mcp/agents", options.handleAgentMcpRequest);
|
||||
internalApp.get("/mcp/agents", options.handleAgentMcpRequest);
|
||||
internalApp.delete("/mcp/agents", options.handleAgentMcpRequest);
|
||||
internalApp.post("/_internal/mcp/agents", options.handleAgentMcpRequest);
|
||||
internalApp.get("/_internal/mcp/agents", options.handleAgentMcpRequest);
|
||||
internalApp.delete("/_internal/mcp/agents", options.handleAgentMcpRequest);
|
||||
internalApp.post("/api/terminal-activity", options.handleTerminalActivityRequest);
|
||||
|
||||
const server = createHTTPServer(internalApp);
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { Client as McpClient, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
||||
import pino from "pino";
|
||||
import { z } from "zod";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import type { DaemonPermission, McpServerStatus } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonMcpServerConfig } from "../persisted-config.js";
|
||||
import { TunnelManager, type RegisteredTunnelProvider } from "../tunnels/manager.js";
|
||||
import { McpServerError, PaseoMcpServer } from "./index.js";
|
||||
|
||||
/** One tool per granted permission, so a test can read the grant back from tools/list. */
|
||||
function permissionServer(permissions: readonly DaemonPermission[]): McpServer {
|
||||
const server = new McpServer({ name: "test", version: "0.0.0" }, { capabilities: { tools: {} } });
|
||||
for (const permission of permissions) {
|
||||
server.registerTool(
|
||||
`tool_${permission.replace(".", "_")}`,
|
||||
{ description: permission, inputSchema: z.object({}) },
|
||||
async () => ({ content: [{ type: "text", text: permission }] }),
|
||||
);
|
||||
}
|
||||
return server;
|
||||
}
|
||||
|
||||
/** A tunnel provider that becomes ready at a fixed URL as soon as it opens. */
|
||||
function fakeTunnelProvider(url: string, opened: string[]): RegisteredTunnelProvider {
|
||||
return {
|
||||
id: "fake",
|
||||
pluginId: "fake-plugin",
|
||||
label: "Fake",
|
||||
status: async () => ({ status: "available" }),
|
||||
open(exposureId, target, callbacks) {
|
||||
opened.push(`${exposureId} ${target.host}:${target.port}`);
|
||||
queueMicrotask(() => callbacks.onEvent({ type: "ready", url, stability: "ephemeral" }));
|
||||
return { close: async () => callbacks.onClosed() };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("PaseoMcpServer", () => {
|
||||
let home: string;
|
||||
let config: DaemonMcpServerConfig;
|
||||
let tunnels: TunnelManager;
|
||||
let mcpServer: PaseoMcpServer;
|
||||
|
||||
beforeEach(async () => {
|
||||
home = await mkdtemp(path.join(os.tmpdir(), "paseo-mcp-server-"));
|
||||
config = {};
|
||||
tunnels = new TunnelManager();
|
||||
mcpServer = new PaseoMcpServer({
|
||||
paseoHome: home,
|
||||
config: {
|
||||
read: () => config,
|
||||
write: async (next) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
config = next;
|
||||
},
|
||||
},
|
||||
tunnels,
|
||||
createMcpServer: permissionServer,
|
||||
logger: pino({ level: "silent" }),
|
||||
defaultPort: 0,
|
||||
});
|
||||
await mcpServer.start();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await mcpServer.stop();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function listTools(url: string, token?: string): Promise<string[]> {
|
||||
const client = new McpClient({ name: "test", version: "0.0.0" });
|
||||
await client.connect(
|
||||
new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: token ? { headers: { Authorization: `Bearer ${token}` } } : undefined,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
return (await client.listTools()).tools.map((tool) => tool.name);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
function nextStatus(predicate: (status: McpServerStatus) => boolean) {
|
||||
return new Promise<McpServerStatus>((resolve) => {
|
||||
const stop = mcpServer.subscribeStatus((status) => {
|
||||
if (!predicate(status)) return;
|
||||
stop();
|
||||
resolve(status);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("preserves the saved tunnel provider while stopped and opens it when enabled", async () => {
|
||||
const opened: string[] = [];
|
||||
tunnels.registerProvider(fakeTunnelProvider("https://saved.tunnel.example", opened));
|
||||
|
||||
const stopped = await mcpServer.configure({ enabled: false, tunnelProviderId: "fake" });
|
||||
expect(stopped.tunnel).toEqual({
|
||||
providerId: "fake",
|
||||
state: "closed",
|
||||
url: null,
|
||||
stability: null,
|
||||
detail: null,
|
||||
error: null,
|
||||
});
|
||||
expect(stopped.mcpUrls).toEqual([]);
|
||||
expect(opened).toEqual([]);
|
||||
|
||||
const ready = nextStatus((status) => status.tunnel?.state === "ready");
|
||||
await mcpServer.configure({ enabled: true });
|
||||
const started = await ready;
|
||||
expect(started.tunnel).toMatchObject({
|
||||
providerId: "fake",
|
||||
state: "ready",
|
||||
url: "https://saved.tunnel.example",
|
||||
});
|
||||
expect(started.mcpUrls).toContain("https://saved.tunnel.example/mcp");
|
||||
});
|
||||
|
||||
test("a tunnel attached before its provider loads opens once the provider registers", async () => {
|
||||
const waiting = await mcpServer.configure({ enabled: true, tunnelProviderId: "fake" });
|
||||
expect(waiting.tunnel).toMatchObject({ providerId: "fake", state: "error" });
|
||||
const localUrl = waiting.listener.url!;
|
||||
expect(waiting.mcpUrls).toEqual([localUrl]);
|
||||
|
||||
const opened: string[] = [];
|
||||
const ready = nextStatus((status) => status.tunnel?.state === "ready");
|
||||
tunnels.registerProvider(fakeTunnelProvider("https://abc.tunnel.example", opened));
|
||||
const status = await ready;
|
||||
expect(opened).toEqual([`mcp-server 127.0.0.1:${waiting.listener.port}`]);
|
||||
expect(status.tunnel).toMatchObject({
|
||||
url: "https://abc.tunnel.example",
|
||||
stability: "ephemeral",
|
||||
});
|
||||
expect(status.mcpUrls).toEqual(["https://abc.tunnel.example/mcp", localUrl]);
|
||||
|
||||
const detached = await mcpServer.configure({ tunnelProviderId: null });
|
||||
expect(detached.tunnel).toBeNull();
|
||||
expect(tunnels.getExposure("mcp-server")).toBeNull();
|
||||
expect(detached.listener.state).toBe("listening");
|
||||
});
|
||||
|
||||
test("orthogonal auth settings update live without restarting the listener", async () => {
|
||||
const started = await mcpServer.configure({ enabled: true });
|
||||
expect(started.auth).toEqual({
|
||||
oauth: true,
|
||||
bearerTokens: true,
|
||||
defaultPermissions: [],
|
||||
});
|
||||
const url = started.listener.url!;
|
||||
const grantor = new Set<DaemonPermission>([
|
||||
"daemon.read",
|
||||
"workspace.read",
|
||||
"tunnel.manage",
|
||||
"access.manage",
|
||||
]);
|
||||
const { token } = await mcpServer.createToken({
|
||||
label: "App",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
expiresAt: null,
|
||||
grantor,
|
||||
});
|
||||
expect(await listTools(url, token)).toEqual(["tool_daemon_read", "tool_workspace_read"]);
|
||||
|
||||
// Turn off bearerTokens -> static token is rejected.
|
||||
await mcpServer.configure({ auth: { bearerTokens: false } }, grantor);
|
||||
await expect(listTools(url, token)).rejects.toThrow();
|
||||
|
||||
// Turn off oauth too -> unauthenticated mode admits with defaultPermissions.
|
||||
const unauth = await mcpServer.configure(
|
||||
{ auth: { oauth: false, defaultPermissions: ["daemon.read"] } },
|
||||
grantor,
|
||||
);
|
||||
expect(unauth.listener.port).toBe(started.listener.port);
|
||||
expect(unauth.auth).toEqual({
|
||||
oauth: false,
|
||||
bearerTokens: false,
|
||||
defaultPermissions: ["daemon.read"],
|
||||
});
|
||||
expect(await listTools(url)).toEqual(["tool_daemon_read"]);
|
||||
});
|
||||
|
||||
test("an owner cannot grant permissions or change auth settings their session does not hold", async () => {
|
||||
const grantor = new Set<DaemonPermission>(["daemon.read", "access.manage"]);
|
||||
await expect(
|
||||
mcpServer.createToken({
|
||||
label: "App",
|
||||
permissions: ["daemon.read", "workspace.write"],
|
||||
expiresAt: null,
|
||||
grantor,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "permission_denied" });
|
||||
expect(() => mcpServer.createApprovalCode(["workspace.manage"], grantor)).toThrow(
|
||||
McpServerError,
|
||||
);
|
||||
expect(() =>
|
||||
mcpServer.decideApproval(
|
||||
"missing",
|
||||
{ kind: "approve", permissions: ["workspace.write"] },
|
||||
grantor,
|
||||
),
|
||||
).toThrow("You cannot grant permissions you do not hold: workspace.write.");
|
||||
await expect(
|
||||
mcpServer.configure(
|
||||
{ auth: { oauth: false, bearerTokens: false, defaultPermissions: ["workspace.write"] } },
|
||||
grantor,
|
||||
),
|
||||
).rejects.toMatchObject({ code: "permission_denied" });
|
||||
await expect(mcpServer.configure({ enabled: true }, grantor)).rejects.toMatchObject({
|
||||
code: "permission_denied",
|
||||
});
|
||||
await expect(
|
||||
mcpServer.configure({ auth: { oauth: false } }, new Set<DaemonPermission>(["tunnel.manage"])),
|
||||
).rejects.toMatchObject({ code: "permission_denied" });
|
||||
|
||||
// Saved defaultPermissions that exceed grantor cannot be activated by disabling auth without
|
||||
// overriding defaultPermissions.
|
||||
await mcpServer.configure({
|
||||
auth: { oauth: true, bearerTokens: true, defaultPermissions: ["workspace.write"] },
|
||||
});
|
||||
await expect(
|
||||
mcpServer.configure({ auth: { oauth: false, bearerTokens: false } }, grantor),
|
||||
).rejects.toMatchObject({ code: "permission_denied" });
|
||||
|
||||
// A tunnel.manage operator can stop or narrow exposure on an unauthenticated listener when
|
||||
// defaults exceed their permissions, but cannot start or widen exposure.
|
||||
await mcpServer.configure({
|
||||
enabled: false,
|
||||
auth: { oauth: false, bearerTokens: false, defaultPermissions: ["workspace.write"] },
|
||||
});
|
||||
const tunnelOperator = new Set<DaemonPermission>(["tunnel.manage"]);
|
||||
await expect(mcpServer.configure({ enabled: true }, tunnelOperator)).rejects.toMatchObject({
|
||||
code: "permission_denied",
|
||||
});
|
||||
|
||||
await mcpServer.configure({
|
||||
enabled: true,
|
||||
listenHost: "0.0.0.0",
|
||||
publicUrl: "https://old.example.com",
|
||||
});
|
||||
await expect(
|
||||
mcpServer.configure({ publicUrl: "https://new.example.com" }, tunnelOperator),
|
||||
).rejects.toMatchObject({ code: "permission_denied" });
|
||||
const narrowedHost = await mcpServer.configure({ listenHost: "127.0.0.1" }, tunnelOperator);
|
||||
expect(narrowedHost.listener.host).toBe("127.0.0.1");
|
||||
await expect(
|
||||
mcpServer.configure({ listenHost: "0.0.0.0" }, tunnelOperator),
|
||||
).rejects.toMatchObject({ code: "permission_denied" });
|
||||
const narrowed = await mcpServer.configure({ publicUrl: null }, tunnelOperator);
|
||||
expect(narrowed.publicUrl).toBeNull();
|
||||
const stopped = await mcpServer.configure({ enabled: false }, tunnelOperator);
|
||||
expect(stopped.enabled).toBe(false);
|
||||
expect(mcpServer.getAccess().credentials).toEqual([]);
|
||||
});
|
||||
|
||||
test("serializes overlapping configure calls so network and auth patches do not overwrite each other", async () => {
|
||||
const [first, second] = await Promise.all([
|
||||
mcpServer.configure({ enabled: true }),
|
||||
mcpServer.configure({ auth: { oauth: false } }),
|
||||
]);
|
||||
expect(first.enabled).toBe(true);
|
||||
expect(second.enabled).toBe(true);
|
||||
expect(second.auth.oauth).toBe(false);
|
||||
expect(config).toMatchObject({ enabled: true, auth: { oauth: false } });
|
||||
});
|
||||
|
||||
test("rejects a public URL with a path", async () => {
|
||||
await expect(
|
||||
mcpServer.configure({ publicUrl: "https://mcp.example.com/paseo" }),
|
||||
).rejects.toMatchObject({ code: "invalid_config" });
|
||||
await mcpServer.configure({ publicUrl: "https://MCP.example.com/" });
|
||||
expect(config.publicUrl).toBe("https://mcp.example.com");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,617 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { isIP } from "node:net";
|
||||
import { networkInterfaces } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Logger } from "pino";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import {
|
||||
MCP_SERVER_DEFAULT_LISTEN_HOST,
|
||||
MCP_SERVER_DEFAULT_PORT,
|
||||
type DaemonPermission,
|
||||
type McpServerAccess,
|
||||
type McpServerAuthSettings,
|
||||
type McpServerConfigureAuthPatch,
|
||||
type McpServerCredential,
|
||||
type McpServerListenerStatus,
|
||||
type McpServerStatus,
|
||||
type McpServerTunnelStatus,
|
||||
type TunnelExposure,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { DaemonMcpServerAuthConfig, DaemonMcpServerConfig } from "../persisted-config.js";
|
||||
import type { TunnelManager } from "../tunnels/manager.js";
|
||||
import { Approvals, ApprovalLimitError } from "./internal/approvals.js";
|
||||
import { CredentialLimitError, CredentialStore } from "./internal/credential-store.js";
|
||||
import { createMcpServerRequestListener } from "./internal/http-server.js";
|
||||
import { OAuthServer } from "./internal/oauth.js";
|
||||
import { knownOrigins, LOOPBACK_HOSTS, WILDCARD_HOSTS } from "./internal/origins.js";
|
||||
import { loadSigningKey } from "./internal/signing-key.js";
|
||||
|
||||
const TUNNEL_EXPOSURE_ID = "mcp-server";
|
||||
|
||||
export type McpServerErrorCode =
|
||||
| "invalid_config"
|
||||
| "permission_denied"
|
||||
| "limit_reached"
|
||||
| "approval_not_found";
|
||||
|
||||
export class McpServerError extends Error {
|
||||
constructor(
|
||||
readonly code: McpServerErrorCode,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "McpServerError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface McpServerConfigPatch {
|
||||
enabled?: boolean;
|
||||
listenHost?: string;
|
||||
port?: number;
|
||||
tunnelProviderId?: string | null;
|
||||
publicUrl?: string | null;
|
||||
auth?: McpServerConfigureAuthPatch;
|
||||
}
|
||||
|
||||
export type ApprovalDecision =
|
||||
| { kind: "approve"; permissions: DaemonPermission[] }
|
||||
| { kind: "deny" };
|
||||
|
||||
export interface McpServerOptions {
|
||||
paseoHome: string;
|
||||
config: {
|
||||
read(): DaemonMcpServerConfig;
|
||||
write(config: DaemonMcpServerConfig): Promise<void>;
|
||||
};
|
||||
tunnels: Pick<TunnelManager, "expose" | "close" | "getExposure" | "subscribe">;
|
||||
/** Builds an MCP server with only the tools these permissions allow. */
|
||||
createMcpServer(permissions: readonly DaemonPermission[]): Promise<McpServer> | McpServer;
|
||||
logger: Logger;
|
||||
now?: () => Date;
|
||||
/** Port used when the config sets none. Tests pass 0 for a free port. */
|
||||
defaultPort?: number;
|
||||
}
|
||||
|
||||
type ListenerState =
|
||||
| { kind: "stopped" }
|
||||
| { kind: "listening"; server: Server; host: string; port: number }
|
||||
| { kind: "error"; host: string; port: number; error: string };
|
||||
|
||||
function describe(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function urlHost(host: string): string {
|
||||
return isIP(host) === 6 ? `[${host}]` : host;
|
||||
}
|
||||
|
||||
/** The address a local process uses to reach a listener bound to `host`. */
|
||||
function reachableHost(host: string): string {
|
||||
return WILDCARD_HOSTS.has(host) ? "127.0.0.1" : host.replace(/^\[|\]$/gu, "");
|
||||
}
|
||||
|
||||
function lanAddresses(): string[] {
|
||||
return Object.values(networkInterfaces())
|
||||
.flatMap((entries) => entries ?? [])
|
||||
.filter((entry) => !entry.internal && entry.family === "IPv4")
|
||||
.map((entry) => entry.address);
|
||||
}
|
||||
|
||||
function normalizePublicUrl(value: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value.trim());
|
||||
} catch {
|
||||
throw new McpServerError("invalid_config", "The public URL is not a valid URL.");
|
||||
}
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
||||
throw new McpServerError("invalid_config", "The public URL must start with https://.");
|
||||
}
|
||||
if (url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
||||
throw new McpServerError(
|
||||
"invalid_config",
|
||||
"The public URL must be an origin like https://mcp.example.com, without a path.",
|
||||
);
|
||||
}
|
||||
return url.origin;
|
||||
}
|
||||
|
||||
function assertSubset(
|
||||
granted: readonly DaemonPermission[],
|
||||
holder: ReadonlySet<DaemonPermission>,
|
||||
): void {
|
||||
const missing = granted.filter((permission) => !holder.has(permission));
|
||||
if (missing.length > 0) {
|
||||
throw new McpServerError(
|
||||
"permission_denied",
|
||||
`You cannot grant permissions you do not hold: ${missing.join(", ")}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveAuth(config: DaemonMcpServerConfig): McpServerAuthSettings {
|
||||
return {
|
||||
oauth: config.auth?.oauth ?? true,
|
||||
bearerTokens: config.auth?.bearerTokens ?? true,
|
||||
defaultPermissions: [...(config.auth?.defaultPermissions ?? [])],
|
||||
};
|
||||
}
|
||||
|
||||
function assertCanConfigure(
|
||||
patch: McpServerConfigPatch,
|
||||
grantor: ReadonlySet<DaemonPermission>,
|
||||
): void {
|
||||
const touchesNetwork =
|
||||
patch.enabled !== undefined ||
|
||||
patch.listenHost !== undefined ||
|
||||
patch.port !== undefined ||
|
||||
patch.tunnelProviderId !== undefined ||
|
||||
patch.publicUrl !== undefined;
|
||||
if (touchesNetwork && !grantor.has("tunnel.manage")) {
|
||||
throw new McpServerError(
|
||||
"permission_denied",
|
||||
"You do not have permission to change MCP Server network settings.",
|
||||
);
|
||||
}
|
||||
if (patch.auth === undefined) return;
|
||||
if (!grantor.has("access.manage")) {
|
||||
throw new McpServerError(
|
||||
"permission_denied",
|
||||
"You do not have permission to change MCP Server authentication settings.",
|
||||
);
|
||||
}
|
||||
if (patch.auth.defaultPermissions !== undefined) {
|
||||
assertSubset(patch.auth.defaultPermissions, grantor);
|
||||
}
|
||||
}
|
||||
|
||||
function widensListenHost(
|
||||
current: DaemonMcpServerConfig,
|
||||
next: DaemonMcpServerConfig,
|
||||
patch: McpServerConfigPatch,
|
||||
): boolean {
|
||||
if (patch.listenHost === undefined) return false;
|
||||
const prevHost = (current.listenHost ?? MCP_SERVER_DEFAULT_LISTEN_HOST).trim().toLowerCase();
|
||||
const nextHost = (next.listenHost ?? MCP_SERVER_DEFAULT_LISTEN_HOST).trim().toLowerCase();
|
||||
if (nextHost === prevHost) return false;
|
||||
return !(LOOPBACK_HOSTS.has(nextHost) && !LOOPBACK_HOSTS.has(prevHost));
|
||||
}
|
||||
|
||||
function widensExposure(
|
||||
current: DaemonMcpServerConfig,
|
||||
next: DaemonMcpServerConfig,
|
||||
patch: McpServerConfigPatch,
|
||||
defaultPort: number,
|
||||
): boolean {
|
||||
if (current.enabled !== true) return true;
|
||||
if (widensListenHost(current, next, patch)) return true;
|
||||
if (patch.port !== undefined && (next.port ?? defaultPort) !== (current.port ?? defaultPort)) {
|
||||
return true;
|
||||
}
|
||||
if (patch.tunnelProviderId && next.tunnelProviderId !== current.tunnelProviderId) return true;
|
||||
return Boolean(patch.publicUrl && next.publicUrl !== current.publicUrl);
|
||||
}
|
||||
|
||||
function exposesUnauthenticatedDefaults(
|
||||
current: DaemonMcpServerConfig,
|
||||
next: DaemonMcpServerConfig,
|
||||
patch: McpServerConfigPatch,
|
||||
defaultPort: number,
|
||||
): boolean {
|
||||
const prevAuth = resolveAuth(current);
|
||||
const nextAuth = resolveAuth(next);
|
||||
if (nextAuth.oauth || nextAuth.bearerTokens) return false;
|
||||
if (prevAuth.oauth || prevAuth.bearerTokens) return true;
|
||||
return next.enabled === true && widensExposure(current, next, patch, defaultPort);
|
||||
}
|
||||
|
||||
function mergeMcpServerConfig(
|
||||
current: DaemonMcpServerConfig,
|
||||
patch: McpServerConfigPatch,
|
||||
): DaemonMcpServerConfig {
|
||||
const next: DaemonMcpServerConfig = { ...current };
|
||||
if (patch.enabled !== undefined) next.enabled = patch.enabled;
|
||||
if (patch.listenHost !== undefined) {
|
||||
const trimmed = patch.listenHost.trim();
|
||||
if (!trimmed) {
|
||||
throw new McpServerError("invalid_config", "Listen host cannot be empty.");
|
||||
}
|
||||
next.listenHost = trimmed;
|
||||
}
|
||||
if (patch.port !== undefined) next.port = patch.port;
|
||||
if (patch.tunnelProviderId !== undefined) {
|
||||
if (patch.tunnelProviderId === null) delete next.tunnelProviderId;
|
||||
else next.tunnelProviderId = patch.tunnelProviderId;
|
||||
}
|
||||
if (patch.publicUrl !== undefined) {
|
||||
if (patch.publicUrl === null) delete next.publicUrl;
|
||||
else next.publicUrl = normalizePublicUrl(patch.publicUrl);
|
||||
}
|
||||
if (patch.auth !== undefined) {
|
||||
const nextAuth: DaemonMcpServerAuthConfig = { ...current.auth };
|
||||
if (patch.auth.oauth !== undefined) nextAuth.oauth = patch.auth.oauth;
|
||||
if (patch.auth.bearerTokens !== undefined) nextAuth.bearerTokens = patch.auth.bearerTokens;
|
||||
if (patch.auth.defaultPermissions !== undefined) {
|
||||
nextAuth.defaultPermissions = [...new Set(patch.auth.defaultPermissions)];
|
||||
}
|
||||
next.auth = nextAuth;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP Server: Paseo's top-level tools over HTTP on a dedicated listener (default 127.0.0.1:6770),
|
||||
* never the daemon's port. Supports OAuth 2.1, static Bearer tokens, or unauthenticated access
|
||||
* with explicit default permissions, plus additive addresses via tunnels or a reverse proxy URL.
|
||||
*/
|
||||
export class PaseoMcpServer {
|
||||
private readonly now: () => Date;
|
||||
private readonly credentials: CredentialStore;
|
||||
private readonly approvals: Approvals;
|
||||
private oauth: OAuthServer | null = null;
|
||||
private listener: ListenerState = { kind: "stopped" };
|
||||
private tunnel: McpServerTunnelStatus | null = null;
|
||||
private readonly statusListeners = new Set<(status: McpServerStatus) => void>();
|
||||
private readonly accessListeners = new Set<(access: McpServerAccess) => void>();
|
||||
private readonly cleanups: Array<() => void> = [];
|
||||
private applying: Promise<void> = Promise.resolve();
|
||||
private configuring: Promise<void> = Promise.resolve();
|
||||
private stopped = false;
|
||||
|
||||
constructor(private readonly options: McpServerOptions) {
|
||||
this.now = options.now ?? (() => new Date());
|
||||
const directory = path.join(options.paseoHome, "mcp-server");
|
||||
this.credentials = new CredentialStore(path.join(directory, "credentials.json"), this.now);
|
||||
this.approvals = new Approvals(this.now);
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const directory = path.join(this.options.paseoHome, "mcp-server");
|
||||
await this.credentials.load();
|
||||
this.oauth = new OAuthServer(
|
||||
await loadSigningKey(path.join(directory, "oauth-signing-key")),
|
||||
this.now,
|
||||
);
|
||||
this.cleanups.push(
|
||||
this.credentials.subscribe(() => this.emitAccess()),
|
||||
this.approvals.subscribe(() => this.emitAccess()),
|
||||
this.options.tunnels.subscribe((event) => {
|
||||
if (event.type === "providers.changed") {
|
||||
void this.apply();
|
||||
return;
|
||||
}
|
||||
if (event.exposure.id === TUNNEL_EXPOSURE_ID) this.trackExposure(event.exposure);
|
||||
}),
|
||||
);
|
||||
await this.apply();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stopped = true;
|
||||
for (const cleanup of this.cleanups.splice(0)) cleanup();
|
||||
await this.applying;
|
||||
await this.options.tunnels.close(TUNNEL_EXPOSURE_ID).catch(() => undefined);
|
||||
await this.closeListener();
|
||||
this.approvals.dispose();
|
||||
await this.credentials.flush();
|
||||
}
|
||||
|
||||
getStatus(): McpServerStatus {
|
||||
const config = this.options.config.read();
|
||||
return {
|
||||
enabled: config.enabled === true,
|
||||
listener: this.listenerStatus(),
|
||||
tunnel: this.tunnel,
|
||||
publicUrl: config.publicUrl ?? null,
|
||||
mcpUrls: this.mcpUrls(),
|
||||
auth: resolveAuth(config),
|
||||
};
|
||||
}
|
||||
|
||||
subscribeStatus(listener: (status: McpServerStatus) => void): () => void {
|
||||
this.statusListeners.add(listener);
|
||||
return () => this.statusListeners.delete(listener);
|
||||
}
|
||||
|
||||
async configure(
|
||||
patch: McpServerConfigPatch,
|
||||
grantor?: ReadonlySet<DaemonPermission>,
|
||||
): Promise<McpServerStatus> {
|
||||
const previous = this.configuring;
|
||||
let release!: () => void;
|
||||
this.configuring = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
await previous;
|
||||
try {
|
||||
const current = this.options.config.read();
|
||||
if (grantor) assertCanConfigure(patch, grantor);
|
||||
const next = mergeMcpServerConfig(current, patch);
|
||||
if (
|
||||
grantor &&
|
||||
exposesUnauthenticatedDefaults(
|
||||
current,
|
||||
next,
|
||||
patch,
|
||||
this.options.defaultPort ?? MCP_SERVER_DEFAULT_PORT,
|
||||
)
|
||||
) {
|
||||
assertSubset(resolveAuth(next).defaultPermissions, grantor);
|
||||
}
|
||||
await this.options.config.write(next);
|
||||
await this.apply();
|
||||
return this.getStatus();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
getAccess(): McpServerAccess {
|
||||
return { credentials: this.credentials.list(), approvals: this.approvals.list() };
|
||||
}
|
||||
|
||||
subscribeAccess(listener: (access: McpServerAccess) => void): () => void {
|
||||
this.accessListeners.add(listener);
|
||||
return () => this.accessListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** A static bearer token. `grantor` holds the permissions of whoever asks for it. */
|
||||
async createToken(input: {
|
||||
label: string;
|
||||
permissions: DaemonPermission[];
|
||||
expiresAt: string | null;
|
||||
grantor: ReadonlySet<DaemonPermission>;
|
||||
}): Promise<{ credential: McpServerCredential; token: string }> {
|
||||
assertSubset(input.permissions, input.grantor);
|
||||
if (input.expiresAt !== null) {
|
||||
const expiresAtMs = Date.parse(input.expiresAt);
|
||||
if (Number.isNaN(expiresAtMs) || expiresAtMs <= this.now().getTime()) {
|
||||
throw new McpServerError("invalid_config", "The expiry must be a future date.");
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await this.credentials.issue({
|
||||
label: input.label,
|
||||
authKind: "token",
|
||||
permissions: input.permissions,
|
||||
expiresAt: input.expiresAt === null ? null : new Date(input.expiresAt).toISOString(),
|
||||
redirectHost: null,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof CredentialLimitError) {
|
||||
throw new McpServerError("limit_reached", error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
revoke(credentialId: string): Promise<boolean> {
|
||||
return this.credentials.revoke(credentialId);
|
||||
}
|
||||
|
||||
decideApproval(
|
||||
approvalId: string,
|
||||
decision: ApprovalDecision,
|
||||
grantor: ReadonlySet<DaemonPermission>,
|
||||
): void {
|
||||
if (decision.kind === "approve") assertSubset(decision.permissions, grantor);
|
||||
if (!this.approvals.decide(approvalId, decision)) {
|
||||
throw new McpServerError(
|
||||
"approval_not_found",
|
||||
"This sign-in is no longer waiting. Ask the app to start again.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
createApprovalCode(
|
||||
permissions: DaemonPermission[],
|
||||
grantor: ReadonlySet<DaemonPermission>,
|
||||
): { code: string; expiresAt: string } {
|
||||
assertSubset(permissions, grantor);
|
||||
try {
|
||||
return this.approvals.createCode(permissions);
|
||||
} catch (error) {
|
||||
if (error instanceof ApprovalLimitError) {
|
||||
throw new McpServerError("limit_reached", error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Brings the listener and tunnel in line with the config. Runs one at a time. */
|
||||
private apply(): Promise<void> {
|
||||
const run = this.applying.then(() => this.reconcile());
|
||||
this.applying = run.catch((error) => {
|
||||
this.options.logger.error({ err: error }, "MCP Server reconcile failed");
|
||||
});
|
||||
return run;
|
||||
}
|
||||
|
||||
private async reconcile(): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const config = this.options.config.read();
|
||||
const host = config.listenHost ?? MCP_SERVER_DEFAULT_LISTEN_HOST;
|
||||
const port = config.port ?? this.options.defaultPort ?? MCP_SERVER_DEFAULT_PORT;
|
||||
const listening = this.listener.kind === "listening" ? this.listener : null;
|
||||
const sameAddress =
|
||||
listening?.host === host && (config.port === undefined || listening.port === port);
|
||||
if (!config.enabled || (listening && !sameAddress)) {
|
||||
await this.options.tunnels.close(TUNNEL_EXPOSURE_ID).catch(() => undefined);
|
||||
await this.closeListener();
|
||||
}
|
||||
if (config.enabled && this.listener.kind !== "listening") {
|
||||
await this.listen(host, port);
|
||||
}
|
||||
await this.reconcileTunnel(config);
|
||||
this.emitStatus();
|
||||
}
|
||||
|
||||
private async listen(host: string, port: number): Promise<void> {
|
||||
const server = createServer(
|
||||
createMcpServerRequestListener({
|
||||
oauth: this.oauth!,
|
||||
approvals: this.approvals,
|
||||
credentials: this.credentials,
|
||||
auth: () => resolveAuth(this.options.config.read()),
|
||||
origins: () => this.origins(),
|
||||
createMcpServer: async (permissions) => this.options.createMcpServer(permissions),
|
||||
logger: this.options.logger,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, host.replace(/^\[|\]$/gu, ""), () => {
|
||||
server.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
this.listener = { kind: "error", host, port, error: describe(error) };
|
||||
this.options.logger.warn({ err: error, host, port }, "MCP Server could not listen");
|
||||
return;
|
||||
}
|
||||
const address = server.address();
|
||||
const boundPort = typeof address === "object" && address ? address.port : port;
|
||||
this.listener = { kind: "listening", server, host, port: boundPort };
|
||||
this.options.logger.info({ host, port: boundPort }, "MCP Server listening");
|
||||
}
|
||||
|
||||
private async closeListener(): Promise<void> {
|
||||
const listener = this.listener;
|
||||
this.listener = { kind: "stopped" };
|
||||
if (listener.kind !== "listening") return;
|
||||
listener.server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => listener.server.close(() => resolve()));
|
||||
}
|
||||
|
||||
private async reconcileTunnel(config: DaemonMcpServerConfig): Promise<void> {
|
||||
const listening = this.listener.kind === "listening" ? this.listener : null;
|
||||
const savedProviderId = config.tunnelProviderId ?? null;
|
||||
const activeProviderId = listening && savedProviderId ? savedProviderId : undefined;
|
||||
const target = listening ? { host: reachableHost(listening.host), port: listening.port } : null;
|
||||
const current = this.options.tunnels.getExposure(TUNNEL_EXPOSURE_ID);
|
||||
if (
|
||||
current &&
|
||||
(current.providerId !== activeProviderId ||
|
||||
current.target.host !== target?.host ||
|
||||
current.target.port !== target?.port)
|
||||
) {
|
||||
await this.options.tunnels.close(TUNNEL_EXPOSURE_ID);
|
||||
}
|
||||
if (!savedProviderId) {
|
||||
this.tunnel = null;
|
||||
return;
|
||||
}
|
||||
if (!target) {
|
||||
this.tunnel = {
|
||||
providerId: savedProviderId,
|
||||
state: "closed",
|
||||
url: null,
|
||||
stability: null,
|
||||
detail: null,
|
||||
error: null,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (this.options.tunnels.getExposure(TUNNEL_EXPOSURE_ID)) return;
|
||||
try {
|
||||
const exposure = await this.options.tunnels.expose({
|
||||
id: TUNNEL_EXPOSURE_ID,
|
||||
providerId: savedProviderId,
|
||||
host: target.host,
|
||||
port: target.port,
|
||||
label: "MCP Server",
|
||||
slug: "paseo-mcp",
|
||||
waitForReady: false,
|
||||
});
|
||||
this.trackExposure(exposure);
|
||||
} catch (error) {
|
||||
// Provider plugins register late. A providers.changed event retries.
|
||||
this.tunnel = {
|
||||
providerId: savedProviderId,
|
||||
state: "error",
|
||||
url: null,
|
||||
stability: null,
|
||||
detail: null,
|
||||
error: describe(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private trackExposure(exposure: TunnelExposure): void {
|
||||
if (exposure.providerId !== this.options.config.read().tunnelProviderId) return;
|
||||
this.tunnel = {
|
||||
providerId: exposure.providerId,
|
||||
state: exposure.state,
|
||||
url: exposure.url,
|
||||
stability: exposure.stability,
|
||||
detail: exposure.detail,
|
||||
error: exposure.error,
|
||||
};
|
||||
this.emitStatus();
|
||||
}
|
||||
|
||||
private listenerStatus(): McpServerListenerStatus {
|
||||
const config = this.options.config.read();
|
||||
const listener = this.listener;
|
||||
if (listener.kind === "listening") {
|
||||
return {
|
||||
host: listener.host,
|
||||
port: listener.port,
|
||||
state: "listening",
|
||||
url: `http://${urlHost(reachableHost(listener.host))}:${listener.port}/mcp`,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
host: config.listenHost ?? MCP_SERVER_DEFAULT_LISTEN_HOST,
|
||||
port: config.port ?? this.options.defaultPort ?? MCP_SERVER_DEFAULT_PORT,
|
||||
state: listener.kind,
|
||||
url: null,
|
||||
error: listener.kind === "error" ? listener.error : null,
|
||||
};
|
||||
}
|
||||
|
||||
private tunnelUrl(): string | null {
|
||||
return this.tunnel && this.tunnel.state !== "closed" ? this.tunnel.url : null;
|
||||
}
|
||||
|
||||
private origins(): string[] {
|
||||
const listener = this.listener;
|
||||
if (listener.kind !== "listening") return [];
|
||||
return knownOrigins({
|
||||
listenHost: listener.host,
|
||||
port: listener.port,
|
||||
tunnelUrl: this.tunnelUrl(),
|
||||
publicUrl: this.options.config.read().publicUrl ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
private mcpUrls(): string[] {
|
||||
const listener = this.listener;
|
||||
if (listener.kind !== "listening") return [];
|
||||
const urls: string[] = [];
|
||||
const publicUrl = this.options.config.read().publicUrl;
|
||||
if (publicUrl) urls.push(`${publicUrl}/mcp`);
|
||||
const tunnelUrl = this.tunnelUrl();
|
||||
if (tunnelUrl) urls.push(`${new URL(tunnelUrl).origin}/mcp`);
|
||||
if (WILDCARD_HOSTS.has(listener.host)) {
|
||||
for (const address of lanAddresses()) urls.push(`http://${address}:${listener.port}/mcp`);
|
||||
}
|
||||
urls.push(`http://${urlHost(reachableHost(listener.host))}:${listener.port}/mcp`);
|
||||
return urls;
|
||||
}
|
||||
|
||||
private emitStatus(): void {
|
||||
if (this.statusListeners.size === 0) return;
|
||||
const status = this.getStatus();
|
||||
for (const listener of this.statusListeners) listener(status);
|
||||
}
|
||||
|
||||
private emitAccess(): void {
|
||||
if (this.accessListeners.size === 0) return;
|
||||
const access = this.getAccess();
|
||||
for (const listener of this.accessListeners) listener(access);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { Approvals, ApprovalLimitError } from "./approvals.js";
|
||||
import type { AuthorizationRequest } from "./oauth.js";
|
||||
|
||||
const REQUEST: AuthorizationRequest = {
|
||||
client: { clientId: "client", name: "Test App", redirectUris: ["https://app.example/cb"] },
|
||||
redirectUri: "https://app.example/cb",
|
||||
codeChallenge: "c".repeat(43),
|
||||
state: "s",
|
||||
resource: "http://127.0.0.1:6770/mcp",
|
||||
issuer: "http://127.0.0.1:6770",
|
||||
};
|
||||
|
||||
describe("Approvals", () => {
|
||||
let nowMs = Date.parse("2026-01-01T00:00:00.000Z");
|
||||
const approvals = new Approvals(() => new Date(nowMs));
|
||||
|
||||
afterEach(() => {
|
||||
approvals.dispose();
|
||||
nowMs = Date.parse("2026-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("the owner's decision reaches the browser that holds the key", () => {
|
||||
const { browserKey, approval } = approvals.open(REQUEST, "10.0.0.1");
|
||||
expect(approval).toMatchObject({ clientName: "Test App", redirectHost: "app.example" });
|
||||
expect(approval.verificationCode).toMatch(/^\d{3}-\d{3}$/);
|
||||
expect(approvals.list().map((entry) => entry.id)).toEqual([approval.id]);
|
||||
|
||||
expect(approvals.decide(approval.id, { kind: "approve", permissions: ["daemon.read"] })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(approvals.find(browserKey)?.outcome).toEqual({
|
||||
state: "approved",
|
||||
permissions: ["daemon.read"],
|
||||
});
|
||||
expect(approvals.list()).toEqual([]);
|
||||
expect(approvals.decide(approval.id, { kind: "deny" })).toBe(false);
|
||||
approvals.finish(browserKey);
|
||||
expect(approvals.find(browserKey)).toBeNull();
|
||||
});
|
||||
|
||||
test("a sign-in expires after three minutes", () => {
|
||||
const { browserKey, approval } = approvals.open(REQUEST, "10.0.0.1");
|
||||
nowMs += 3 * 60_000;
|
||||
expect(approvals.decide(approval.id, { kind: "deny" })).toBe(false);
|
||||
expect(approvals.find(browserKey)).toBeNull();
|
||||
});
|
||||
|
||||
test("approval codes are single use and forgive look-alike characters", () => {
|
||||
const { code } = approvals.createCode(["workspace.read"]);
|
||||
const first = approvals.open(REQUEST, "10.0.0.1");
|
||||
const typed = code.toLowerCase().replace("-", " ").replaceAll("1", "l").replaceAll("0", "o");
|
||||
expect(approvals.redeemCode(first.browserKey, typed)).toBe("approved");
|
||||
expect(approvals.find(first.browserKey)?.outcome).toEqual({
|
||||
state: "approved",
|
||||
permissions: ["workspace.read"],
|
||||
});
|
||||
const second = approvals.open(REQUEST, "10.0.0.1");
|
||||
expect(approvals.redeemCode(second.browserKey, code)).toBe("invalid");
|
||||
});
|
||||
|
||||
test("approval codes expire after ten minutes", () => {
|
||||
const { code } = approvals.createCode(["workspace.read"]);
|
||||
nowMs += 10 * 60_000;
|
||||
const { browserKey } = approvals.open(REQUEST, "10.0.0.1");
|
||||
expect(approvals.redeemCode(browserKey, code)).toBe("invalid");
|
||||
});
|
||||
|
||||
test("five wrong codes deny the sign-in", () => {
|
||||
const { browserKey } = approvals.open(REQUEST, "10.0.0.1");
|
||||
for (let attempt = 0; attempt < 4; attempt += 1) {
|
||||
expect(approvals.redeemCode(browserKey, "AAAAA-AAAAA")).toBe("invalid");
|
||||
}
|
||||
expect(approvals.redeemCode(browserKey, "AAAAA-AAAAA")).toBe("locked");
|
||||
expect(approvals.find(browserKey)?.outcome).toEqual({
|
||||
state: "denied",
|
||||
reason: "too_many_attempts",
|
||||
});
|
||||
});
|
||||
|
||||
test("limits waiting sign-ins per IP without blocking other IPs, and resets after window", () => {
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
approvals.open(REQUEST, "198.51.100.1");
|
||||
}
|
||||
expect(() => approvals.open(REQUEST, "198.51.100.1")).toThrow(ApprovalLimitError);
|
||||
// Another IP can still open pending approvals.
|
||||
expect(() => approvals.open(REQUEST, "198.51.100.2")).not.toThrow();
|
||||
|
||||
// Window expires after 60s.
|
||||
nowMs += 60_000;
|
||||
expect(() => approvals.open(REQUEST, "198.51.100.1")).not.toThrow();
|
||||
});
|
||||
|
||||
test("limits total waiting sign-ins and open codes, while direct code redemption bypasses the queue", () => {
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
approvals.open(REQUEST, `198.51.100.${index + 1}`);
|
||||
}
|
||||
expect(() => approvals.open(REQUEST, "198.51.100.200")).toThrow(ApprovalLimitError);
|
||||
|
||||
// One-time approval code still creates and redeems cleanly when the 20-slot queue is full.
|
||||
const { code } = approvals.createCode(["daemon.read", "workspace.read"]);
|
||||
expect(
|
||||
approvals.redeemCodeDirect("AAAAA-AAAAA", {
|
||||
requestId: "req_1",
|
||||
}),
|
||||
).toEqual({ kind: "invalid" });
|
||||
expect(
|
||||
approvals.redeemCodeDirect(code, {
|
||||
requestId: "req_1",
|
||||
}),
|
||||
).toEqual({ kind: "approved", permissions: ["daemon.read", "workspace.read"] });
|
||||
// Single-use.
|
||||
expect(
|
||||
approvals.redeemCodeDirect(code, {
|
||||
requestId: "req_2",
|
||||
}),
|
||||
).toEqual({ kind: "invalid" });
|
||||
|
||||
for (let index = 0; index < 10; index += 1) approvals.createCode(["daemon.read"]);
|
||||
expect(() => approvals.createCode(["daemon.read"])).toThrow(ApprovalLimitError);
|
||||
});
|
||||
|
||||
test("direct code redemption locks after five wrong attempts on a request without locking another request from the same IP", () => {
|
||||
const { code } = approvals.createCode(["daemon.read"]);
|
||||
for (let attempt = 0; attempt < 4; attempt += 1) {
|
||||
expect(
|
||||
approvals.redeemCodeDirect("AAAAA-AAAAA", {
|
||||
requestId: "req_lock",
|
||||
}),
|
||||
).toEqual({ kind: "invalid" });
|
||||
}
|
||||
expect(
|
||||
approvals.redeemCodeDirect("AAAAA-AAAAA", {
|
||||
requestId: "req_lock",
|
||||
}),
|
||||
).toEqual({ kind: "locked" });
|
||||
// Even the real code is rejected once this requestId is locked.
|
||||
expect(
|
||||
approvals.redeemCodeDirect(code, {
|
||||
requestId: "req_lock",
|
||||
}),
|
||||
).toEqual({ kind: "locked" });
|
||||
// Another request (e.g., the owner behind the same tunnel IP) can still redeem the code.
|
||||
expect(
|
||||
approvals.redeemCodeDirect(code, {
|
||||
requestId: "req_owner",
|
||||
}),
|
||||
).toEqual({ kind: "approved", permissions: ["daemon.read"] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,340 @@
|
||||
import { createHash, randomBytes, randomInt } from "node:crypto";
|
||||
import type { DaemonPermission, McpServerApproval } from "@getpaseo/protocol/messages";
|
||||
import type { AuthorizationRequest } from "./oauth.js";
|
||||
|
||||
const APPROVAL_TTL_MS = 3 * 60_000;
|
||||
const MAX_PENDING_APPROVALS = 20;
|
||||
const MAX_PENDING_PER_IP = 5;
|
||||
const IP_RATE_WINDOW_MS = 60_000;
|
||||
const MAX_TRACKED_IPS = 2_000;
|
||||
const APPROVAL_CODE_TTL_MS = 10 * 60_000;
|
||||
const MAX_APPROVAL_CODES = 10;
|
||||
const MAX_CODE_ATTEMPTS = 5;
|
||||
const MAX_TRACKED_DIRECT_REQUESTS = 500;
|
||||
// Crockford base32 without I, L, O and U, so a code read aloud or retyped stays unambiguous.
|
||||
const CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
||||
const CODE_LENGTH = 10;
|
||||
|
||||
export type ApprovalState =
|
||||
| { state: "pending" }
|
||||
| { state: "approved"; permissions: DaemonPermission[] }
|
||||
| { state: "denied"; reason: "owner" | "too_many_attempts" };
|
||||
|
||||
export interface BrowserApproval {
|
||||
request: AuthorizationRequest;
|
||||
approval: McpServerApproval;
|
||||
outcome: ApprovalState;
|
||||
}
|
||||
|
||||
export type CodeRedemption = "approved" | "invalid" | "locked";
|
||||
|
||||
export type DirectCodeRedemption =
|
||||
| { kind: "approved"; permissions: DaemonPermission[] }
|
||||
| { kind: "invalid" }
|
||||
| { kind: "locked" };
|
||||
|
||||
interface PendingApproval {
|
||||
approval: McpServerApproval;
|
||||
browserKey: string;
|
||||
request: AuthorizationRequest;
|
||||
outcome: ApprovalState;
|
||||
attempts: number;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
interface ApprovalCode {
|
||||
permissions: DaemonPermission[];
|
||||
expiresAtMs: number;
|
||||
}
|
||||
|
||||
interface AttemptBucket {
|
||||
count: number;
|
||||
expiresAtMs: number;
|
||||
}
|
||||
|
||||
export class ApprovalLimitError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ApprovalLimitError";
|
||||
}
|
||||
}
|
||||
|
||||
function verificationCode(): string {
|
||||
const digits = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
||||
return `${digits.slice(0, 3)}-${digits.slice(3)}`;
|
||||
}
|
||||
|
||||
function newApprovalCode(): string {
|
||||
const bytes = randomBytes(CODE_LENGTH);
|
||||
let code = "";
|
||||
for (const byte of bytes) code += CODE_ALPHABET[byte % CODE_ALPHABET.length];
|
||||
return `${code.slice(0, 5)}-${code.slice(5)}`;
|
||||
}
|
||||
|
||||
function normalizeApprovalCode(input: string): string {
|
||||
return input.toUpperCase().replace(/[\s-]/gu, "").replace(/[IL]/gu, "1").replace(/O/gu, "0");
|
||||
}
|
||||
|
||||
function hashCode(normalized: string): string {
|
||||
return createHash("sha256").update(normalized).digest("hex");
|
||||
}
|
||||
|
||||
function pruneSlidingWindow(
|
||||
map: Map<string, number[]>,
|
||||
key: string,
|
||||
nowMs: number,
|
||||
windowMs: number,
|
||||
maxTracked: number,
|
||||
): number[] {
|
||||
const cutoff = nowMs - windowMs;
|
||||
for (const [entryKey, timestamps] of map) {
|
||||
const fresh = timestamps.filter((ts) => ts > cutoff);
|
||||
if (fresh.length === 0) map.delete(entryKey);
|
||||
else if (fresh.length !== timestamps.length) map.set(entryKey, fresh);
|
||||
}
|
||||
while (map.size >= maxTracked && !map.has(key)) {
|
||||
const oldest = map.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
map.delete(oldest);
|
||||
}
|
||||
return map.get(key) ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign-ins waiting for the owner, and owner-minted approval codes. Both live only in memory and
|
||||
* expire quickly. A browser holds a secret key to its sign-in; Paseo clients see only the public ID.
|
||||
*/
|
||||
export class Approvals {
|
||||
private readonly pending = new Map<string, PendingApproval>();
|
||||
private readonly byBrowserKey = new Map<string, string>();
|
||||
private readonly codes = new Map<string, ApprovalCode>();
|
||||
private readonly ipOpenTimestamps = new Map<string, number[]>();
|
||||
private readonly directRequestAttempts = new Map<string, AttemptBucket>();
|
||||
private readonly listeners = new Set<() => void>();
|
||||
|
||||
constructor(private readonly now: () => Date) {}
|
||||
|
||||
subscribe(listener: () => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Approvals the owner can still decide. */
|
||||
list(): McpServerApproval[] {
|
||||
this.pruneExpiredPending();
|
||||
return [...this.pending.values()]
|
||||
.filter((entry) => entry.outcome.state === "pending")
|
||||
.map((entry) => structuredClone(entry.approval));
|
||||
}
|
||||
|
||||
open(
|
||||
request: AuthorizationRequest,
|
||||
clientIp = "unknown",
|
||||
): { browserKey: string; approval: McpServerApproval } {
|
||||
this.pruneExpiredPending();
|
||||
const nowMs = this.now().getTime();
|
||||
const recentForIp = pruneSlidingWindow(
|
||||
this.ipOpenTimestamps,
|
||||
clientIp,
|
||||
nowMs,
|
||||
IP_RATE_WINDOW_MS,
|
||||
MAX_TRACKED_IPS,
|
||||
);
|
||||
if (recentForIp.length >= MAX_PENDING_PER_IP) {
|
||||
throw new ApprovalLimitError(
|
||||
"Too many sign-ins from this address. Enter an approval code or try again soon.",
|
||||
);
|
||||
}
|
||||
if (this.pending.size >= MAX_PENDING_APPROVALS) {
|
||||
throw new ApprovalLimitError("Too many sign-ins are waiting. Try again in a few minutes.");
|
||||
}
|
||||
const id = randomBytes(12).toString("base64url");
|
||||
const browserKey = randomBytes(32).toString("base64url");
|
||||
const createdAt = new Date(nowMs);
|
||||
const approval: McpServerApproval = {
|
||||
id,
|
||||
clientName: request.client.name,
|
||||
redirectHost: new URL(request.redirectUri).host,
|
||||
verificationCode: verificationCode(),
|
||||
createdAt: createdAt.toISOString(),
|
||||
expiresAt: new Date(nowMs + APPROVAL_TTL_MS).toISOString(),
|
||||
};
|
||||
const timer = setTimeout(() => this.remove(id), APPROVAL_TTL_MS);
|
||||
timer.unref?.();
|
||||
this.pending.set(id, {
|
||||
approval,
|
||||
browserKey,
|
||||
request,
|
||||
outcome: { state: "pending" },
|
||||
attempts: 0,
|
||||
timer,
|
||||
});
|
||||
this.byBrowserKey.set(browserKey, id);
|
||||
this.ipOpenTimestamps.set(clientIp, [...recentForIp, nowMs]);
|
||||
this.changed();
|
||||
return { browserKey, approval: { ...approval } };
|
||||
}
|
||||
|
||||
/** The sign-in a browser key belongs to, or null once it expired or finished. */
|
||||
find(browserKey: string): BrowserApproval | null {
|
||||
const entry = this.entryForBrowser(browserKey);
|
||||
if (!entry) return null;
|
||||
return { request: entry.request, approval: { ...entry.approval }, outcome: entry.outcome };
|
||||
}
|
||||
|
||||
/** Returns false when the approval expired, finished, or was already decided. */
|
||||
decide(
|
||||
approvalId: string,
|
||||
decision: { kind: "approve"; permissions: DaemonPermission[] } | { kind: "deny" },
|
||||
): boolean {
|
||||
const entry = this.pending.get(approvalId);
|
||||
if (!entry || this.expired(entry) || entry.outcome.state !== "pending") return false;
|
||||
entry.outcome =
|
||||
decision.kind === "approve"
|
||||
? { state: "approved", permissions: [...decision.permissions] }
|
||||
: { state: "denied", reason: "owner" };
|
||||
this.changed();
|
||||
return true;
|
||||
}
|
||||
|
||||
redeemCode(browserKey: string, input: string): CodeRedemption {
|
||||
const entry = this.entryForBrowser(browserKey);
|
||||
if (!entry || entry.outcome.state !== "pending") return "locked";
|
||||
const permissions = this.consumeCode(input);
|
||||
if (permissions) {
|
||||
entry.outcome = { state: "approved", permissions };
|
||||
this.changed();
|
||||
return "approved";
|
||||
}
|
||||
entry.attempts += 1;
|
||||
if (entry.attempts >= MAX_CODE_ATTEMPTS) {
|
||||
entry.outcome = { state: "denied", reason: "too_many_attempts" };
|
||||
this.changed();
|
||||
return "locked";
|
||||
}
|
||||
return "invalid";
|
||||
}
|
||||
|
||||
/**
|
||||
* Redeems a one-time approval code directly without occupying a slot in the 20-entry pending
|
||||
* approval queue. Enforces per-request failure limits against brute-force guesses without a
|
||||
* shared IP lock so tunnel users cannot lock out the owner.
|
||||
*/
|
||||
redeemCodeDirect(input: string, context: { requestId: string }): DirectCodeRedemption {
|
||||
const nowMs = this.now().getTime();
|
||||
this.pruneDirectAttempts(nowMs);
|
||||
const requestAttempts = this.directRequestAttempts.get(context.requestId);
|
||||
if (requestAttempts !== undefined && requestAttempts.count >= MAX_CODE_ATTEMPTS) {
|
||||
return { kind: "locked" };
|
||||
}
|
||||
|
||||
const permissions = this.consumeCode(input);
|
||||
if (permissions) {
|
||||
this.directRequestAttempts.delete(context.requestId);
|
||||
return { kind: "approved", permissions };
|
||||
}
|
||||
|
||||
const nextCount = (requestAttempts?.count ?? 0) + 1;
|
||||
if (
|
||||
!this.directRequestAttempts.has(context.requestId) &&
|
||||
this.directRequestAttempts.size >= MAX_TRACKED_DIRECT_REQUESTS
|
||||
) {
|
||||
const oldest = this.directRequestAttempts.keys().next().value;
|
||||
if (oldest !== undefined) this.directRequestAttempts.delete(oldest);
|
||||
}
|
||||
this.directRequestAttempts.set(context.requestId, {
|
||||
count: nextCount,
|
||||
expiresAtMs: nowMs + APPROVAL_TTL_MS,
|
||||
});
|
||||
|
||||
if (nextCount >= MAX_CODE_ATTEMPTS) {
|
||||
return { kind: "locked" };
|
||||
}
|
||||
return { kind: "invalid" };
|
||||
}
|
||||
|
||||
createCode(permissions: readonly DaemonPermission[]): { code: string; expiresAt: string } {
|
||||
const nowMs = this.now().getTime();
|
||||
for (const [key, code] of this.codes) {
|
||||
if (code.expiresAtMs <= nowMs) this.codes.delete(key);
|
||||
}
|
||||
if (this.codes.size >= MAX_APPROVAL_CODES) {
|
||||
throw new ApprovalLimitError(
|
||||
`At most ${MAX_APPROVAL_CODES} approval codes can be open. Wait for one to expire.`,
|
||||
);
|
||||
}
|
||||
const code = newApprovalCode();
|
||||
const expiresAtMs = nowMs + APPROVAL_CODE_TTL_MS;
|
||||
this.codes.set(hashCode(normalizeApprovalCode(code)), {
|
||||
permissions: [...permissions],
|
||||
expiresAtMs,
|
||||
});
|
||||
return { code, expiresAt: new Date(expiresAtMs).toISOString() };
|
||||
}
|
||||
|
||||
/** Forgets a sign-in after its browser was sent back to the app. */
|
||||
finish(browserKey: string): void {
|
||||
const id = this.byBrowserKey.get(browserKey);
|
||||
if (id) this.remove(id);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const entry of this.pending.values()) clearTimeout(entry.timer);
|
||||
this.pending.clear();
|
||||
this.byBrowserKey.clear();
|
||||
this.codes.clear();
|
||||
this.ipOpenTimestamps.clear();
|
||||
this.directRequestAttempts.clear();
|
||||
}
|
||||
|
||||
private consumeCode(input: string): DaemonPermission[] | null {
|
||||
const normalized = normalizeApprovalCode(input);
|
||||
const key = hashCode(normalized);
|
||||
const code = this.codes.get(key);
|
||||
if (normalized.length !== CODE_LENGTH || !code || code.expiresAtMs <= this.now().getTime()) {
|
||||
return null;
|
||||
}
|
||||
this.codes.delete(key);
|
||||
return code.permissions;
|
||||
}
|
||||
|
||||
private pruneExpiredPending(): void {
|
||||
for (const entry of this.pending.values()) {
|
||||
if (this.expired(entry)) this.remove(entry.approval.id);
|
||||
}
|
||||
}
|
||||
|
||||
private pruneDirectAttempts(nowMs: number): void {
|
||||
for (const [requestId, bucket] of this.directRequestAttempts) {
|
||||
if (bucket.expiresAtMs <= nowMs) this.directRequestAttempts.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
private entryForBrowser(browserKey: string): PendingApproval | null {
|
||||
const id = this.byBrowserKey.get(browserKey);
|
||||
const entry = id ? this.pending.get(id) : undefined;
|
||||
if (!entry) return null;
|
||||
if (this.expired(entry)) {
|
||||
this.remove(entry.approval.id);
|
||||
return null;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
private expired(entry: PendingApproval): boolean {
|
||||
return Date.parse(entry.approval.expiresAt) <= this.now().getTime();
|
||||
}
|
||||
|
||||
private remove(id: string): void {
|
||||
const entry = this.pending.get(id);
|
||||
if (!entry) return;
|
||||
clearTimeout(entry.timer);
|
||||
this.pending.delete(id);
|
||||
this.byBrowserKey.delete(entry.browserKey);
|
||||
this.changed();
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
for (const listener of this.listeners) listener();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import type { McpServerAuthKind } from "@getpaseo/protocol/messages";
|
||||
import { CredentialStore } from "./credential-store.js";
|
||||
|
||||
describe("CredentialStore", () => {
|
||||
let directory: string;
|
||||
let file: string;
|
||||
let nowMs: number;
|
||||
const now = () => new Date(nowMs);
|
||||
const stores: CredentialStore[] = [];
|
||||
|
||||
function makeStore(filePath = file): CredentialStore {
|
||||
const store = new CredentialStore(filePath, now);
|
||||
stores.push(store);
|
||||
return store;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(os.tmpdir(), "paseo-credentials-"));
|
||||
file = path.join(directory, "mcp-server", "credentials.json");
|
||||
nowMs = Date.parse("2026-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(stores.splice(0).map((store) => store.flush()));
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function issue(
|
||||
store: CredentialStore,
|
||||
options: { authKind?: McpServerAuthKind; expiresAt?: string | null } = {},
|
||||
) {
|
||||
return store.issue({
|
||||
label: "App",
|
||||
authKind: options.authKind ?? "token",
|
||||
permissions: ["daemon.read", "daemon.read", "workspace.read"],
|
||||
expiresAt: options.expiresAt ?? null,
|
||||
redirectHost: options.authKind === "oauth" ? "app.example" : null,
|
||||
});
|
||||
}
|
||||
|
||||
test("every issued token authenticates, including secrets that contain underscores", async () => {
|
||||
const store = makeStore();
|
||||
for (let index = 0; index < 50; index += 1) {
|
||||
const { credential, token } = await issue(store);
|
||||
expect(store.authenticate(token)?.id).toBe(credential.id);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps only hashes in a private file and survives a reload", async () => {
|
||||
const store = makeStore();
|
||||
const { credential, token } = await issue(store);
|
||||
expect(credential.permissions).toEqual(["daemon.read", "workspace.read"]);
|
||||
await store.flush();
|
||||
// Windows exposes inherited ACLs rather than POSIX mode bits.
|
||||
if (process.platform !== "win32") {
|
||||
expect((await stat(file)).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
expect(await readFile(file, "utf8")).not.toContain(token.slice(-43));
|
||||
|
||||
const reloaded = makeStore();
|
||||
await reloaded.load();
|
||||
expect(reloaded.authenticate(token)).toMatchObject({ id: credential.id, label: "App" });
|
||||
});
|
||||
|
||||
test("rejects tampered, revoked and expired tokens", async () => {
|
||||
const store = makeStore();
|
||||
const { credential, token } = await issue(store);
|
||||
const tampered = `${token.slice(0, -1)}${token.endsWith("A") ? "B" : "A"}`;
|
||||
expect(store.authenticate(tampered)).toBeNull();
|
||||
expect(store.authenticate(`${token}x`)).toBeNull();
|
||||
expect(store.authenticate("Bearer nonsense")).toBeNull();
|
||||
|
||||
expect(await store.revoke(credential.id)).toBe(true);
|
||||
expect(store.authenticate(token)).toBeNull();
|
||||
expect(await store.revoke(credential.id)).toBe(false);
|
||||
|
||||
const expiring = await issue(store, { expiresAt: new Date(nowMs + 1_000).toISOString() });
|
||||
expect(store.authenticate(expiring.token)).not.toBeNull();
|
||||
nowMs += 1_000;
|
||||
expect(store.authenticate(expiring.token)).toBeNull();
|
||||
});
|
||||
|
||||
test("records last use", async () => {
|
||||
const store = makeStore();
|
||||
const { token } = await issue(store);
|
||||
expect(store.list()[0]!.lastUsedAt).toBeNull();
|
||||
nowMs += 5_000;
|
||||
store.authenticate(token);
|
||||
expect(store.list()[0]!.lastUsedAt).toBe(new Date(nowMs).toISOString());
|
||||
});
|
||||
|
||||
test("enforces allowed auth kinds without recording rejected use", async () => {
|
||||
const store = makeStore();
|
||||
const staticCred = await issue(store, { authKind: "token" });
|
||||
const oauthCred = await issue(store, { authKind: "oauth" });
|
||||
|
||||
nowMs += 5_000;
|
||||
expect(store.authenticate(oauthCred.token, { oauth: false, bearerTokens: true })).toBeNull();
|
||||
expect(store.authenticate(staticCred.token, { oauth: true, bearerTokens: false })).toBeNull();
|
||||
|
||||
// Rejected attempts do not stamp lastUsedAt.
|
||||
expect(store.list().find((c) => c.id === oauthCred.credential.id)?.lastUsedAt).toBeNull();
|
||||
expect(store.list().find((c) => c.id === staticCred.credential.id)?.lastUsedAt).toBeNull();
|
||||
|
||||
expect(store.authenticate(staticCred.token, { oauth: false, bearerTokens: true })?.id).toBe(
|
||||
staticCred.credential.id,
|
||||
);
|
||||
expect(store.authenticate(oauthCred.token, { oauth: true, bearerTokens: false })?.id).toBe(
|
||||
oauthCred.credential.id,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
DaemonPermissionSchema,
|
||||
type DaemonPermission,
|
||||
type McpServerAuthKind,
|
||||
type McpServerCredential,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { writePrivateFileAtomic } from "../../private-files.js";
|
||||
|
||||
const TOKEN_PREFIX = "pmcp";
|
||||
const ID_PATTERN = /^[a-f0-9]{16}$/;
|
||||
const MAX_CREDENTIALS = 200;
|
||||
// Last-used times are for display; writing them on every request would rewrite the file per call.
|
||||
const LAST_USED_WRITE_INTERVAL_MS = 60_000;
|
||||
|
||||
const StoredCredentialSchema = z.object({
|
||||
id: z.string().regex(ID_PATTERN),
|
||||
label: z.string(),
|
||||
authKind: z.enum(["oauth", "token"]),
|
||||
secretHash: z.string(),
|
||||
permissions: z.array(DaemonPermissionSchema),
|
||||
createdAt: z.string(),
|
||||
lastUsedAt: z.string().nullable(),
|
||||
expiresAt: z.string().nullable(),
|
||||
redirectHost: z.string().nullable(),
|
||||
});
|
||||
|
||||
const StoredFileSchema = z.object({
|
||||
version: z.literal(1),
|
||||
credentials: z.array(StoredCredentialSchema),
|
||||
});
|
||||
|
||||
type StoredCredential = z.infer<typeof StoredCredentialSchema>;
|
||||
|
||||
export class CredentialLimitError extends Error {
|
||||
constructor() {
|
||||
super(`MCP Server keeps at most ${MAX_CREDENTIALS} connections. Revoke one first.`);
|
||||
this.name = "CredentialLimitError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface IssueCredentialInput {
|
||||
label: string;
|
||||
authKind: McpServerAuthKind;
|
||||
permissions: readonly DaemonPermission[];
|
||||
expiresAt: string | null;
|
||||
redirectHost: string | null;
|
||||
}
|
||||
|
||||
export interface IssuedCredential {
|
||||
credential: McpServerCredential;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface AllowedCredentialKinds {
|
||||
oauth: boolean;
|
||||
bearerTokens: boolean;
|
||||
}
|
||||
|
||||
function hashSecret(secret: string): string {
|
||||
return createHash("sha256").update(secret).digest("hex");
|
||||
}
|
||||
|
||||
function toCredential({ secretHash: _secret, ...credential }: StoredCredential) {
|
||||
return structuredClone(credential) satisfies McpServerCredential;
|
||||
}
|
||||
|
||||
// The secret is base64url, which may itself contain "_", so the format is matched whole.
|
||||
const TOKEN_PATTERN = new RegExp(`^${TOKEN_PREFIX}_([a-f0-9]{16})_([A-Za-z0-9_-]{43})$`);
|
||||
|
||||
function parseToken(token: string): { id: string; secret: string } | null {
|
||||
const match = TOKEN_PATTERN.exec(token);
|
||||
return match ? { id: match[1]!, secret: match[2]! } : null;
|
||||
}
|
||||
|
||||
function isAuthKindAllowed(kind: McpServerAuthKind, allowed?: AllowedCredentialKinds): boolean {
|
||||
if (!allowed) return true;
|
||||
return kind === "oauth" ? allowed.oauth : allowed.bearerTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bearer credentials for the MCP Server, issued by OAuth or created by the owner. The file holds
|
||||
* only SHA-256 hashes of the secrets, so reading it does not reveal a usable token.
|
||||
*/
|
||||
export class CredentialStore {
|
||||
private credentials = new Map<string, StoredCredential>();
|
||||
private readonly listeners = new Set<() => void>();
|
||||
private writes: Promise<void> = Promise.resolve();
|
||||
private readonly lastUsedWrittenAt = new Map<string, number>();
|
||||
|
||||
constructor(
|
||||
private readonly filePath: string,
|
||||
private readonly now: () => Date,
|
||||
) {}
|
||||
|
||||
async load(): Promise<void> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(this.filePath, "utf8");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
||||
throw error;
|
||||
}
|
||||
const parsed = StoredFileSchema.parse(JSON.parse(raw));
|
||||
this.credentials = new Map(parsed.credentials.map((entry) => [entry.id, entry]));
|
||||
}
|
||||
|
||||
subscribe(listener: () => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
list(): McpServerCredential[] {
|
||||
return [...this.credentials.values()]
|
||||
.sort((left, right) => right.createdAt.localeCompare(left.createdAt))
|
||||
.map(toCredential);
|
||||
}
|
||||
|
||||
async issue(input: IssueCredentialInput): Promise<IssuedCredential> {
|
||||
if (this.credentials.size >= MAX_CREDENTIALS) throw new CredentialLimitError();
|
||||
const id = randomBytes(8).toString("hex");
|
||||
const secret = randomBytes(32).toString("base64url");
|
||||
const stored: StoredCredential = {
|
||||
id,
|
||||
label: input.label,
|
||||
authKind: input.authKind,
|
||||
secretHash: hashSecret(secret),
|
||||
permissions: [...new Set(input.permissions)],
|
||||
createdAt: this.now().toISOString(),
|
||||
lastUsedAt: null,
|
||||
expiresAt: input.expiresAt,
|
||||
redirectHost: input.redirectHost,
|
||||
};
|
||||
this.credentials.set(id, stored);
|
||||
await this.persist();
|
||||
return { credential: toCredential(stored), token: `${TOKEN_PREFIX}_${id}_${secret}` };
|
||||
}
|
||||
|
||||
/** The credential a bearer token proves, or null. Records the use. */
|
||||
authenticate(token: string, allowedKinds?: AllowedCredentialKinds): McpServerCredential | null {
|
||||
const parsed = parseToken(token);
|
||||
if (!parsed) return null;
|
||||
const stored = this.credentials.get(parsed.id);
|
||||
if (!stored) return null;
|
||||
const presented = Buffer.from(hashSecret(parsed.secret), "hex");
|
||||
const expected = Buffer.from(stored.secretHash, "hex");
|
||||
if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null;
|
||||
if (!isAuthKindAllowed(stored.authKind, allowedKinds)) return null;
|
||||
const now = this.now();
|
||||
if (stored.expiresAt !== null && Date.parse(stored.expiresAt) <= now.getTime()) return null;
|
||||
this.recordUse(stored, now);
|
||||
return toCredential(stored);
|
||||
}
|
||||
|
||||
async revoke(id: string): Promise<boolean> {
|
||||
if (!this.credentials.delete(id)) return false;
|
||||
this.lastUsedWrittenAt.delete(id);
|
||||
await this.persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Waits for writes already started, for orderly shutdown and tests. */
|
||||
flush(): Promise<void> {
|
||||
return this.writes;
|
||||
}
|
||||
|
||||
private recordUse(stored: StoredCredential, now: Date): void {
|
||||
stored.lastUsedAt = now.toISOString();
|
||||
const writtenAt = this.lastUsedWrittenAt.get(stored.id);
|
||||
if (writtenAt !== undefined && now.getTime() - writtenAt < LAST_USED_WRITE_INTERVAL_MS) return;
|
||||
this.lastUsedWrittenAt.set(stored.id, now.getTime());
|
||||
void this.persist().catch(() => undefined);
|
||||
}
|
||||
|
||||
private persist(): Promise<void> {
|
||||
const snapshot = JSON.stringify(
|
||||
{ version: 1, credentials: [...this.credentials.values()] },
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const write = this.writes.then(() => writePrivateFileAtomic(this.filePath, snapshot));
|
||||
this.writes = write.catch(() => undefined);
|
||||
for (const listener of this.listeners) listener();
|
||||
return write;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer, request as httpRequest, type Server } from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { Client as McpClient, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
||||
import pino from "pino";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { z } from "zod";
|
||||
import type { DaemonPermission, McpServerAuthSettings } from "@getpaseo/protocol/messages";
|
||||
import { Approvals } from "./approvals.js";
|
||||
import { CredentialStore } from "./credential-store.js";
|
||||
import { createMcpServerRequestListener } from "./http-server.js";
|
||||
import { OAuthServer } from "./oauth.js";
|
||||
import { knownOrigins } from "./origins.js";
|
||||
|
||||
function pkce() {
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
|
||||
}
|
||||
|
||||
function permissionServer(permissions: readonly DaemonPermission[]): McpServer {
|
||||
const server = new McpServer({ name: "test", version: "0.0.0" }, { capabilities: { tools: {} } });
|
||||
for (const permission of permissions) {
|
||||
server.registerTool(
|
||||
`tool_${permission.replace(".", "_")}`,
|
||||
{ description: permission, inputSchema: z.object({}) },
|
||||
async () => ({ content: [{ type: "text", text: permission }] }),
|
||||
);
|
||||
}
|
||||
return server;
|
||||
}
|
||||
|
||||
describe("MCP Server HTTP listener", () => {
|
||||
let home: string;
|
||||
let nowMs: number;
|
||||
let auth: McpServerAuthSettings;
|
||||
let tunnelUrl: string | null;
|
||||
let approvals: Approvals;
|
||||
let credentials: CredentialStore;
|
||||
let oauth: OAuthServer;
|
||||
let server: Server;
|
||||
let port: number;
|
||||
let base: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
home = await mkdtemp(path.join(os.tmpdir(), "paseo-mcp-http-"));
|
||||
nowMs = Date.parse("2026-01-01T00:00:00.000Z");
|
||||
const now = () => new Date(nowMs);
|
||||
auth = { oauth: true, bearerTokens: true, defaultPermissions: [] };
|
||||
tunnelUrl = null;
|
||||
approvals = new Approvals(now);
|
||||
credentials = new CredentialStore(path.join(home, "credentials.json"), now);
|
||||
oauth = new OAuthServer(Buffer.alloc(32, 9), now);
|
||||
const app = createMcpServerRequestListener({
|
||||
oauth,
|
||||
approvals,
|
||||
credentials,
|
||||
auth: () => auth,
|
||||
origins: () =>
|
||||
knownOrigins({
|
||||
listenHost: "127.0.0.1",
|
||||
port,
|
||||
tunnelUrl,
|
||||
publicUrl: null,
|
||||
}),
|
||||
createMcpServer: async (permissions) => permissionServer(permissions),
|
||||
logger: pino({ level: "silent" }),
|
||||
});
|
||||
server = createServer(app);
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const addr = server.address();
|
||||
if (!addr || typeof addr === "string") throw new Error("Expected TCP address");
|
||||
port = addr.port;
|
||||
base = `http://127.0.0.1:${port}`;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
approvals.dispose();
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
await rm(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function listTools(headers: Record<string, string> = {}): Promise<string[]> {
|
||||
const client = new McpClient({ name: "test", version: "0.0.0" });
|
||||
await client.connect(
|
||||
new StreamableHTTPClientTransport(new URL(`${base}/mcp`), {
|
||||
requestInit: { headers },
|
||||
}),
|
||||
);
|
||||
try {
|
||||
return (await client.listTools()).tools.map((tool) => tool.name);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function rawGet(
|
||||
pathname: string,
|
||||
headers: Record<string, string>,
|
||||
): Promise<{ status: number; body: string }> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const req = httpRequest(
|
||||
{ host: "127.0.0.1", port, path: pathname, method: "GET", headers },
|
||||
(res) => {
|
||||
let body = "";
|
||||
res.setEncoding("utf8");
|
||||
res.on("data", (chunk: string) => (body += chunk));
|
||||
res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
test("unauthenticated mode (oauth=false, bearerTokens=false) serves defaultPermissions without 421 and blocks Origin", async () => {
|
||||
auth = {
|
||||
oauth: false,
|
||||
bearerTokens: false,
|
||||
defaultPermissions: ["daemon.read", "workspace.read"],
|
||||
};
|
||||
|
||||
expect(await listTools()).toEqual(["tool_daemon_read", "tool_workspace_read"]);
|
||||
|
||||
// Browser Origin is still rejected with 403.
|
||||
const browserRes = await fetch(`${base}/mcp`, {
|
||||
method: "POST",
|
||||
headers: { Origin: "https://evil.example", "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
|
||||
});
|
||||
expect(browserRes.status).toBe(403);
|
||||
|
||||
// OAuth routes are unmounted (404), and unknown Host does NOT return 421.
|
||||
expect((await fetch(`${base}/.well-known/oauth-authorization-server`)).status).toBe(404);
|
||||
expect((await fetch(`${base}/oauth/register`, { method: "POST" })).status).toBe(404);
|
||||
const unknownHost = await rawGet("/mcp", { Host: "custom.internal:6770" });
|
||||
expect(unknownHost.status).toBe(405);
|
||||
});
|
||||
|
||||
test("bearerTokens-only mode rejects OAuth credentials, skips 421, and omits resource_metadata", async () => {
|
||||
auth = { oauth: false, bearerTokens: true, defaultPermissions: ["daemon.read"] };
|
||||
const staticToken = await credentials.issue({
|
||||
label: "Static",
|
||||
authKind: "token",
|
||||
permissions: ["workspace.write"],
|
||||
expiresAt: null,
|
||||
redirectHost: null,
|
||||
});
|
||||
const oauthToken = await credentials.issue({
|
||||
label: "OAuth",
|
||||
authKind: "oauth",
|
||||
permissions: ["workspace.write"],
|
||||
expiresAt: null,
|
||||
redirectHost: "app.example",
|
||||
});
|
||||
|
||||
const missingAuth = await fetch(`${base}/mcp`, { method: "POST" });
|
||||
expect(missingAuth.status).toBe(401);
|
||||
expect(missingAuth.headers.get("www-authenticate")).toBe("Bearer");
|
||||
|
||||
const rejectedOAuth = await fetch(`${base}/mcp`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${oauthToken.token}` },
|
||||
});
|
||||
expect(rejectedOAuth.status).toBe(401);
|
||||
expect(rejectedOAuth.headers.get("www-authenticate")).toBe('Bearer error="invalid_token"');
|
||||
|
||||
expect(await listTools({ Authorization: `Bearer ${staticToken.token}` })).toEqual([
|
||||
"tool_workspace_write",
|
||||
]);
|
||||
expect((await fetch(`${base}/.well-known/oauth-protected-resource/mcp`)).status).toBe(404);
|
||||
expect((await rawGet("/mcp", { Host: "any.proxy.example" })).status).toBe(401);
|
||||
});
|
||||
|
||||
test("oauth-only mode rejects static Bearer tokens and completes code fallback when 20-slot queue is full", async () => {
|
||||
auth = { oauth: true, bearerTokens: false, defaultPermissions: [] };
|
||||
const staticToken = await credentials.issue({
|
||||
label: "Static",
|
||||
authKind: "token",
|
||||
permissions: ["daemon.read"],
|
||||
expiresAt: null,
|
||||
redirectHost: null,
|
||||
});
|
||||
const rejectedStatic = await fetch(`${base}/mcp`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${staticToken.token}` },
|
||||
});
|
||||
expect(rejectedStatic.status).toBe(401);
|
||||
expect(rejectedStatic.headers.get("www-authenticate")).toContain("resource_metadata=");
|
||||
|
||||
// Fill all 20 slots in the pending queue from distinct IPs.
|
||||
const reg = await fetch(`${base}/oauth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ client_name: "Legit App", redirect_uris: ["https://app.example/cb"] }),
|
||||
});
|
||||
expect(reg.status).toBe(201);
|
||||
const { client_id: clientId } = (await reg.json()) as { client_id: string };
|
||||
const pair = pkce();
|
||||
const authParams = new URLSearchParams({
|
||||
response_type: "code",
|
||||
client_id: clientId,
|
||||
redirect_uri: "https://app.example/cb",
|
||||
code_challenge: pair.challenge,
|
||||
code_challenge_method: "S256",
|
||||
state: "st1",
|
||||
resource: `${base}/mcp`,
|
||||
});
|
||||
const check = oauth.checkAuthorization(authParams, {
|
||||
issuer: base,
|
||||
resource: `${base}/mcp`,
|
||||
});
|
||||
if (check.kind !== "valid") throw new Error(check.kind);
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
approvals.open(check.request, `198.51.100.${i + 1}`);
|
||||
}
|
||||
expect(approvals.list()).toHaveLength(20);
|
||||
|
||||
// Legitimate owner hits /oauth/authorize while queue is full -> bypasses to /oauth/authorize/code.
|
||||
const authorize = await fetch(`${base}/oauth/authorize?${authParams.toString()}`, {
|
||||
redirect: "manual",
|
||||
});
|
||||
expect(authorize.status).toBe(303);
|
||||
const codeFormUrl = new URL(authorize.headers.get("location")!, base);
|
||||
expect(codeFormUrl.pathname).toBe("/oauth/authorize/code");
|
||||
expect(approvals.list()).toHaveLength(20);
|
||||
|
||||
const formPage = await fetch(codeFormUrl);
|
||||
expect(formPage.status).toBe(200);
|
||||
expect(await formPage.text()).toContain("Enter an approval code");
|
||||
|
||||
const { code } = approvals.createCode(["daemon.read", "workspace.write"]);
|
||||
const submitted = await fetch(codeFormUrl, {
|
||||
method: "POST",
|
||||
redirect: "manual",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ code }),
|
||||
});
|
||||
expect(submitted.status).toBe(303);
|
||||
const callback = new URL(submitted.headers.get("location")!);
|
||||
expect(callback.origin + callback.pathname).toBe("https://app.example/cb");
|
||||
expect(callback.searchParams.get("state")).toBe("st1");
|
||||
|
||||
const tokenRes = await fetch(`${base}/oauth/token`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: callback.searchParams.get("code")!,
|
||||
redirect_uri: "https://app.example/cb",
|
||||
client_id: clientId,
|
||||
code_verifier: pair.verifier,
|
||||
resource: `${base}/mcp`,
|
||||
}),
|
||||
});
|
||||
expect(tokenRes.status).toBe(200);
|
||||
const { access_token: accessToken } = (await tokenRes.json()) as { access_token: string };
|
||||
expect(await listTools({ Authorization: `Bearer ${accessToken}` })).toEqual([
|
||||
"tool_daemon_read",
|
||||
"tool_workspace_write",
|
||||
]);
|
||||
});
|
||||
|
||||
test("resolves cloudflared and tailscale-funnel metadata origins cleanly", async () => {
|
||||
tunnelUrl = "https://demo-tunnel.trycloudflare.com";
|
||||
const cfMetadata = await rawGet("/.well-known/oauth-protected-resource/mcp", {
|
||||
Host: "demo-tunnel.trycloudflare.com",
|
||||
});
|
||||
expect(cfMetadata.status).toBe(200);
|
||||
expect(JSON.parse(cfMetadata.body)).toMatchObject({
|
||||
resource: "https://demo-tunnel.trycloudflare.com/mcp",
|
||||
authorization_servers: ["https://demo-tunnel.trycloudflare.com"],
|
||||
});
|
||||
|
||||
tunnelUrl = "https://my-box.tailnet.ts.net";
|
||||
const funnelMetadata = await rawGet("/.well-known/oauth-protected-resource/mcp", {
|
||||
Host: `127.0.0.1:${port}`,
|
||||
"X-Forwarded-Host": "my-box.tailnet.ts.net:443",
|
||||
});
|
||||
expect(funnelMetadata.status).toBe(200);
|
||||
expect(JSON.parse(funnelMetadata.body)).toMatchObject({
|
||||
resource: "https://my-box.tailnet.ts.net/mcp",
|
||||
authorization_servers: ["https://my-box.tailnet.ts.net"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,474 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import express from "express";
|
||||
import type { Logger } from "pino";
|
||||
import { createMcpHandler, type McpServer } from "@modelcontextprotocol/server";
|
||||
import { toNodeHandler } from "@modelcontextprotocol/node";
|
||||
import type { DaemonPermission, McpServerAuthSettings } from "@getpaseo/protocol/messages";
|
||||
import { ApprovalLimitError, type Approvals } from "./approvals.js";
|
||||
import { CredentialLimitError, type CredentialStore } from "./credential-store.js";
|
||||
import {
|
||||
authorizationServerMetadata,
|
||||
oauthUrlsForBase,
|
||||
protectedResourceMetadata,
|
||||
type OAuthServer,
|
||||
type OAuthUrls,
|
||||
} from "./oauth.js";
|
||||
import { resolveRequestOrigin } from "./origins.js";
|
||||
import { codePage, errorPage, sendPage, setPageSecurityHeaders, waitingPage } from "./pages.js";
|
||||
|
||||
const MCP_BODY_LIMIT = "4mb";
|
||||
const FORM_BODY_LIMIT = "16kb";
|
||||
const PENDING_PATH = "/oauth/authorize/pending";
|
||||
const DIRECT_CODE_PATH = "/oauth/authorize/code";
|
||||
|
||||
export interface McpServerHttpDependencies {
|
||||
oauth: OAuthServer;
|
||||
approvals: Approvals;
|
||||
credentials: CredentialStore;
|
||||
/** Effective auth settings, read per request so live configure takes effect immediately. */
|
||||
auth(): McpServerAuthSettings;
|
||||
/** Origins this listener answers as. See `knownOrigins`. */
|
||||
origins(): readonly string[];
|
||||
/** A fresh MCP server holding only the tools these permissions allow. */
|
||||
createMcpServer(permissions: readonly DaemonPermission[]): Promise<McpServer>;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
function header(req: IncomingMessage, name: string): string | undefined {
|
||||
const value = req.headers[name];
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
|
||||
function sendJson(res: ServerResponse, status: number, body: unknown): void {
|
||||
res.statusCode = status;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function redirect(res: ServerResponse, location: string): void {
|
||||
setPageSecurityHeaders(res);
|
||||
res.statusCode = 303;
|
||||
res.setHeader("Location", location);
|
||||
res.end();
|
||||
}
|
||||
|
||||
function bearerToken(req: IncomingMessage): string | null {
|
||||
const match = /^Bearer\s+(\S+)\s*$/iu.exec(header(req, "authorization") ?? "");
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function formParams(body: unknown): URLSearchParams {
|
||||
const params = new URLSearchParams();
|
||||
if (body && typeof body === "object") {
|
||||
for (const [name, value] of Object.entries(body as Record<string, unknown>)) {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
for (const entry of values) if (typeof entry === "string") params.append(name, entry);
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* The MCP Server listener's routes. It never serves the daemon's own API, WebSocket, or app:
|
||||
* only `/mcp` and, while OAuth is enabled, OAuth metadata and sign-in pages.
|
||||
*/
|
||||
export function createMcpServerRequestListener(deps: McpServerHttpDependencies): express.Express {
|
||||
const app = express();
|
||||
app.disable("x-powered-by");
|
||||
app.set("query parser", "simple");
|
||||
|
||||
const urlsFor = (req: IncomingMessage): OAuthUrls | null => {
|
||||
const origin = resolveRequestOrigin(deps.origins(), {
|
||||
host: header(req, "host"),
|
||||
forwardedHost: header(req, "x-forwarded-host"),
|
||||
forwardedProto: header(req, "x-forwarded-proto"),
|
||||
});
|
||||
return origin ? oauthUrlsForBase(origin) : null;
|
||||
};
|
||||
|
||||
// While OAuth is enabled, every route answers only for one of the owner's known addresses.
|
||||
app.use((req, res, next) => {
|
||||
if (!deps.auth().oauth) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const urls = urlsFor(req);
|
||||
if (!urls) {
|
||||
sendJson(res, 421, {
|
||||
error: "misdirected_request",
|
||||
error_description:
|
||||
"This address is not one Paseo knows. Set it as the public URL in Paseo's MCP Server settings.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.locals.urls = urls;
|
||||
next();
|
||||
});
|
||||
const urls = (res: express.Response): OAuthUrls => res.locals.urls as OAuthUrls;
|
||||
|
||||
const requireOAuth: express.RequestHandler = (_req, res, next) => {
|
||||
if (!deps.auth().oauth) {
|
||||
sendJson(res, 404, { error: "not_found" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
const protectedResource: express.RequestHandler = (_req, res) => {
|
||||
sendJson(res, 200, protectedResourceMetadata(urls(res)));
|
||||
};
|
||||
app.get("/.well-known/oauth-protected-resource", requireOAuth, protectedResource);
|
||||
app.get("/.well-known/oauth-protected-resource/mcp", requireOAuth, protectedResource);
|
||||
app.get("/.well-known/oauth-authorization-server", requireOAuth, (_req, res) => {
|
||||
sendJson(res, 200, authorizationServerMetadata(urls(res)));
|
||||
});
|
||||
|
||||
app.all("/mcp", express.json({ limit: MCP_BODY_LIMIT }), (req, res) => {
|
||||
void serveMcp(req, res);
|
||||
});
|
||||
|
||||
const serveMcp = async (req: express.Request, res: express.Response): Promise<void> => {
|
||||
// MCP apps call from servers. A browser page must never reach /mcp, even in unauthenticated mode.
|
||||
if (header(req, "origin") !== undefined) {
|
||||
sendJson(res, 403, {
|
||||
error: "forbidden",
|
||||
error_description: "Browser requests are refused.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const auth = deps.auth();
|
||||
let permissions: readonly DaemonPermission[];
|
||||
if (!auth.oauth && !auth.bearerTokens) {
|
||||
permissions = auth.defaultPermissions;
|
||||
} else {
|
||||
const token = bearerToken(req);
|
||||
const credential = token
|
||||
? deps.credentials.authenticate(token, {
|
||||
oauth: auth.oauth,
|
||||
bearerTokens: auth.bearerTokens,
|
||||
})
|
||||
: null;
|
||||
if (!credential) {
|
||||
let challenge = token ? 'Bearer error="invalid_token"' : "Bearer";
|
||||
if (auth.oauth) {
|
||||
const metadataUrl = `${urls(res).issuer}/.well-known/oauth-protected-resource/mcp`;
|
||||
challenge += `${token ? ", " : " "}resource_metadata="${metadataUrl}"`;
|
||||
}
|
||||
res.setHeader("WWW-Authenticate", challenge);
|
||||
sendJson(res, 401, {
|
||||
error: token ? "invalid_token" : "unauthorized",
|
||||
error_description: auth.oauth
|
||||
? "Sign in to Paseo first."
|
||||
: "Provide a valid Bearer token.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
permissions = credential.permissions;
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
res.setHeader("Allow", "POST");
|
||||
sendJson(res, 405, {
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32000, message: "Method not allowed" },
|
||||
id: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let handler: ReturnType<typeof createMcpHandler> | null = null;
|
||||
try {
|
||||
const server = await deps.createMcpServer(permissions);
|
||||
handler = createMcpHandler(() => server, {
|
||||
legacy: "stateless",
|
||||
onerror: (err: Error) => deps.logger.warn({ err }, "MCP Server transport error"),
|
||||
});
|
||||
await toNodeHandler(handler)(req, res, req.body);
|
||||
} catch (err) {
|
||||
deps.logger.error({ err }, "MCP Server request failed");
|
||||
if (!res.headersSent) {
|
||||
sendJson(res, 500, {
|
||||
jsonrpc: "2.0",
|
||||
error: { code: -32603, message: "Internal MCP server error" },
|
||||
id: null,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await handler?.close();
|
||||
}
|
||||
};
|
||||
|
||||
app.post(
|
||||
"/oauth/register",
|
||||
requireOAuth,
|
||||
express.json({ limit: FORM_BODY_LIMIT }),
|
||||
(req, res) => {
|
||||
const result = deps.oauth.register(req.body);
|
||||
if (!result.ok) {
|
||||
sendJson(res, 400, { error: result.error, error_description: result.description });
|
||||
return;
|
||||
}
|
||||
sendJson(res, 201, {
|
||||
client_id: result.client.clientId,
|
||||
client_name: result.client.name,
|
||||
redirect_uris: result.client.redirectUris,
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code"],
|
||||
response_types: ["code"],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
app.get("/oauth/authorize", requireOAuth, (req, res) => {
|
||||
const query = new URL(req.originalUrl, "http://request.invalid").searchParams;
|
||||
const check = deps.oauth.checkAuthorization(query, urls(res));
|
||||
if (check.kind === "page_error") {
|
||||
sendPage(res, 400, errorPage("Sign-in failed", check.description));
|
||||
return;
|
||||
}
|
||||
if (check.kind === "redirect_error") {
|
||||
redirect(res, check.redirectTo);
|
||||
return;
|
||||
}
|
||||
const clientIp = req.socket.remoteAddress ?? "unknown";
|
||||
try {
|
||||
const { browserKey } = deps.approvals.open(check.request, clientIp);
|
||||
redirect(res, `${PENDING_PATH}/${browserKey}`);
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApprovalLimitError)) throw error;
|
||||
// Bypass the 20-slot pending queue with a stateless signed request so one-time approval codes
|
||||
// still work even when pending slots or per-IP limits are saturated.
|
||||
const sealed = deps.oauth.sealAuthorizationRequest(check.request);
|
||||
redirect(res, `${DIRECT_CODE_PATH}?req=${encodeURIComponent(sealed)}`);
|
||||
}
|
||||
});
|
||||
|
||||
const renderDirectCodePage = (
|
||||
res: express.Response,
|
||||
sealedToken: string,
|
||||
clientName: string,
|
||||
redirectHost: string,
|
||||
status: number,
|
||||
error: string | null,
|
||||
) => {
|
||||
sendPage(
|
||||
res,
|
||||
status,
|
||||
codePage({
|
||||
clientName,
|
||||
redirectHost,
|
||||
formPath: `${DIRECT_CODE_PATH}?req=${encodeURIComponent(sealedToken)}`,
|
||||
waitingPath: null,
|
||||
error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
app.get(DIRECT_CODE_PATH, requireOAuth, (req, res) => {
|
||||
const sealedToken = typeof req.query.req === "string" ? req.query.req : "";
|
||||
const unsealed = deps.oauth.unsealAuthorizationRequest(sealedToken, urls(res).issuer);
|
||||
if (!unsealed) {
|
||||
sendPage(
|
||||
res,
|
||||
410,
|
||||
errorPage(
|
||||
"Sign-in expired",
|
||||
"This sign-in is no longer waiting. Start again from the app.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
renderDirectCodePage(
|
||||
res,
|
||||
sealedToken,
|
||||
unsealed.request.client.name,
|
||||
new URL(unsealed.request.redirectUri).host,
|
||||
200,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
app.post(
|
||||
DIRECT_CODE_PATH,
|
||||
requireOAuth,
|
||||
express.urlencoded({ extended: false, limit: FORM_BODY_LIMIT }),
|
||||
(req, res) => {
|
||||
const sealedToken = typeof req.query.req === "string" ? req.query.req : "";
|
||||
const unsealed = deps.oauth.unsealAuthorizationRequest(sealedToken, urls(res).issuer);
|
||||
if (!unsealed) {
|
||||
sendPage(
|
||||
res,
|
||||
410,
|
||||
errorPage(
|
||||
"Sign-in expired",
|
||||
"This sign-in is no longer waiting. Start again from the app.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const code = formParams(req.body).get("code") ?? "";
|
||||
const redemption = deps.approvals.redeemCodeDirect(code, {
|
||||
requestId: unsealed.id,
|
||||
});
|
||||
if (redemption.kind === "approved") {
|
||||
redirect(res, deps.oauth.approve(unsealed.request, redemption.permissions));
|
||||
return;
|
||||
}
|
||||
if (redemption.kind === "locked") {
|
||||
redirect(res, deps.oauth.deny(unsealed.request, "Too many wrong approval codes."));
|
||||
return;
|
||||
}
|
||||
renderDirectCodePage(
|
||||
res,
|
||||
sealedToken,
|
||||
unsealed.request.client.name,
|
||||
new URL(unsealed.request.redirectUri).host,
|
||||
400,
|
||||
"That code is wrong or expired.",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Sends the browser back to the app once the owner decided. Returns false while still waiting.
|
||||
const finishIfDecided = (browserKey: string, res: express.Response): boolean => {
|
||||
const entry = deps.approvals.find(browserKey);
|
||||
if (!entry) {
|
||||
sendPage(
|
||||
res,
|
||||
410,
|
||||
errorPage(
|
||||
"Sign-in expired",
|
||||
"This sign-in is no longer waiting. Start again from the app.",
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (entry.outcome.state === "pending") return false;
|
||||
deps.approvals.finish(browserKey);
|
||||
if (entry.outcome.state === "approved") {
|
||||
redirect(res, deps.oauth.approve(entry.request, entry.outcome.permissions));
|
||||
} else {
|
||||
const description =
|
||||
entry.outcome.reason === "too_many_attempts"
|
||||
? "Too many wrong approval codes."
|
||||
: "The owner denied this sign-in.";
|
||||
redirect(res, deps.oauth.deny(entry.request, description));
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
app.get(`${PENDING_PATH}/:browserKey`, requireOAuth, (req, res) => {
|
||||
const { browserKey } = req.params;
|
||||
if (finishIfDecided(browserKey, res)) return;
|
||||
const entry = deps.approvals.find(browserKey)!;
|
||||
sendPage(
|
||||
res,
|
||||
200,
|
||||
waitingPage({
|
||||
clientName: entry.approval.clientName,
|
||||
redirectHost: entry.approval.redirectHost,
|
||||
verificationCode: entry.approval.verificationCode,
|
||||
codePath: `${PENDING_PATH}/${browserKey}/code`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const renderPendingCodePage = (
|
||||
res: express.Response,
|
||||
browserKey: string,
|
||||
status: number,
|
||||
error: string | null,
|
||||
) => {
|
||||
const entry = deps.approvals.find(browserKey)!;
|
||||
sendPage(
|
||||
res,
|
||||
status,
|
||||
codePage({
|
||||
clientName: entry.approval.clientName,
|
||||
redirectHost: entry.approval.redirectHost,
|
||||
formPath: `${PENDING_PATH}/${browserKey}/code`,
|
||||
waitingPath: `${PENDING_PATH}/${browserKey}`,
|
||||
error,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
app.get(`${PENDING_PATH}/:browserKey/code`, requireOAuth, (req, res) => {
|
||||
const { browserKey } = req.params;
|
||||
if (finishIfDecided(browserKey, res)) return;
|
||||
renderPendingCodePage(res, browserKey, 200, null);
|
||||
});
|
||||
|
||||
app.post(
|
||||
`${PENDING_PATH}/:browserKey/code`,
|
||||
requireOAuth,
|
||||
express.urlencoded({ extended: false, limit: FORM_BODY_LIMIT }),
|
||||
(req, res) => {
|
||||
const { browserKey } = req.params;
|
||||
if (finishIfDecided(browserKey, res)) return;
|
||||
const code = formParams(req.body).get("code") ?? "";
|
||||
const redemption = deps.approvals.redeemCode(browserKey, code);
|
||||
if (redemption === "invalid") {
|
||||
renderPendingCodePage(res, browserKey, 400, "That code is wrong or expired.");
|
||||
return;
|
||||
}
|
||||
finishIfDecided(browserKey, res);
|
||||
},
|
||||
);
|
||||
|
||||
app.post(
|
||||
"/oauth/token",
|
||||
requireOAuth,
|
||||
express.urlencoded({ extended: false, limit: FORM_BODY_LIMIT }),
|
||||
(req, res) => {
|
||||
void exchangeToken(req, res);
|
||||
},
|
||||
);
|
||||
|
||||
const exchangeToken = async (req: express.Request, res: express.Response): Promise<void> => {
|
||||
res.setHeader("Pragma", "no-cache");
|
||||
const result = deps.oauth.exchange(formParams(req.body), urls(res));
|
||||
if (!result.ok) {
|
||||
sendJson(res, result.error === "invalid_client" ? 401 : 400, {
|
||||
error: result.error,
|
||||
error_description: result.description,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const issued = await deps.credentials.issue({
|
||||
label: result.grant.clientName,
|
||||
authKind: "oauth",
|
||||
permissions: result.grant.permissions,
|
||||
expiresAt: null,
|
||||
redirectHost: new URL(result.grant.redirectUri).host,
|
||||
});
|
||||
sendJson(res, 200, { access_token: issued.token, token_type: "Bearer" });
|
||||
} catch (error) {
|
||||
if (error instanceof CredentialLimitError) {
|
||||
sendJson(res, 400, { error: "invalid_grant", error_description: error.message });
|
||||
return;
|
||||
}
|
||||
deps.logger.error({ err: error }, "MCP Server token issue failed");
|
||||
sendJson(res, 500, { error: "server_error" });
|
||||
}
|
||||
};
|
||||
|
||||
app.use((_req, res) => {
|
||||
sendJson(res, 404, { error: "not_found" });
|
||||
});
|
||||
|
||||
const handleError: express.ErrorRequestHandler = (error, _req, res, _next) => {
|
||||
const status =
|
||||
typeof (error as { status?: unknown }).status === "number"
|
||||
? (error as { status: number }).status
|
||||
: 500;
|
||||
if (status >= 500) deps.logger.error({ err: error }, "MCP Server request failed");
|
||||
if (!res.headersSent) {
|
||||
sendJson(res, status, { error: status >= 500 ? "server_error" : "invalid_request" });
|
||||
}
|
||||
};
|
||||
app.use(handleError);
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { OAuthServer, oauthUrlsForBase, redirectMatches, type OAuthClient } from "./oauth.js";
|
||||
|
||||
const URLS = oauthUrlsForBase("http://127.0.0.1:6770");
|
||||
const REDIRECT = "https://app.example/callback";
|
||||
|
||||
function server(nowMs = Date.parse("2026-01-01T00:00:00.000Z")) {
|
||||
return new OAuthServer(Buffer.alloc(32, 7), () => new Date(nowMs));
|
||||
}
|
||||
|
||||
function register(oauth: OAuthServer, redirectUris = [REDIRECT]): OAuthClient {
|
||||
const result = oauth.register({ client_name: "App", redirect_uris: redirectUris });
|
||||
if (!result.ok) throw new Error(result.description);
|
||||
return result.client;
|
||||
}
|
||||
|
||||
function pkce() {
|
||||
const verifier = randomBytes(32).toString("base64url");
|
||||
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
|
||||
}
|
||||
|
||||
function authorizeParams(
|
||||
client: OAuthClient,
|
||||
challenge: string,
|
||||
extra: Record<string, string> = {},
|
||||
) {
|
||||
return new URLSearchParams({
|
||||
response_type: "code",
|
||||
client_id: client.clientId,
|
||||
redirect_uri: REDIRECT,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
state: "st",
|
||||
...extra,
|
||||
});
|
||||
}
|
||||
|
||||
describe("OAuthServer", () => {
|
||||
test("registration accepts only https and loopback redirects", () => {
|
||||
const oauth = server();
|
||||
expect(oauth.register({ redirect_uris: ["http://app.example/cb"] }).ok).toBe(false);
|
||||
expect(oauth.register({ redirect_uris: ["https://app.example/cb#frag"] }).ok).toBe(false);
|
||||
expect(oauth.register({ redirect_uris: ["https://user:pw@app.example/cb"] }).ok).toBe(false);
|
||||
expect(oauth.register({ redirect_uris: [] }).ok).toBe(false);
|
||||
expect(oauth.register({ redirect_uris: ["http://localhost:1234/cb"] }).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("a client ID signed by another key is unknown", () => {
|
||||
const client = register(server());
|
||||
const other = new OAuthServer(Buffer.alloc(32, 8), () => new Date());
|
||||
expect(other.checkAuthorization(authorizeParams(client, pkce().challenge), URLS).kind).toBe(
|
||||
"page_error",
|
||||
);
|
||||
});
|
||||
|
||||
test("errors before a verified redirect show a page; later ones go back to the app", () => {
|
||||
const oauth = server();
|
||||
const client = register(oauth);
|
||||
const challenge = pkce().challenge;
|
||||
expect(
|
||||
oauth.checkAuthorization(
|
||||
authorizeParams(client, challenge, { redirect_uri: "https://evil.example/cb" }),
|
||||
URLS,
|
||||
).kind,
|
||||
).toBe("page_error");
|
||||
const duplicated = authorizeParams(client, challenge);
|
||||
duplicated.append("redirect_uri", REDIRECT);
|
||||
expect(oauth.checkAuthorization(duplicated, URLS).kind).toBe("page_error");
|
||||
|
||||
const plain = oauth.checkAuthorization(
|
||||
authorizeParams(client, challenge, { code_challenge_method: "plain" }),
|
||||
URLS,
|
||||
);
|
||||
expect(plain.kind).toBe("redirect_error");
|
||||
if (plain.kind === "redirect_error") {
|
||||
const url = new URL(plain.redirectTo);
|
||||
expect(url.searchParams.get("error")).toBe("invalid_request");
|
||||
expect(url.searchParams.get("state")).toBe("st");
|
||||
expect(url.searchParams.get("iss")).toBe(URLS.issuer);
|
||||
}
|
||||
const wrongResource = oauth.checkAuthorization(
|
||||
authorizeParams(client, challenge, { resource: "https://other.example/mcp" }),
|
||||
URLS,
|
||||
);
|
||||
expect(wrongResource.kind).toBe("redirect_error");
|
||||
});
|
||||
|
||||
test("a code exchanges once, only with its verifier, client, redirect and issuer", () => {
|
||||
const oauth = server();
|
||||
const client = register(oauth);
|
||||
const { verifier, challenge } = pkce();
|
||||
const approve = () => {
|
||||
const check = oauth.checkAuthorization(authorizeParams(client, challenge), URLS);
|
||||
if (check.kind !== "valid") throw new Error(check.kind);
|
||||
return new URL(oauth.approve(check.request, ["daemon.read"])).searchParams.get("code")!;
|
||||
};
|
||||
const form = (code: string, overrides: Record<string, string> = {}) =>
|
||||
new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: REDIRECT,
|
||||
client_id: client.clientId,
|
||||
code_verifier: verifier,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const code = approve();
|
||||
expect(oauth.exchange(form(code), URLS)).toEqual({
|
||||
ok: true,
|
||||
grant: { clientName: "App", redirectUri: REDIRECT, permissions: ["daemon.read"] },
|
||||
});
|
||||
expect(oauth.exchange(form(code), URLS)).toMatchObject({ ok: false, error: "invalid_grant" });
|
||||
|
||||
const other = register(oauth, ["https://other.example/cb"]);
|
||||
for (const overrides of [
|
||||
{ code_verifier: pkce().verifier },
|
||||
{ client_id: other.clientId },
|
||||
{ redirect_uri: "https://app.example/other" },
|
||||
]) {
|
||||
const spent = approve();
|
||||
expect(oauth.exchange(form(spent, overrides), URLS)).toMatchObject({ ok: false });
|
||||
expect(oauth.exchange(form(spent), URLS)).toMatchObject({
|
||||
ok: false,
|
||||
error: "invalid_grant",
|
||||
});
|
||||
}
|
||||
const viaTunnel = approve();
|
||||
expect(
|
||||
oauth.exchange(form(viaTunnel), oauthUrlsForBase("https://tunnel.example")),
|
||||
).toMatchObject({ ok: false, error: "invalid_grant" });
|
||||
});
|
||||
|
||||
test("codes expire after a minute", () => {
|
||||
let nowMs = Date.parse("2026-01-01T00:00:00.000Z");
|
||||
const oauth = new OAuthServer(Buffer.alloc(32, 7), () => new Date(nowMs));
|
||||
const client = register(oauth);
|
||||
const { verifier, challenge } = pkce();
|
||||
const check = oauth.checkAuthorization(authorizeParams(client, challenge), URLS);
|
||||
if (check.kind !== "valid") throw new Error(check.kind);
|
||||
const code = new URL(oauth.approve(check.request, ["daemon.read"])).searchParams.get("code")!;
|
||||
nowMs += 60_000;
|
||||
const result = oauth.exchange(
|
||||
new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
redirect_uri: REDIRECT,
|
||||
client_id: client.clientId,
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
URLS,
|
||||
);
|
||||
expect(result).toMatchObject({ ok: false, error: "invalid_grant" });
|
||||
});
|
||||
|
||||
test("seals and unseals authorization requests for queue-bypass code approval", () => {
|
||||
let nowMs = Date.parse("2026-01-01T00:00:00.000Z");
|
||||
const oauth = new OAuthServer(Buffer.alloc(32, 7), () => new Date(nowMs));
|
||||
const client = register(oauth);
|
||||
const check = oauth.checkAuthorization(authorizeParams(client, pkce().challenge), URLS);
|
||||
if (check.kind !== "valid") throw new Error(check.kind);
|
||||
|
||||
const token = oauth.sealAuthorizationRequest(check.request);
|
||||
const unsealed = oauth.unsealAuthorizationRequest(token, URLS.issuer);
|
||||
expect(unsealed).not.toBeNull();
|
||||
expect(unsealed!.request).toEqual(check.request);
|
||||
|
||||
// Rejects wrong issuer, tampered token, and wrong signing key.
|
||||
expect(oauth.unsealAuthorizationRequest(token, "https://other.example")).toBeNull();
|
||||
expect(oauth.unsealAuthorizationRequest(`${token}x`, URLS.issuer)).toBeNull();
|
||||
const other = new OAuthServer(Buffer.alloc(32, 8), () => new Date(nowMs));
|
||||
expect(other.unsealAuthorizationRequest(token, URLS.issuer)).toBeNull();
|
||||
|
||||
// Expires after 3 minutes.
|
||||
nowMs += 3 * 60_000;
|
||||
expect(oauth.unsealAuthorizationRequest(token, URLS.issuer)).toBeNull();
|
||||
});
|
||||
|
||||
test("loopback redirects ignore the port; https redirects match exactly", () => {
|
||||
expect(redirectMatches("http://127.0.0.1/cb", "http://127.0.0.1:4567/cb")).toBe(true);
|
||||
expect(redirectMatches("http://127.0.0.1/cb", "http://localhost:4567/cb")).toBe(false);
|
||||
expect(redirectMatches(REDIRECT, `${REDIRECT}?x=1`)).toBe(false);
|
||||
expect(redirectMatches(REDIRECT, "https://app.example:8443/callback")).toBe(false);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user