mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 06:36:34 +00:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eba7d0ca14 | ||
|
|
35f0ff6ff1 | ||
|
|
b31565fbf7 | ||
|
|
8302319f54 | ||
|
|
8b0c22ca31 | ||
|
|
26175ed408 | ||
|
|
41e21d8d5f | ||
|
|
5700dc3ea1 | ||
|
|
aabb5764d3 | ||
|
|
4fe15a6918 | ||
|
|
32a5dd8bad | ||
|
|
70f374f269 | ||
|
|
e31ee658c2 | ||
|
|
acde63e614 | ||
|
|
25d9ed2985 |
+11
-1
@@ -72,7 +72,7 @@ browser:
|
||||
- "packages/server/src/server/agent/providers/codex-app-server-agent.ts"
|
||||
- "packages/server/src/server/agent/providers/claude/agent.ts"
|
||||
- "packages/server/src/server/agent/plugin-provider.ts"
|
||||
- "packages/server/src/server/plugins/{index,plugin-process,plugin-process-protocol,runtime}.ts"
|
||||
- "packages/server/src/server/plugins/{index,managed-source,plugin-process,plugin-process-protocol,runtime}.ts"
|
||||
- "packages/server/src/executable-resolution/**"
|
||||
- "packages/plugin/src/server/provider.ts"
|
||||
- "packages/app/src/!(desktop)/**"
|
||||
@@ -88,6 +88,16 @@ browser:
|
||||
relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
website:
|
||||
- "packages/website/**"
|
||||
- "packages/protocol/**"
|
||||
- "public-docs/**"
|
||||
- "CHANGELOG.md"
|
||||
- "CHANGELOG.zh-CN.md"
|
||||
- "README*.md"
|
||||
- "assets/brand/**"
|
||||
- "packages/app/assets/images/editor-apps/finder.png"
|
||||
|
||||
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
|
||||
# plugins and the plugin runtime included, so their changes run it too.
|
||||
cli:
|
||||
|
||||
+32
-10
@@ -43,6 +43,7 @@ jobs:
|
||||
browser: ${{ steps.filter.outputs.browser }}
|
||||
relay: ${{ steps.filter.outputs.relay }}
|
||||
cli: ${{ steps.filter.outputs.cli }}
|
||||
website: ${{ steps.filter.outputs.website }}
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
with:
|
||||
@@ -163,12 +164,11 @@ jobs:
|
||||
- name: Run plugin SDK tests
|
||||
run: npm run test --workspace=@getpaseo/plugin
|
||||
|
||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||
typecheck:
|
||||
name: typecheck
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -195,6 +195,32 @@ jobs:
|
||||
- name: Typecheck all packages
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Verify public package contents
|
||||
run: |
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
|
||||
|
||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||
website-tests:
|
||||
name: website-tests
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: node scripts/npm-retry.mjs ci
|
||||
|
||||
- name: Build protocol
|
||||
run: npm run build:protocol
|
||||
|
||||
- name: Run website tests
|
||||
run: npx vitest run packages/website/src --bail=1
|
||||
|
||||
@@ -222,7 +248,7 @@ jobs:
|
||||
cp "${archive_debs[@]}" ~/website-browser-debs/
|
||||
fi
|
||||
|
||||
- name: Verify website mockups
|
||||
- name: Run website E2E tests
|
||||
run: npm run test:e2e --workspace=@getpaseo/website
|
||||
|
||||
- name: Upload website test artifacts
|
||||
@@ -230,16 +256,12 @@ jobs:
|
||||
if: failure()
|
||||
with:
|
||||
name: website-playwright-results
|
||||
path: packages/website/test-results/
|
||||
path: |
|
||||
packages/website/test-results/
|
||||
packages/website/playwright-report/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Verify public package contents
|
||||
run: |
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/client
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/server
|
||||
|
||||
server-tests-ubuntu:
|
||||
name: server-tests (ubuntu-latest)
|
||||
needs: changes
|
||||
|
||||
@@ -51,7 +51,6 @@ 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` uses download tokens. `/_internal/mcp/agents` requires an agent capability token or an owner credential, even without a configured password.
|
||||
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 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.
|
||||
|
||||
|
||||
+17
-18
@@ -86,23 +86,22 @@ 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/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 |
|
||||
| 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 |
|
||||
|
||||
### `packages/protocol` — Wire schemas and shared protocol types
|
||||
|
||||
@@ -468,7 +467,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 `/_internal/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 `/mcp/agents`.
|
||||
|
||||
## Data flow: running an agent
|
||||
|
||||
|
||||
+1
-5
@@ -69,9 +69,6 @@ $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
|
||||
@@ -267,8 +264,7 @@ 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
|
||||
mcpServer: { enabled: boolean, listenHost: string, port: number, tunnelProviderId: string, publicUrl: string, auth: { oauth: boolean, bearerTokens: boolean, defaultPermissions: string[] } }
|
||||
auth: { password: string } // bcrypt hash, optional
|
||||
},
|
||||
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 top-level catalog and `-- --json`
|
||||
`-- --scope=top-level` for the unaffiliated `/mcp/agents` shape and `-- --json`
|
||||
for machine-readable output.
|
||||
|
||||
## Worktree starting refs
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# 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. [MCP Server](mcp-server.md) credentials follow the same rule with their own presets.
|
||||
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.
|
||||
|
||||
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 `/_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.
|
||||
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.
|
||||
|
||||
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 `/_internal/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 `/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.
|
||||
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
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.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type MockAgentWorkspace,
|
||||
} from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
|
||||
const PLUGIN_ID = "agent-chat-focus-e2e";
|
||||
@@ -135,6 +136,7 @@ async function withEmbeds(
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await gotoAppShell(page);
|
||||
await approveClientPluginsInUi(page, [PLUGIN_ID]);
|
||||
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
|
||||
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
|
||||
for (const agent of agents) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { approveClientPluginsInUi } from "../support/helpers/plugin-execution-approval";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
|
||||
const PLUGIN_ID = "agent-chat-example";
|
||||
@@ -14,6 +15,7 @@ function embed(page: Page) {
|
||||
|
||||
async function openAgentInEmbed(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await approveClientPluginsInUi(page, [PLUGIN_ID]);
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page
|
||||
.getByTestId("example-agent-list")
|
||||
|
||||
@@ -690,16 +690,20 @@ async function updateGitPlugin(page: Page, repository: string) {
|
||||
async function failUpdateFromPluginPage(page: Page, repository: string) {
|
||||
await publishGitPluginChange(repository, "Git plugin v3");
|
||||
await page.reload();
|
||||
const update = page.getByTestId("plugin-update").filter({ visible: true });
|
||||
await expect(update).toHaveText("Update");
|
||||
// Rewriting the commit the page checked leaves its update pointing at a commit the remote no
|
||||
// longer serves. The next check offers the rewritten commit.
|
||||
const update = page.getByRole("button", { name: "Update", exact: true });
|
||||
await expect(update).toBeVisible();
|
||||
// Remove the advertised commit from the fixture. A file:// remote can still serve an
|
||||
// amended-away commit by SHA while its object remains in the repository.
|
||||
execFileSync("git", ["commit", "--amend", "-m", "Git plugin v3, amended"], {
|
||||
cwd: repository,
|
||||
stdio: "ignore",
|
||||
});
|
||||
execFileSync("git", ["-c", "gc.reflogExpireUnreachable=now", "gc", "--prune=now"], {
|
||||
cwd: repository,
|
||||
stdio: "ignore",
|
||||
});
|
||||
await update.click();
|
||||
await expect(update).toHaveText("Retry");
|
||||
await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/Git command failed/)).toBeVisible();
|
||||
}
|
||||
|
||||
|
||||
@@ -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, getE2EMcpRequestInit } from "../support/helpers/daemon-port";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
@@ -305,10 +305,7 @@ 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()}/_internal/mcp/agents?callerAgentId=${callerAgentId}`,
|
||||
),
|
||||
{ requestInit: getE2EMcpRequestInit() },
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
|
||||
),
|
||||
);
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { PNG } from "pngjs";
|
||||
|
||||
// Generate resolution-chart.png in an Android test workspace with the "fixture" command.
|
||||
// Open it from Files on a 1080 x 2400 emulator, pinch out by 4x at (540, 1250),
|
||||
// then pass the zoomed screenshot from adb exec-out screencap -p to the "check" command.
|
||||
// Generate a 6,000 x 5,000 PNG with "fixture-large" to exercise Android's bitmap size
|
||||
// limit. Open it from Files at fit and pass the screenshot to the same "check" command.
|
||||
// Pass the width and height from Expo Image's onLoad event to "check-decode" on an
|
||||
// emulator with the default 100 MiB canvas limit.
|
||||
const [command, path, height] = process.argv.slice(2);
|
||||
assert.ok(
|
||||
path && ["fixture", "fixture-large", "check", "check-decode"].includes(command),
|
||||
"Use fixture <png>, fixture-large <png>, check <png>, or check-decode <width> <height>",
|
||||
);
|
||||
|
||||
if (command === "check-decode") {
|
||||
const width = Number(path);
|
||||
const decodedHeight = Number(height);
|
||||
assert.ok(width > 0 && decodedHeight > 0, "Provide the positive decoded dimensions");
|
||||
assert.ok(
|
||||
width * decodedHeight * 4 <= 100 * 1024 * 1024,
|
||||
`Decoded bitmap exceeds 100 MiB at ${width} × ${decodedHeight}`,
|
||||
);
|
||||
} else if (command === "fixture" || command === "fixture-large") {
|
||||
const size =
|
||||
command === "fixture-large" ? { width: 6000, height: 5000 } : { width: 4000, height: 3000 };
|
||||
const chart = new PNG(size);
|
||||
const stripeWidth = command === "fixture-large" ? 240 : 3;
|
||||
for (let x = 0; x < chart.width; x++) {
|
||||
const shade = Math.floor(x / stripeWidth) % 2 === 0 ? 0 : 255;
|
||||
chart.data.set([shade, shade, shade, 255], x * 4);
|
||||
}
|
||||
for (let y = 1; y < chart.height; y++) {
|
||||
chart.data.copy(chart.data, y * chart.width * 4, 0, chart.width * 4);
|
||||
}
|
||||
writeFileSync(path, PNG.sync.write(chart));
|
||||
} else {
|
||||
const screenshot = PNG.sync.read(readFileSync(path));
|
||||
assert.equal(screenshot.width, 1080, "Use a 1080 x 2400 emulator");
|
||||
assert.equal(screenshot.height, 2400, "Use a 1080 x 2400 emulator");
|
||||
|
||||
// The center of each stripe should be nearly black or white. Antialiased edges
|
||||
// may stay gray, so sample a wide span and allow for those pixels.
|
||||
const row = 1200;
|
||||
let dark = 0;
|
||||
let light = 0;
|
||||
for (let x = 340; x < 740; x++) {
|
||||
const shade = screenshot.data[(row * screenshot.width + x) * 4];
|
||||
if (shade < 35) dark++;
|
||||
if (shade > 220) light++;
|
||||
}
|
||||
|
||||
assert.ok(
|
||||
dark >= 80 && light >= 80,
|
||||
`Fine stripes lost contrast (${dark} dark, ${light} light pixels)`,
|
||||
);
|
||||
}
|
||||
@@ -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, getE2EMcpRequestInit } from "./daemon-port";
|
||||
import { getE2EDaemonPort } from "./daemon-port";
|
||||
import { assertComposerIdle } from "./rewind-flow";
|
||||
import { getServerId } from "./server-id";
|
||||
import { archiveWorkspaceFromSidebar, expectWorkspaceAbsentFromSidebar } from "./sidebar";
|
||||
@@ -80,8 +80,7 @@ async function createCodexRestoreJourney(page: Page, client: SeedDaemonClient, i
|
||||
async createWorktreeWithCodex() {
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/_internal/mcp/agents`),
|
||||
{ requestInit: getE2EMcpRequestInit() },
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents`),
|
||||
),
|
||||
);
|
||||
workspace = workspaceSchema.parse(
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { escapeRegex } from "./regex";
|
||||
|
||||
/**
|
||||
@@ -23,23 +21,6 @@ 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
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
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,7 +70,6 @@ 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, getE2EMcpRequestInit } from "./daemon-port";
|
||||
import { getE2EDaemonPort } 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,10 +386,7 @@ export async function delegateFleetThroughMcp() {
|
||||
.toBe("online");
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(
|
||||
`http://127.0.0.1:${getE2EDaemonPort()}/_internal/mcp/agents?callerAgentId=${parent.id}`,
|
||||
),
|
||||
{ requestInit: getE2EMcpRequestInit() },
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${parent.id}`),
|
||||
),
|
||||
);
|
||||
expect(await call("list_hosts")).toMatchObject({
|
||||
|
||||
@@ -948,3 +948,46 @@ it.each([false, true])(
|
||||
expect(opened.groupsByHostId.size).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("folds a completed turn whose plugin replaces every tool and reasoning row", () => {
|
||||
const present = createStreamPresentation();
|
||||
const timestamp = new Date();
|
||||
const tail: StreamItem[] = [
|
||||
{ kind: "user_message", id: "prompt", text: "Work", timestamp },
|
||||
{ kind: "thought", id: "reasoning", text: "Plan", status: "ready", timestamp },
|
||||
toolCall("one", "Bash"),
|
||||
{ kind: "assistant_message", id: "reply", text: "Done", timestamp },
|
||||
];
|
||||
const toolPlugin = installedTransform(installProbe("tool_call"));
|
||||
const reasoningPlugin = installedTransform(installProbe("reasoning"));
|
||||
const input = {
|
||||
...presentationOptions,
|
||||
tail,
|
||||
head: [],
|
||||
display: "collapseTurns" as const,
|
||||
isTurnActive: false,
|
||||
};
|
||||
const transform: TimelineItemTransform = (item) =>
|
||||
toolPlugin(item)?.flatMap((card) => [card, { ...card, id: `${card.id}/detail` }]) ??
|
||||
reasoningPlugin(item);
|
||||
const control = present({ ...input, transform: undefined });
|
||||
expect(control.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"turn_summary",
|
||||
"assistant_message",
|
||||
]);
|
||||
const closed = present({ ...input, transform });
|
||||
expect(closed.tail.map((item) => item.kind)).toEqual(control.tail.map((item) => item.kind));
|
||||
expect(closed.turns.summaryRowsByHostId.get("prompt")?.tools).toEqual(
|
||||
control.turns.summaryRowsByHostId.get("prompt")?.tools,
|
||||
);
|
||||
const opened = present({ ...input, transform, expandedTurnHostIds: new Set(["prompt"]) });
|
||||
expect(opened.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"turn_summary",
|
||||
"plugin",
|
||||
"plugin",
|
||||
"plugin",
|
||||
"assistant_message",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -45,9 +45,14 @@ function summarizeTurn(
|
||||
getGroupedCalls: CollapseTurnsInput["getGroupedCalls"],
|
||||
): OverviewSummary {
|
||||
const calls: (ToolCallItem | ThoughtItem)[] = [];
|
||||
const countedSources = new Set<string>();
|
||||
for (const item of items) {
|
||||
if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item))
|
||||
calls.push(...(getGroupedCalls(item.id) ?? [item]));
|
||||
const source = item.kind === "plugin" ? item.source : item;
|
||||
if (!source || (source.kind !== "tool_call" && source.kind !== "thought")) continue;
|
||||
if (isTurnTrigger(source) || countedSources.has(source.id)) continue;
|
||||
// One source tool call can render as several plugin cards.
|
||||
countedSources.add(source.id);
|
||||
calls.push(...(getGroupedCalls(source.id) ?? [source]));
|
||||
}
|
||||
return summarizeToolCalls(calls);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ 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";
|
||||
@@ -573,7 +572,6 @@ 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, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -768,7 +768,6 @@ export function AdaptiveModalSheet({
|
||||
desktopHeight != null && { height: desktopHeight },
|
||||
desktopMaxWidth != null && { maxWidth: desktopMaxWidth },
|
||||
isWeb && WEB_ENTER_STYLE,
|
||||
isWeb && { outlineWidth: 0 },
|
||||
],
|
||||
[desktopMaxWidth, desktopHeight],
|
||||
);
|
||||
@@ -813,24 +812,6 @@ 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;
|
||||
@@ -921,7 +902,7 @@ export function AdaptiveModalSheet({
|
||||
const desktopContent = (
|
||||
<View style={desktopOverlayStyle} testID={testID}>
|
||||
<DismissBackdrop label={t("common.actions.dismiss")} onPress={onClose} />
|
||||
<View ref={setDesktopCardRef} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
|
||||
<View ref={setOverlayScope} style={desktopCardStyle} role="dialog" aria-modal tabIndex={-1}>
|
||||
{cardInner}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -46,6 +46,7 @@ const DRAG_OVERLAY_STYLE: React.CSSProperties = {
|
||||
const TOP_RESIZER_STYLE: React.CSSProperties = {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
height: 4,
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
|
||||
@@ -10,16 +10,9 @@ 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",
|
||||
testID,
|
||||
}: StatusBadgeProps) {
|
||||
export function StatusBadge({ label, variant = "muted", leading, size = "sm" }: StatusBadgeProps) {
|
||||
const pillStyle = useMemo(
|
||||
() => [
|
||||
styles.pill,
|
||||
@@ -41,7 +34,7 @@ export function StatusBadge({
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={pillStyle} testID={testID}>
|
||||
<View style={pillStyle}>
|
||||
{leading}
|
||||
<Text style={textStyle}>{label}</Text>
|
||||
</View>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Image } from "expo-image";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { Platform, View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { ViewportFitOptions, ViewportSize } from "./geometry";
|
||||
import { measureImage } from "./image-size";
|
||||
@@ -84,7 +84,9 @@ export function ZoomableImage({
|
||||
<ViewportImage
|
||||
// No transition, so the image appears together with its toolbar.
|
||||
transition={null}
|
||||
contentFit="contain"
|
||||
// The viewport already fits the image's aspect ratio. On Android, fill selects
|
||||
// Expo Image's bitmap size cap while preserving detail below that cap for zoom.
|
||||
contentFit={Platform.OS === "android" ? "fill" : "contain"}
|
||||
onError={onError}
|
||||
onLoad={handleLoad}
|
||||
source={source}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ar: TranslationResources = {
|
||||
@@ -3836,5 +3835,4 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ar,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginGallery } from "./plugin-gallery";
|
||||
|
||||
export const en = {
|
||||
@@ -3958,7 +3957,6 @@ export const en = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.en,
|
||||
} as const;
|
||||
|
||||
type WidenStringLeaves<T> = {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const es: TranslationResources = {
|
||||
@@ -3878,5 +3877,4 @@ export const es: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.es,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const fr: TranslationResources = {
|
||||
@@ -3889,5 +3888,4 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.fr,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ja: TranslationResources = {
|
||||
@@ -3839,5 +3838,4 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ja,
|
||||
} as const;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ko: TranslationResources = {
|
||||
@@ -3823,5 +3822,4 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ko,
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ptBR: TranslationResources = {
|
||||
@@ -3858,5 +3857,4 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer["pt-BR"],
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const ru: TranslationResources = {
|
||||
@@ -3870,5 +3869,4 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer.ru,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { en, type TranslationResources } from "./en";
|
||||
import { mcpServer } from "./mcp-server";
|
||||
import { pluginSettings } from "./plugin-settings";
|
||||
|
||||
export const zhCN: TranslationResources = {
|
||||
@@ -3755,5 +3754,4 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
},
|
||||
},
|
||||
mcpServer: mcpServer["zh-CN"],
|
||||
};
|
||||
|
||||
@@ -1,367 +0,0 @@
|
||||
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 },
|
||||
}));
|
||||
@@ -1,192 +0,0 @@
|
||||
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 },
|
||||
}));
|
||||
@@ -1,167 +0,0 @@
|
||||
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] },
|
||||
}));
|
||||
@@ -1,151 +0,0 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
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 },
|
||||
}));
|
||||
@@ -1,29 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
export { McpServerApprovalPrompts } from "./approval-prompt";
|
||||
export { McpServerSettings } from "./settings-page";
|
||||
@@ -1,357 +0,0 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,227 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,282 +0,0 @@
|
||||
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>;
|
||||
@@ -1,145 +0,0 @@
|
||||
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,
|
||||
},
|
||||
}));
|
||||
@@ -1,46 +0,0 @@
|
||||
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";
|
||||
}
|
||||
@@ -1,502 +0,0 @@
|
||||
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 },
|
||||
}));
|
||||
@@ -1,81 +0,0 @@
|
||||
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 },
|
||||
}));
|
||||
@@ -1,69 +0,0 @@
|
||||
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,11 +36,8 @@ 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";
|
||||
@@ -226,7 +223,6 @@ 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 },
|
||||
];
|
||||
|
||||
@@ -253,8 +249,6 @@ 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} />;
|
||||
}
|
||||
@@ -1117,13 +1111,9 @@ 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);
|
||||
@@ -1171,7 +1161,7 @@ function SettingsSidebar({
|
||||
enableBuiltInDaemonOption={enableBuiltInDaemonOption}
|
||||
layout={layout}
|
||||
/>
|
||||
{hostItems.map((item) => (
|
||||
{HOST_SECTION_ITEMS.map((item) => (
|
||||
<SidebarHostSectionButton
|
||||
key={item.id}
|
||||
itemId={item.id}
|
||||
|
||||
@@ -475,6 +475,47 @@ describe("terminal emulator runtime in a real browser", () => {
|
||||
expect(mounted.inputs).toEqual(["legacy renderer paste"]);
|
||||
});
|
||||
|
||||
it.skipIf(!navigator.platform.includes("Linux")).each([
|
||||
{
|
||||
mode: "mouse tracking",
|
||||
sequence: "\x1b[?1000h\x1b[?1006h",
|
||||
shiftKey: false,
|
||||
reportsMouse: true,
|
||||
},
|
||||
{ mode: "shell", sequence: "", shiftKey: false, reportsMouse: false },
|
||||
{
|
||||
mode: "forced selection",
|
||||
sequence: "\x1b[?1000h\x1b[?1006h",
|
||||
shiftKey: true,
|
||||
reportsMouse: false,
|
||||
},
|
||||
])(
|
||||
"routes a middle click in $mode to one input path",
|
||||
async ({ sequence, shiftKey, reportsMouse }) => {
|
||||
const mounted = createTerminalHost({ width: 720, height: 360 });
|
||||
await new Promise<void>((resolve) =>
|
||||
mounted.runtime.write({ data: terminalOutput(sequence + "ready"), onCommitted: resolve }),
|
||||
);
|
||||
const screen = mounted.host.querySelector(".xterm-screen")!;
|
||||
const bounds = screen.getBoundingClientRect();
|
||||
const mouse = {
|
||||
button: 1,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
shiftKey,
|
||||
clientX: bounds.x + 2,
|
||||
clientY: bounds.y + 2,
|
||||
};
|
||||
|
||||
screen.dispatchEvent(new MouseEvent("mousedown", { ...mouse, buttons: 4 }));
|
||||
const release = new MouseEvent("mouseup", mouse);
|
||||
screen.dispatchEvent(release);
|
||||
|
||||
expect(mounted.inputs).toEqual(reportsMouse ? ["\x1b[<1;1;1M", "\x1b[<1;1;1m"] : []);
|
||||
expect(release.defaultPrevented).toBe(reportsMouse);
|
||||
},
|
||||
);
|
||||
|
||||
it("pastes clipboard text on Ctrl+V without reading the clipboard image", async () => {
|
||||
const mounted = createTerminalHost({ width: 720, height: 360, isMac: false });
|
||||
await waitFor({ predicate: () => mounted.sizes.length > 0 });
|
||||
|
||||
@@ -124,6 +124,7 @@ interface TerminalEmulatorRuntimeDisposables {
|
||||
clearFitTimeouts: () => void;
|
||||
removeFontListeners: () => void;
|
||||
removeFilePasteListener: () => void;
|
||||
removeMiddleClickListeners: () => void;
|
||||
removeUserInputListeners: () => void;
|
||||
restoreDocumentStyles: () => void;
|
||||
restoreViewportStyles: () => void;
|
||||
@@ -782,6 +783,26 @@ export class TerminalEmulatorRuntime {
|
||||
};
|
||||
input.host.addEventListener("paste", filePasteHandler, true);
|
||||
|
||||
// Chromium pastes the Linux primary selection on middle-button release.
|
||||
// If xterm sent the press to the PTY, the application owns that gesture.
|
||||
let middlePressReported = false;
|
||||
const recordMiddlePress = (event: MouseEvent): void => {
|
||||
if (event.button === 1) {
|
||||
middlePressReported = !event.shiftKey && terminal.modes.mouseTrackingMode !== "none";
|
||||
}
|
||||
};
|
||||
const cancelReportedMiddleRelease = (event: MouseEvent): void => {
|
||||
if (event.button === 1 && middlePressReported) {
|
||||
middlePressReported = false;
|
||||
event.preventDefault();
|
||||
}
|
||||
};
|
||||
const terminalElement = terminal.element;
|
||||
if (navigator.platform.includes("Linux")) {
|
||||
terminalElement?.addEventListener("mousedown", recordMiddlePress, true);
|
||||
terminalElement?.addEventListener("mouseup", cancelReportedMiddleRelease, true);
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
fitAndEmitResize({ shouldClaim: false });
|
||||
});
|
||||
@@ -864,6 +885,10 @@ export class TerminalEmulatorRuntime {
|
||||
removeFilePasteListener: () => {
|
||||
input.host.removeEventListener("paste", filePasteHandler, true);
|
||||
},
|
||||
removeMiddleClickListeners: () => {
|
||||
terminalElement?.removeEventListener("mousedown", recordMiddlePress, true);
|
||||
terminalElement?.removeEventListener("mouseup", cancelReportedMiddleRelease, true);
|
||||
},
|
||||
removeUserInputListeners: () => {
|
||||
for (const type of USER_INPUT_EVENT_TYPES) {
|
||||
input.host.removeEventListener(type, recordUserInputEvent, true);
|
||||
@@ -899,6 +924,7 @@ export class TerminalEmulatorRuntime {
|
||||
disposables.clearFitTimeouts();
|
||||
disposables.removeFontListeners();
|
||||
disposables.removeFilePasteListener();
|
||||
disposables.removeMiddleClickListeners();
|
||||
disposables.removeUserInputListeners();
|
||||
disposables.disposeFitAddon();
|
||||
disposables.disposeWebglAddon();
|
||||
|
||||
@@ -534,7 +534,6 @@ export const HOST_SECTION_SLUGS = [
|
||||
"terminals",
|
||||
"plugins",
|
||||
"devices",
|
||||
"mcp-server",
|
||||
"daemon",
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -16,13 +16,6 @@ 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";
|
||||
@@ -6677,139 +6670,6 @@ 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,
|
||||
|
||||
@@ -1,300 +0,0 @@
|
||||
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,23 +1064,20 @@ async function verifyRoutedHostBrowsing({ page, targetServer, targetUrl }) {
|
||||
};
|
||||
}
|
||||
|
||||
async function createMcpClient({ daemonPort, password, paseoHome, callerAgentId }) {
|
||||
const url = new URL(`http://127.0.0.1:${daemonPort}/_internal/mcp/agents`);
|
||||
async function createMcpClient({ daemonPort, password, callerAgentId }) {
|
||||
const url = new URL(`http://127.0.0.1:${daemonPort}/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,
|
||||
token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined,
|
||||
password ? { requestInit: { headers: { Authorization: `Bearer ${password}` } } } : undefined,
|
||||
);
|
||||
return await experimental_createMCPClient({ transport });
|
||||
}
|
||||
|
||||
async function createMcpCallerAgent({ daemonPort, password, paseoHome, workspaceId }) {
|
||||
const client = await createMcpClient({ daemonPort, password, paseoHome });
|
||||
async function createMcpCallerAgent({ daemonPort, password, workspaceId }) {
|
||||
const client = await createMcpClient({ daemonPort, password });
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "create_agent",
|
||||
@@ -1119,7 +1116,6 @@ async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
localDaemonPort,
|
||||
localDaemonPassword,
|
||||
remoteDaemonPort,
|
||||
remoteHome,
|
||||
sharedWorkspaceId,
|
||||
targetUrl,
|
||||
runtimeDir,
|
||||
@@ -1134,7 +1130,6 @@ async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
});
|
||||
const remoteAgentId = await createMcpCallerAgent({
|
||||
daemonPort: remoteDaemonPort,
|
||||
paseoHome: remoteHome,
|
||||
workspaceId: sharedWorkspaceId,
|
||||
});
|
||||
|
||||
@@ -1145,7 +1140,6 @@ async function verifyCrossHostAutomationAndUploadBoundary({
|
||||
});
|
||||
const remoteClient = await createMcpClient({
|
||||
daemonPort: remoteDaemonPort,
|
||||
paseoHome: remoteHome,
|
||||
callerAgentId: remoteAgentId,
|
||||
});
|
||||
|
||||
@@ -1768,7 +1762,6 @@ async function main() {
|
||||
localDaemonPort,
|
||||
localDaemonPassword,
|
||||
remoteDaemonPort,
|
||||
remoteHome,
|
||||
sharedWorkspaceId,
|
||||
targetUrl,
|
||||
runtimeDir,
|
||||
|
||||
@@ -410,17 +410,11 @@ async function callBrowserTool(client, name, args = {}) {
|
||||
return mcpPayload(await client.callTool({ name, args }), name);
|
||||
}
|
||||
|
||||
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) {
|
||||
async function connectBrowserToolClient(daemonPort, callerAgentId) {
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
new URL(
|
||||
`http://127.0.0.1:${daemonPort}/_internal/mcp/agents?callerAgentId=${encodeURIComponent(callerAgentId)}`,
|
||||
`http://127.0.0.1:${daemonPort}/mcp/agents?callerAgentId=${encodeURIComponent(callerAgentId)}`,
|
||||
),
|
||||
{ requestInit: readLocalCredentialHeaders(paseoHome) },
|
||||
);
|
||||
return experimental_createMCPClient({ transport });
|
||||
}
|
||||
@@ -667,10 +661,9 @@ async function verifyLocalUploadContainment({ client, targetUrl, workspaceDir, r
|
||||
}
|
||||
}
|
||||
|
||||
async function createCallerAgent(daemonPort, paseoHome, workspaceId = workspaceIds[0]) {
|
||||
async function createCallerAgent(daemonPort, workspaceId = workspaceIds[0]) {
|
||||
const transport = new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${daemonPort}/_internal/mcp/agents`),
|
||||
{ requestInit: readLocalCredentialHeaders(paseoHome) },
|
||||
new URL(`http://127.0.0.1:${daemonPort}/mcp/agents`),
|
||||
);
|
||||
const client = await experimental_createMCPClient({ transport });
|
||||
try {
|
||||
@@ -1658,8 +1651,8 @@ async function main() {
|
||||
}
|
||||
const { page, status } = await launchDesktop({ approveSeededPlugin: true });
|
||||
async function checkProfiles() {
|
||||
const caller = await createCallerAgent(daemonPort, paseoHome);
|
||||
const profileClient = await connectBrowserToolClient(daemonPort, paseoHome, caller);
|
||||
const caller = await createCallerAgent(daemonPort);
|
||||
const profileClient = await connectBrowserToolClient(daemonPort, caller);
|
||||
const inspect = (expression) => evaluateDesktopWindow(inspectorPort, expression);
|
||||
try {
|
||||
return await runProfileJourney({
|
||||
@@ -1734,20 +1727,20 @@ async function main() {
|
||||
browserWorkspaceId: workspaceIds[0],
|
||||
});
|
||||
if (process.env.PASEO_DESKTOP_BROWSER_PERMISSIONS_ONLY === "1") {
|
||||
const callerAgentId = await createCallerAgent(daemonPort, paseoHome);
|
||||
client = await connectBrowserToolClient(daemonPort, paseoHome, callerAgentId);
|
||||
const callerAgentId = await createCallerAgent(daemonPort);
|
||||
client = await connectBrowserToolClient(daemonPort, 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, paseoHome);
|
||||
const callerAgentId = await createCallerAgent(daemonPort);
|
||||
const typingAgent = {
|
||||
workspaceId: workspaceIds.at(-1),
|
||||
agentId: await createCallerAgent(daemonPort, paseoHome, workspaceIds.at(-1)),
|
||||
agentId: await createCallerAgent(daemonPort, workspaceIds.at(-1)),
|
||||
};
|
||||
client = await connectBrowserToolClient(daemonPort, paseoHome, callerAgentId);
|
||||
client = await connectBrowserToolClient(daemonPort, callerAgentId);
|
||||
const focusIsolation = await checkFocusIsolation(client, callerAgentId, typingAgent);
|
||||
writeJson(path.join(artifactDir, "result.json"), { focusIsolation });
|
||||
console.log("Desktop browser focus isolation regression passed.");
|
||||
@@ -1779,12 +1772,12 @@ async function main() {
|
||||
const adaptiveTheme = await runAdaptiveThemeRegression(artifactDir);
|
||||
await runAppearanceFontSizeRegression(page);
|
||||
|
||||
const callerAgentId = await createCallerAgent(daemonPort, paseoHome);
|
||||
const callerAgentId = await createCallerAgent(daemonPort);
|
||||
const typingAgent = {
|
||||
workspaceId: workspaceIds.at(-1),
|
||||
agentId: await createCallerAgent(daemonPort, paseoHome, workspaceIds.at(-1)),
|
||||
agentId: await createCallerAgent(daemonPort, workspaceIds.at(-1)),
|
||||
};
|
||||
client = await connectBrowserToolClient(daemonPort, paseoHome, callerAgentId);
|
||||
client = await connectBrowserToolClient(daemonPort, callerAgentId);
|
||||
const report = await runRegression({
|
||||
page,
|
||||
client,
|
||||
@@ -1804,11 +1797,7 @@ async function main() {
|
||||
const focusIsolation = await checkFocusIsolation(client, callerAgentId, typingAgent);
|
||||
const permissions = await checkPermissions(client);
|
||||
const pluginLinks = await checkPluginLinks();
|
||||
const routingClient = await connectBrowserToolClient(
|
||||
daemonPort,
|
||||
paseoHome,
|
||||
typingAgent.agentId,
|
||||
);
|
||||
const routingClient = await connectBrowserToolClient(daemonPort, typingAgent.agentId);
|
||||
try {
|
||||
await verifyBrowserHostRouting({
|
||||
page,
|
||||
|
||||
@@ -1215,6 +1215,27 @@ async function stopCliDaemon({ appPath, env }) {
|
||||
});
|
||||
}
|
||||
|
||||
async function expectPageDownKeepsWorkspaceAligned(page) {
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
const newTab = page.getByRole("button", { name: "New tab", exact: true });
|
||||
await composer.fill("Keep the workspace in place");
|
||||
await composer.press("ArrowLeft");
|
||||
const before = await newTab.boundingBox();
|
||||
assert.ok(before, "Workspace tab controls are visible before Page Down");
|
||||
|
||||
await composer.press("PageDown");
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
}),
|
||||
);
|
||||
|
||||
const after = await newTab.boundingBox();
|
||||
assert.ok(after, "Workspace tab controls are visible after Page Down");
|
||||
assert.equal(after.x, before.x, "Page Down in the chat draft keeps the workspace aligned");
|
||||
}
|
||||
|
||||
async function openSmokeWorkspace({ appPath, env, page, daemonHome }) {
|
||||
const projectPath = path.join(daemonHome, "sandbox-smoke-project");
|
||||
fs.mkdirSync(projectPath);
|
||||
@@ -1242,7 +1263,7 @@ async function openSmokeWorkspace({ appPath, env, page, daemonHome }) {
|
||||
await page.getByRole("button", { name: "Sandbox smoke workspace", exact: true }).click();
|
||||
await page.waitForURL((url) => url.pathname.endsWith(`/workspace/${workspace.workspaceId}`));
|
||||
await page.getByRole("button", { name: "Agent", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Message agent..." }).click();
|
||||
await expectPageDownKeepsWorkspaceAligned(page);
|
||||
console.log(`Packaged desktop smoke: renderer opened workspace ${workspace.workspaceId}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -239,7 +239,7 @@ describe("desktop-settings", () => {
|
||||
expect(persisted.settings.daemon.manageBuiltInDaemon).toBe(false);
|
||||
});
|
||||
|
||||
it("does not rewrite existing settings while reading them", async () => {
|
||||
it("does not rewrite migrated settings while reading them", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
const raw = JSON.stringify({
|
||||
@@ -253,6 +253,7 @@ describe("desktop-settings", () => {
|
||||
},
|
||||
migrations: {
|
||||
legacyRendererSettingsImported: false,
|
||||
daemonStopOnQuitDefaultApplied: true,
|
||||
},
|
||||
});
|
||||
await writeFile(settingsFilePath(userDataPath), raw);
|
||||
@@ -265,7 +266,7 @@ describe("desktop-settings", () => {
|
||||
expect(persisted).toBe(raw);
|
||||
});
|
||||
|
||||
it("resets the pre-existing keep-running default so the daemon stops with the app", async () => {
|
||||
it("persists the stop-on-quit migration on the first read", async () => {
|
||||
const userDataPath = await createTempUserDataDir();
|
||||
directories.add(userDataPath);
|
||||
await writeFile(
|
||||
@@ -276,7 +277,7 @@ describe("desktop-settings", () => {
|
||||
releaseChannel: "stable",
|
||||
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
|
||||
},
|
||||
migrations: { legacyRendererSettingsImported: true },
|
||||
futureSetting: { value: 7 },
|
||||
}),
|
||||
);
|
||||
const store = createDesktopSettingsStore({ userDataPath });
|
||||
@@ -284,6 +285,12 @@ describe("desktop-settings", () => {
|
||||
const settings = await store.get();
|
||||
|
||||
expect(settings.daemon.keepRunningAfterQuit).toBe(false);
|
||||
const persisted = JSON.parse(await readFile(settingsFilePath(userDataPath), "utf8"));
|
||||
expect(persisted).toMatchObject({
|
||||
settings: { daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: false } },
|
||||
migrations: { daemonStopOnQuitDefaultApplied: true },
|
||||
futureSetting: { value: 7 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an explicit keep-running choice across restarts", async () => {
|
||||
|
||||
@@ -238,12 +238,9 @@ function hasLegacyRendererOwnedPatch(patch: DesktopSettingsPatch): boolean {
|
||||
return patch.releaseChannel !== undefined || patch.daemon?.manageBuiltInDaemon !== undefined;
|
||||
}
|
||||
|
||||
function coerceDocument(input: unknown): PersistedDesktopSettingsDocument {
|
||||
const document = PersistedDocumentSchema.parse(input);
|
||||
if (document.migrations.daemonStopOnQuitDefaultApplied) {
|
||||
return document;
|
||||
}
|
||||
|
||||
function applyDaemonStopOnQuitDefault(
|
||||
document: PersistedDesktopSettingsDocument,
|
||||
): PersistedDesktopSettingsDocument {
|
||||
return {
|
||||
...document,
|
||||
settings: {
|
||||
@@ -283,45 +280,39 @@ export function createDesktopSettingsStore({
|
||||
cachedDocument = document;
|
||||
}
|
||||
|
||||
async function loadDocumentUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
async function loadDocumentUnlocked({
|
||||
recoverUnreadable = false,
|
||||
} = {}): Promise<PersistedDesktopSettingsDocument> {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
|
||||
let raw: string;
|
||||
let document: PersistedDesktopSettingsDocument;
|
||||
try {
|
||||
raw = await readFile(filePath, "utf8");
|
||||
const raw = await readFile(filePath, "utf8");
|
||||
document = PersistedDocumentSchema.parse(JSON.parse(raw));
|
||||
} catch (error) {
|
||||
if (!isNodeError(error) || error.code !== "ENOENT") {
|
||||
if (!recoverUnreadable && (!isNodeError(error) || error.code !== "ENOENT")) {
|
||||
throw error;
|
||||
}
|
||||
const document = buildDefaultDocument();
|
||||
await writeDocument(document);
|
||||
return document;
|
||||
const defaults = buildDefaultDocument();
|
||||
await writeDocument(defaults);
|
||||
return defaults;
|
||||
}
|
||||
const document = coerceDocument(JSON.parse(raw));
|
||||
|
||||
if (!document.migrations.daemonStopOnQuitDefaultApplied) {
|
||||
const migrated = applyDaemonStopOnQuitDefault(document);
|
||||
await writeDocument(migrated);
|
||||
return migrated;
|
||||
}
|
||||
|
||||
cachedDocument = document;
|
||||
return document;
|
||||
}
|
||||
|
||||
async function initializeLegacyRendererMigrationUnlocked(): Promise<PersistedDesktopSettingsDocument> {
|
||||
try {
|
||||
return await loadDocumentUnlocked();
|
||||
} catch {
|
||||
const document = buildDefaultDocument();
|
||||
await writeDocument(document);
|
||||
return document;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async get(): Promise<DesktopSettings> {
|
||||
const document = await enqueueOperation(async () => {
|
||||
if (cachedDocument) {
|
||||
return cachedDocument;
|
||||
}
|
||||
return loadDocumentUnlocked();
|
||||
});
|
||||
const document = await enqueueOperation(() => loadDocumentUnlocked());
|
||||
return toDesktopSettings(document.settings);
|
||||
},
|
||||
|
||||
@@ -346,7 +337,7 @@ export function createDesktopSettingsStore({
|
||||
|
||||
async migrateLegacyRendererSettings(legacySettings: unknown): Promise<DesktopSettings> {
|
||||
return enqueueOperation(async () => {
|
||||
const current = await initializeLegacyRendererMigrationUnlocked();
|
||||
const current = await loadDocumentUnlocked({ recoverUnreadable: true });
|
||||
if (current.migrations.legacyRendererSettingsImported) {
|
||||
return toDesktopSettings(current.settings);
|
||||
}
|
||||
|
||||
@@ -1,242 +0,0 @@
|
||||
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,25 +46,6 @@ 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,
|
||||
@@ -3870,13 +3851,6 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
TunnelExposuresListRequestSchema,
|
||||
TunnelExposureOpenRequestSchema,
|
||||
TunnelExposureCloseRequestSchema,
|
||||
McpServerGetStatusRequestSchema,
|
||||
McpServerConfigureRequestSchema,
|
||||
McpServerAccessListRequestSchema,
|
||||
McpServerTokensCreateRequestSchema,
|
||||
McpServerCredentialsRevokeRequestSchema,
|
||||
McpServerApprovalsDecideRequestSchema,
|
||||
McpServerApprovalCodesCreateRequestSchema,
|
||||
NetworkTunnelCreateTicketRequestSchema,
|
||||
|
||||
BrowserHostRegisterRequestSchema,
|
||||
@@ -4400,8 +4374,6 @@ 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.
|
||||
@@ -8259,15 +8231,6 @@ 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/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: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: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",
|
||||
|
||||
@@ -2393,6 +2393,50 @@ async function createControlledInterruptFixture(options: {
|
||||
};
|
||||
}
|
||||
|
||||
test("a recorded submitted prompt persists and publishes its time while the turn runs", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-submitted-prompt-time-"));
|
||||
const session = new ControlledInterruptSession(
|
||||
{ provider: "codex", cwd: workdir },
|
||||
"turn-submitted-prompt-time",
|
||||
async () => undefined,
|
||||
);
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const states: ManagedAgent[] = [];
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state") states.push(event.agent);
|
||||
},
|
||||
{ replayState: false },
|
||||
);
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
const run = manager.streamAgent(agent.id, "keep working", {
|
||||
clientMessageId: "submitted-prompt",
|
||||
});
|
||||
void drainAsyncGenerator(run).catch(() => undefined);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
await manager.flush();
|
||||
|
||||
const live = manager.getAgent(agent.id);
|
||||
expect(live?.lifecycle).toBe("running");
|
||||
const recordedAt = live?.lastUserMessageAt;
|
||||
expect(recordedAt).toBeInstanceOf(Date);
|
||||
expect((await storage.get(agent.id))?.lastUserMessageAt).toBe(recordedAt?.toISOString());
|
||||
expect(states.at(-1)?.lastUserMessageAt).toEqual(recordedAt);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
class HeldRuntimeInfoSession extends TestAgentSession {
|
||||
private readonly runtimeInfoRequested = deferred<void>();
|
||||
private readonly runtimeInfoAllowed = deferred<void>();
|
||||
@@ -4559,7 +4603,7 @@ test("createAgent injects paseo MCP server only into provider launch config", as
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000103",
|
||||
});
|
||||
|
||||
@@ -4587,8 +4631,7 @@ 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/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${manager.getAgentMcpToken(snapshot.id)}` },
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${snapshot.id}`,
|
||||
},
|
||||
custom: {
|
||||
type: "stdio",
|
||||
@@ -4808,7 +4851,7 @@ test("createAgent passes native Paseo tools through launch context without inter
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
paseoToolCatalogFactory: () => paseoTools,
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000106",
|
||||
});
|
||||
@@ -4872,7 +4915,8 @@ test("createAgent allows best-effort internal MCP when the provider session repo
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: "cap-token",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000104",
|
||||
});
|
||||
|
||||
@@ -4885,12 +4929,11 @@ test("createAgent allows best-effort internal MCP when the provider session repo
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
|
||||
const token = manager.getAgentMcpToken(snapshot.id);
|
||||
expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
||||
expect(manager.getMcpAuthToken()).toBe("cap-token");
|
||||
expect(client.lastConfig?.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${token!}` },
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${snapshot.id}`,
|
||||
headers: { Authorization: "Bearer cap-token" },
|
||||
});
|
||||
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
@@ -4937,7 +4980,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/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
resolvePaseoToolPolicy: (provider) => policies.get(provider),
|
||||
paseoToolCatalogFactory: async (context) => {
|
||||
policyInputs.push(context);
|
||||
@@ -5017,7 +5060,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/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
resolvePaseoToolPolicy: () => ({ disabledTools: ["list_agents"] }),
|
||||
});
|
||||
const enabledAgent = await enabledManager.createAgent(
|
||||
@@ -5028,8 +5071,7 @@ 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/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${enabledManager.getAgentMcpToken(enabledAgent.id)}` },
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${enabledAgent.id}`,
|
||||
});
|
||||
|
||||
const disabledClient = new McpClient();
|
||||
@@ -5038,7 +5080,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/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
paseoToolsEnabled: false,
|
||||
resolvePaseoToolPolicy: () => ({ enabled: true }),
|
||||
paseoToolCatalogFactory: () => {
|
||||
@@ -5149,7 +5191,8 @@ 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/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: "voice-token",
|
||||
paseoToolsEnabled: false,
|
||||
hasActiveVoiceTools: (agentId) => voiceActiveAgents.has(agentId),
|
||||
paseoToolCatalogFactory: (context) => {
|
||||
@@ -5184,12 +5227,10 @@ 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/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${voiceToken!}` },
|
||||
url: `http://127.0.0.1:6767/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
headers: { Authorization: "Bearer voice-token" },
|
||||
});
|
||||
expect(mcpClient.launchContexts.at(-1)?.voiceToolsEnabled).toBe(true);
|
||||
|
||||
@@ -5296,7 +5337,7 @@ test("reloadAgentSession rejects voice mode when the session cannot mount speak
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
paseoToolsEnabled: false,
|
||||
hasActiveVoiceTools: () => voiceActive,
|
||||
});
|
||||
@@ -5368,7 +5409,7 @@ test("resumeAgentFromPersistence replaces stored internal paseo MCP with current
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6768/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6768/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000105",
|
||||
});
|
||||
const handle: AgentPersistenceHandle = {
|
||||
@@ -5396,8 +5437,7 @@ 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/_internal/mcp/agents",
|
||||
headers: { Authorization: `Bearer ${manager.getAgentMcpToken(snapshot.id)}` },
|
||||
url: `http://127.0.0.1:6768/mcp/agents?callerAgentId=${snapshot.id}`,
|
||||
},
|
||||
custom: {
|
||||
type: "stdio",
|
||||
@@ -5467,7 +5507,7 @@ test("createAgent preserves a user-provided paseo MCP config", async () => {
|
||||
},
|
||||
registry: storage,
|
||||
logger,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
idFactory: () => "00000000-0000-4000-8000-000000000104",
|
||||
});
|
||||
|
||||
|
||||
@@ -147,9 +147,7 @@ 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,
|
||||
@@ -505,13 +503,16 @@ export interface ManagedImportableSessionsResult {
|
||||
providerErrors: ImportableSessionProviderError[];
|
||||
}
|
||||
|
||||
export type AgentAttentionCallback = (params: {
|
||||
export interface AgentAttentionEvent {
|
||||
agentId: string;
|
||||
provider: AgentProvider;
|
||||
reason: "finished" | "error" | "permission";
|
||||
finishedTurnId?: string;
|
||||
/** When the agent's current unread attention started; null when the agent is read. */
|
||||
attentionTimestamp: Date | null;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
export type AgentAttentionCallback = (event: AgentAttentionEvent) => void;
|
||||
|
||||
export type AgentArchivedCallback = (agentId: string) => Promise<void> | void;
|
||||
|
||||
@@ -570,7 +571,7 @@ export interface AgentManagerOptions {
|
||||
timeline?: AgentTimeline;
|
||||
terminalManager?: TerminalManager | null;
|
||||
mcpBaseUrl?: string;
|
||||
mcpTokenRegistry?: AgentMcpTokenRegistry;
|
||||
mcpAuthToken?: string;
|
||||
pluginSessions?: PluginSessionsRuntime;
|
||||
paseoToolsEnabled?: boolean;
|
||||
paseoToolCatalogFactory?: PaseoToolCatalogFactory;
|
||||
@@ -1282,8 +1283,7 @@ export class AgentManager {
|
||||
>();
|
||||
private readonly agentStreamCoalescer: AgentStreamCoalescer;
|
||||
private mcpBaseUrl: string | null;
|
||||
private readonly mcpTokenRegistry: AgentMcpTokenRegistry;
|
||||
private readonly launchingAgents = new Set<string>();
|
||||
private readonly mcpAuthToken: string | null;
|
||||
private readonly pluginSessions: PluginSessionsRuntime | undefined;
|
||||
private paseoToolsEnabled = true;
|
||||
private paseoToolCatalogFactory: PaseoToolCatalogFactory | null = null;
|
||||
@@ -1314,7 +1314,7 @@ export class AgentManager {
|
||||
this.onAgentAttention = options?.onAgentAttention;
|
||||
this.onWorkspaceStateMayHaveChanged = options?.onWorkspaceStateMayHaveChanged;
|
||||
this.mcpBaseUrl = options?.mcpBaseUrl ?? null;
|
||||
this.mcpTokenRegistry = options?.mcpTokenRegistry ?? new AgentMcpTokenRegistry();
|
||||
this.mcpAuthToken = options?.mcpAuthToken ?? null;
|
||||
this.configurePaseoTools(options);
|
||||
this.resolvePaseoToolPolicy = options.resolvePaseoToolPolicy ?? (() => undefined);
|
||||
this.resolveWorkspaceProjectResourceApproval = options.resolveWorkspaceProjectResourceApproval;
|
||||
@@ -1560,26 +1560,14 @@ export class AgentManager {
|
||||
return this.paseoToolPolicies.get(agentId);
|
||||
}
|
||||
|
||||
private syncAgentMcpTokenAfterLaunch(agentId: string, launchConfig: AgentSessionConfig): void {
|
||||
if (!hasInternalPaseoMcpServer(launchConfig)) {
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the active per-agent MCP capability token if one is issued for the
|
||||
* agent, without minting a new token.
|
||||
* 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.
|
||||
*/
|
||||
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);
|
||||
getMcpAuthToken(): string | null {
|
||||
return this.mcpAuthToken;
|
||||
}
|
||||
|
||||
setAppendSystemPrompt(prompt: string | null | undefined): void {
|
||||
@@ -2254,7 +2242,6 @@ 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 }),
|
||||
@@ -2399,7 +2386,6 @@ export class AgentManager {
|
||||
restoring: true,
|
||||
importMissingHistory: true,
|
||||
});
|
||||
this.syncAgentMcpTokenAfterLaunch(resolvedAgentId, providerLaunchConfig);
|
||||
return await this.settleStoredRewind(registered);
|
||||
}
|
||||
|
||||
@@ -2491,7 +2477,6 @@ 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);
|
||||
@@ -3035,7 +3020,6 @@ export class AgentManager {
|
||||
previousSessions,
|
||||
restoring: true,
|
||||
});
|
||||
this.syncAgentMcpTokenAfterLaunch(agentId, providerLaunchConfig);
|
||||
|
||||
await this.timeline.completeProviderSwitch(scope, intent.id);
|
||||
|
||||
@@ -3076,10 +3060,7 @@ 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);
|
||||
this.mcpTokenRegistry.revoke(params.agentId);
|
||||
}
|
||||
if (params.closedExisting) this.detachPluginTools(params.agentId);
|
||||
this.restoreToolPolicyOnSwitchFailure(
|
||||
params.agentId,
|
||||
params.hadPreviousPaseoToolPolicy,
|
||||
@@ -3116,17 +3097,11 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3227,9 +3202,6 @@ 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))
|
||||
@@ -3247,10 +3219,7 @@ 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);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
}
|
||||
if (closedExisting) this.detachPluginTools(agentId);
|
||||
if (hadPreviousPaseoToolPolicy) {
|
||||
this.paseoToolPolicies.set(agentId, previousPaseoToolPolicy);
|
||||
} else {
|
||||
@@ -3542,7 +3511,6 @@ export class AgentManager {
|
||||
persistError = error;
|
||||
}
|
||||
this.detachPluginTools(agentId);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
this.emitClosedAgent(closedAgent, {
|
||||
persist: false,
|
||||
emitState: persistError !== undefined ? true : options?.emitState,
|
||||
@@ -4359,7 +4327,6 @@ export class AgentManager {
|
||||
|
||||
this.paseoToolPolicies.delete(agentId);
|
||||
this.detachPluginTools(agentId);
|
||||
this.mcpTokenRegistry.revoke(agentId);
|
||||
if (!nextRecord.internal) this.dispatchStoredAgentState(nextRecord);
|
||||
|
||||
await this.fireAgentArchived(agentId);
|
||||
@@ -5154,7 +5121,7 @@ export class AgentManager {
|
||||
);
|
||||
if (!shouldHoldBusyForReplacement) {
|
||||
this.touchUpdatedAt(mutableAgent);
|
||||
this.emitState(mutableAgent);
|
||||
this.emitState(mutableAgent, { finishedTurnId: turnId });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5993,12 +5960,12 @@ export class AgentManager {
|
||||
});
|
||||
}
|
||||
|
||||
async getLastAssistantMessage(agentId: string): Promise<string | null> {
|
||||
async getLastAssistantMessage(agentId: string, turnId?: string): Promise<string | null> {
|
||||
const scope: TimelineScope = { agentId };
|
||||
if (!(await this.timeline.describe(scope))) {
|
||||
return null;
|
||||
}
|
||||
return await this.timeline.lastAssistantMessage(scope);
|
||||
return await this.timeline.lastAssistantMessage(scope, turnId);
|
||||
}
|
||||
|
||||
private getLastAssistantMessageFromTimeline(
|
||||
@@ -6701,7 +6668,6 @@ 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);
|
||||
}
|
||||
@@ -7062,20 +7028,18 @@ export class AgentManager {
|
||||
flags,
|
||||
});
|
||||
|
||||
if (!options?.fromHistory) {
|
||||
if (isTurnTerminalEvent(event)) {
|
||||
this.runs.settleTerminalRun(agent.id, eventTurnId);
|
||||
if (isForegroundEvent) {
|
||||
this.finalizeForegroundTurn(agent, eventTurnId);
|
||||
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
|
||||
// Publish autonomous readiness only after the tracked run has settled.
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
if (flags.shouldDispatchEvent) {
|
||||
this.dispatchStream(agent.id, event, { timestamp: new Date().toISOString() });
|
||||
}
|
||||
if (isTurnTerminalEvent(event)) {
|
||||
this.finalizeStreamTurn({
|
||||
agent,
|
||||
event,
|
||||
options,
|
||||
isForegroundEvent,
|
||||
eventTurnId,
|
||||
terminalDisposition,
|
||||
});
|
||||
}
|
||||
if (!options?.fromHistory && flags.shouldDispatchEvent) {
|
||||
this.dispatchStream(agent.id, event, { timestamp: new Date().toISOString() });
|
||||
}
|
||||
|
||||
this.traceHandleStreamEventEnd(agent, event, eventTurnId, flags);
|
||||
@@ -7083,6 +7047,31 @@ export class AgentManager {
|
||||
return flags.shouldNotifyWaiters;
|
||||
}
|
||||
|
||||
private finalizeStreamTurn(params: Omit<StreamEventDispatch, "flags">): void {
|
||||
const { agent, event, options, isForegroundEvent, eventTurnId, terminalDisposition } = params;
|
||||
// Keep the idle transition next to its state emission. A runtime refresh during the
|
||||
// timeline write must not publish the finish before we can supply its turn ID.
|
||||
if (
|
||||
event.type === "turn_completed" &&
|
||||
terminalDisposition !== "stale" &&
|
||||
!isForegroundEvent &&
|
||||
!agent.activeForegroundTurnId &&
|
||||
agent.lifecycle !== "idle" &&
|
||||
!agent.pendingReplacement
|
||||
) {
|
||||
(agent as ActiveManagedAgent).lifecycle = agent.historySaveError ? "error" : "idle";
|
||||
}
|
||||
|
||||
if (options?.fromHistory) return;
|
||||
this.runs.settleTerminalRun(agent.id, eventTurnId);
|
||||
if (isForegroundEvent) {
|
||||
this.finalizeForegroundTurn(agent, eventTurnId);
|
||||
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
|
||||
// Publish autonomous readiness only after the tracked run has settled.
|
||||
this.emitState(agent, { finishedTurnId: eventTurnId });
|
||||
}
|
||||
}
|
||||
|
||||
private traceHandleStreamEventStart(
|
||||
agent: ActiveManagedAgent,
|
||||
event: AgentStreamEvent,
|
||||
@@ -7174,8 +7163,8 @@ export class AgentManager {
|
||||
|
||||
/**
|
||||
* Applies the event by type, then stamps a completed turn's metrics, returning the event as
|
||||
* stamped. Handlers change the agent's state before they write, so a terminal event whose
|
||||
* record fails to write still ends the turn; the failure is logged.
|
||||
* stamped. A live terminal event still ends the turn when its record fails to write.
|
||||
* In that case, the failure is logged.
|
||||
*/
|
||||
private async recordStreamEvent(params: StreamEventDispatch): Promise<AgentStreamEvent> {
|
||||
const { agent, options, eventTurnId, terminalDisposition } = params;
|
||||
@@ -7248,7 +7237,6 @@ export class AgentManager {
|
||||
agent,
|
||||
event,
|
||||
eventTurnId,
|
||||
isForegroundEvent,
|
||||
terminalDisposition,
|
||||
});
|
||||
return undefined;
|
||||
@@ -7324,10 +7312,6 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
await this.recordAndDispatchTimelineItem(agent.id, item, event.provider, event.turnId);
|
||||
if (item.type === "user_message") {
|
||||
agent.lastUserMessageAt = new Date();
|
||||
this.emitState(agent);
|
||||
}
|
||||
flags.shouldNotifyWaiters = true;
|
||||
}
|
||||
}
|
||||
@@ -7340,10 +7324,9 @@ export class AgentManager {
|
||||
agent: ActiveManagedAgent;
|
||||
event: Extract<AgentStreamEvent, { type: "turn_completed" }>;
|
||||
eventTurnId: string | undefined;
|
||||
isForegroundEvent: boolean;
|
||||
terminalDisposition: ActiveTurnTerminalDisposition;
|
||||
}): void {
|
||||
const { agent, event, eventTurnId, isForegroundEvent, terminalDisposition } = params;
|
||||
const { agent, event, eventTurnId, terminalDisposition } = params;
|
||||
this.logger.trace(
|
||||
{
|
||||
agentId: agent.id,
|
||||
@@ -7363,14 +7346,6 @@ export class AgentManager {
|
||||
// data accumulated during streaming isn't lost when the provider omits
|
||||
// it from the completion event.
|
||||
agent.lastError = agent.historySaveError;
|
||||
if (
|
||||
!isForegroundEvent &&
|
||||
!agent.activeForegroundTurnId &&
|
||||
agent.lifecycle !== "idle" &&
|
||||
!agent.pendingReplacement
|
||||
) {
|
||||
(agent as ActiveManagedAgent).lifecycle = agent.historySaveError ? "error" : "idle";
|
||||
}
|
||||
void this.refreshRuntimeInfo(agent);
|
||||
}
|
||||
|
||||
@@ -7627,6 +7602,13 @@ export class AgentManager {
|
||||
options?.onRecorded?.();
|
||||
this.publishTimelineEvent(agentId, event, commit);
|
||||
if (options?.notifyWaiters) this.notifyForegroundTurnWaiters(agentId, event);
|
||||
if (item.type === "user_message") {
|
||||
const agent = this.agents.get(agentId);
|
||||
if (agent) {
|
||||
agent.lastUserMessageAt = new Date();
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
if (
|
||||
item.type === "tool_call" &&
|
||||
item.status === "completed" &&
|
||||
@@ -7791,7 +7773,6 @@ export class AgentManager {
|
||||
...(options?.rejected ? { rejected: true } : {}),
|
||||
onRecorded: () => {
|
||||
this.touchUpdatedAt(agent);
|
||||
if (item.type === "user_message") agent.lastUserMessageAt = new Date();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -7874,9 +7855,12 @@ export class AgentManager {
|
||||
return parts.join("\n\n");
|
||||
}
|
||||
|
||||
private emitState(agent: ManagedAgent, options?: { persist?: boolean }): void {
|
||||
private emitState(
|
||||
agent: ManagedAgent,
|
||||
options?: { persist?: boolean; finishedTurnId?: string },
|
||||
): void {
|
||||
// Keep attention as an edge-triggered unread signal, not a level signal.
|
||||
this.checkAndSetAttention(agent);
|
||||
this.checkAndSetAttention(agent, options?.finishedTurnId);
|
||||
if (options?.persist !== false) {
|
||||
this.enqueueBackgroundPersist(agent);
|
||||
}
|
||||
@@ -7909,7 +7893,7 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
private checkAndSetAttention(agent: ManagedAgent): void {
|
||||
private checkAndSetAttention(agent: ManagedAgent, finishedTurnId?: string): void {
|
||||
const previousStatus = this.previousStatuses.get(agent.id);
|
||||
const currentStatus = agent.lifecycle;
|
||||
|
||||
@@ -7929,7 +7913,7 @@ export class AgentManager {
|
||||
if (agent.attention.requiresAttention) {
|
||||
// The unread finish stays the same; the notifier knows whether the user was told about it.
|
||||
if (finished && agent.attention.attentionReason === "finished") {
|
||||
this.broadcastAgentAttention(agent, "finished");
|
||||
this.broadcastAgentAttention(agent, "finished", finishedTurnId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -7940,7 +7924,7 @@ export class AgentManager {
|
||||
attentionReason: "finished",
|
||||
attentionTimestamp: new Date(),
|
||||
};
|
||||
this.broadcastAgentAttention(agent, "finished");
|
||||
this.broadcastAgentAttention(agent, "finished", finishedTurnId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8022,6 +8006,7 @@ export class AgentManager {
|
||||
private broadcastAgentAttention(
|
||||
agent: ManagedAgent,
|
||||
reason: "finished" | "error" | "permission",
|
||||
finishedTurnId?: string,
|
||||
): void {
|
||||
if (isDelegatedAgent(agent)) {
|
||||
return;
|
||||
@@ -8031,6 +8016,7 @@ export class AgentManager {
|
||||
agentId: agent.id,
|
||||
provider: agent.provider,
|
||||
reason,
|
||||
...(finishedTurnId === undefined ? {} : { finishedTurnId }),
|
||||
attentionTimestamp: agent.attention.requiresAttention
|
||||
? agent.attention.attentionTimestamp
|
||||
: null,
|
||||
@@ -8256,16 +8242,12 @@ 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,
|
||||
mcpBaseUrl: shouldInjectMcp ? this.mcpBaseUrl : null,
|
||||
mcpAuthToken,
|
||||
agentId,
|
||||
mcpBaseUrl: generalEnabled || voiceActive ? this.mcpBaseUrl : null,
|
||||
mcpAuthToken: this.mcpAuthToken,
|
||||
}),
|
||||
);
|
||||
return { storedConfig, launchConfig, paseoToolPolicy };
|
||||
|
||||
@@ -18,7 +18,6 @@ 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";
|
||||
@@ -103,7 +102,6 @@ async function createMcpClient(url: string, authToken?: string): Promise<McpClie
|
||||
|
||||
interface OfflineDaemon {
|
||||
mcpUrl: string;
|
||||
localToken: string;
|
||||
stop: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -142,12 +140,7 @@ async function startOfflineDaemon(logger = pino({ level: "silent" })): Promise<O
|
||||
await stop();
|
||||
throw error;
|
||||
}
|
||||
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 };
|
||||
return { mcpUrl: `http://127.0.0.1:${port}/mcp/agents`, stop };
|
||||
}
|
||||
|
||||
interface OfflineMcpDaemon {
|
||||
@@ -158,7 +151,7 @@ interface OfflineMcpDaemon {
|
||||
async function startOfflineMcpDaemon(): Promise<OfflineMcpDaemon> {
|
||||
const daemon = await startOfflineDaemon();
|
||||
try {
|
||||
const client = await createMcpClient(daemon.mcpUrl, daemon.localToken);
|
||||
const client = await createMcpClient(daemon.mcpUrl);
|
||||
return {
|
||||
client,
|
||||
stop: async () => {
|
||||
@@ -199,20 +192,12 @@ 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),
|
||||
authToken
|
||||
? { requestInit: { headers: { Authorization: `Bearer ${authToken}` } } }
|
||||
: undefined,
|
||||
),
|
||||
);
|
||||
await client.connect(new StandardMcpHttpTransport(new URL(mcpUrl)));
|
||||
try {
|
||||
const tools = await client.listTools();
|
||||
const workspaces = await client.callTool({ name: "list_workspaces", arguments: {} });
|
||||
@@ -341,10 +326,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -435,9 +417,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}/_internal/mcp/agents`;
|
||||
const localToken = readLocalCredential(paseoHome);
|
||||
expect(typeof localToken).toBe("string");
|
||||
const mcpUrl = `http://127.0.0.1:${port}/mcp/agents`;
|
||||
const capabilityToken = daemon.agentManager.getMcpAuthToken();
|
||||
expect(typeof capabilityToken).toBe("string");
|
||||
|
||||
let agentId: string | null = null;
|
||||
let client: McpClient | null = null;
|
||||
@@ -451,9 +433,12 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
});
|
||||
expect(unauthorized.status).toBe(401);
|
||||
|
||||
// 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!);
|
||||
// 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!);
|
||||
const result = await client.callTool({
|
||||
name: "create_agent",
|
||||
args: {
|
||||
@@ -467,16 +452,6 @@ 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 } });
|
||||
@@ -511,10 +486,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
const disabledPaseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-home-disabled-"));
|
||||
const disabledStaticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-disabled-"));
|
||||
@@ -536,10 +508,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(disabledPaseoHome)!,
|
||||
);
|
||||
const disabledClient = await createMcpClient(`http://127.0.0.1:${disabledPort}/mcp/agents`);
|
||||
|
||||
let agentId: string | null = null;
|
||||
let disabledAgentId: string | null = null;
|
||||
@@ -561,8 +530,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
expect(recorder.recordedLaunches.at(-1)?.mcpServers).toMatchObject({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
headers: { Authorization: `Bearer ${daemon.agentManager.getAgentMcpToken(agentId!)}` },
|
||||
url: `http://127.0.0.1:${port}/mcp/agents?callerAgentId=${agentId!}`,
|
||||
},
|
||||
});
|
||||
const injectedAgent = daemon.agentManager.getAgent(agentId!);
|
||||
@@ -609,8 +577,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}/_internal/mcp/agents`;
|
||||
const client = await createMcpClient(mcpUrl, readLocalCredential(daemon.paseoHome)!);
|
||||
const mcpUrl = `http://127.0.0.1:${daemon.port}/mcp/agents`;
|
||||
const client = await createMcpClient(mcpUrl);
|
||||
const settingsClient = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.18.2",
|
||||
@@ -618,11 +586,8 @@ 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), {
|
||||
requestInit: { headers: { Authorization: `Bearer ${agentToken!}` } },
|
||||
}),
|
||||
new StandardMcpHttpTransport(new URL(`${mcpUrl}?callerAgentId=${agentId!}`)),
|
||||
);
|
||||
try {
|
||||
return (await agentClient.listTools()).tools.map((tool) => tool.name);
|
||||
@@ -688,10 +653,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -712,8 +674,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
expect(recorder.recordedLaunches.at(-1)?.mcpServers).toMatchObject({
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: `http://127.0.0.1:${port}/_internal/mcp/agents`,
|
||||
headers: { Authorization: `Bearer ${daemon.agentManager.getAgentMcpToken(agentId!)}` },
|
||||
url: `http://127.0.0.1:${port}/mcp/agents?callerAgentId=${agentId!}`,
|
||||
},
|
||||
});
|
||||
const injectedAgent = daemon.agentManager.getAgent(agentId!);
|
||||
@@ -785,13 +746,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("/_internal/mcp/agents");
|
||||
expect(mcpUrl.searchParams.has("callerAgentId")).toBe(false);
|
||||
expect(mcpUrl.pathname).toBe("/mcp/agents");
|
||||
expect(mcpUrl.searchParams.get("callerAgentId")).toBe(agentId);
|
||||
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}/_internal/mcp/agents`, {
|
||||
const unauthorized = await fetch(`http://127.0.0.1:${loopbackPort}/mcp/agents`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: "{}",
|
||||
@@ -808,7 +769,7 @@ describe("agent MCP end-to-end (offline)", () => {
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port: loopbackPort!,
|
||||
path: "/_internal/mcp/agents",
|
||||
path: "/mcp/agents",
|
||||
method: "POST",
|
||||
headers: {
|
||||
host: `evil.example:${loopbackPort!}`,
|
||||
@@ -826,7 +787,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.getAgentMcpToken(agentId);
|
||||
const capabilityToken = daemon.agentManager.getMcpAuthToken();
|
||||
expect(typeof capabilityToken).toBe("string");
|
||||
expect(injectedMcp.headers?.Authorization).toBe(`Bearer ${capabilityToken!}`);
|
||||
mcpClient = await createMcpClient(injectedMcp.url, capabilityToken!);
|
||||
@@ -932,10 +893,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -1115,10 +1073,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
try {
|
||||
const result = await client.callTool({
|
||||
@@ -1165,10 +1120,7 @@ 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}/_internal/mcp/agents`,
|
||||
readLocalCredential(paseoHome)!,
|
||||
);
|
||||
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
|
||||
let agentId: string | null = null;
|
||||
try {
|
||||
@@ -1264,11 +1216,7 @@ 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" },
|
||||
daemon.localToken,
|
||||
);
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, { pin: "2026-07-28" });
|
||||
expect(session.negotiatedProtocolVersion).toBe("2026-07-28");
|
||||
expect(session.toolNames).toEqual(expect.arrayContaining(["create_agent", "update_agent"]));
|
||||
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
|
||||
@@ -1281,7 +1229,7 @@ describe("agent MCP protocol negotiation", () => {
|
||||
const { logger, logs } = createCapturingLogger();
|
||||
const daemon = await startOfflineDaemon(logger);
|
||||
try {
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "auto", daemon.localToken);
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "auto");
|
||||
expect(session.negotiatedProtocolVersion).toBe("2026-07-28");
|
||||
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
|
||||
expect(logs.filter((log) => log.msg === "Agent MCP transport error")).toEqual([]);
|
||||
@@ -1293,7 +1241,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", daemon.localToken);
|
||||
const session = await runStandardMcpSession(daemon.mcpUrl, "legacy");
|
||||
expect(session.negotiatedProtocolVersion).toMatch(/^2025-/);
|
||||
expect(session.toolNames).toEqual(expect.arrayContaining(["create_agent", "update_agent"]));
|
||||
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
|
||||
@@ -1589,19 +1537,11 @@ describe("voice-only speak MCP delivery", () => {
|
||||
);
|
||||
expect(claudeLaunches.at(-1)?.mcpServers?.paseo).toBeUndefined();
|
||||
|
||||
// When mcp.enabled=false, authenticated non-voice /_internal/mcp/agents requests still get 404.
|
||||
const localToken = readLocalCredential(paseoHome)!;
|
||||
// When mcp.enabled=false, non-voice /mcp/agents requests still get 404.
|
||||
if (!mcpEnabled) {
|
||||
const nonVoiceRes = await fetch(
|
||||
`http://127.0.0.1:${port}/_internal/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${localToken}`,
|
||||
},
|
||||
body: "{}",
|
||||
},
|
||||
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${claudeAgent.id}`,
|
||||
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
|
||||
);
|
||||
expect(nonVoiceRes.status).toBe(404);
|
||||
}
|
||||
@@ -1617,7 +1557,7 @@ describe("voice-only speak MCP delivery", () => {
|
||||
|
||||
const { toolNames } = await listMcpToolsAndCallSpeak(
|
||||
injected.url,
|
||||
daemon.agentManager.getAgentMcpToken(claudeAgent.id),
|
||||
daemon.agentManager.getMcpAuthToken(),
|
||||
"Hello from voice mode",
|
||||
);
|
||||
expect(toolNames).toEqual(["speak"]);
|
||||
@@ -1636,15 +1576,8 @@ 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}/_internal/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
Authorization: `Bearer ${localToken}`,
|
||||
},
|
||||
body: "{}",
|
||||
},
|
||||
`http://127.0.0.1:${port}/mcp/agents?callerAgentId=${unsupportedAgent.id}`,
|
||||
{ method: "POST", headers: { "content-type": "application/json" }, body: "{}" },
|
||||
);
|
||||
expect(rejectedRes.status).toBe(404);
|
||||
}
|
||||
|
||||
@@ -132,9 +132,9 @@ async function startAgentMcpServer(logger: pino.Logger): Promise<AgentMcpServerH
|
||||
void runAgentMcpRequest(req, res);
|
||||
};
|
||||
|
||||
app.post("/_internal/mcp/agents", handleAgentMcpRequest);
|
||||
app.get("/_internal/mcp/agents", handleAgentMcpRequest);
|
||||
app.delete("/_internal/mcp/agents", handleAgentMcpRequest);
|
||||
app.post("/mcp/agents", handleAgentMcpRequest);
|
||||
app.get("/mcp/agents", handleAgentMcpRequest);
|
||||
app.delete("/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}/_internal/mcp/agents`;
|
||||
const url = `http://127.0.0.1:${port}/mcp/agents`;
|
||||
|
||||
return {
|
||||
url,
|
||||
|
||||
@@ -11,7 +11,6 @@ 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";
|
||||
@@ -51,14 +50,8 @@ 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}/_internal/mcp/agents`),
|
||||
{
|
||||
requestInit: { headers: { Authorization: `Bearer ${localToken!}` } },
|
||||
},
|
||||
),
|
||||
new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${daemon.port}/mcp/agents`)),
|
||||
);
|
||||
const realModel = provider === "codex" ? "gpt-5.6-sol" : "haiku";
|
||||
const agent = await client.createAgent({
|
||||
|
||||
@@ -14,9 +14,18 @@ export function continuesAssistantMessage(previous: MessageRow, next: MessageRow
|
||||
);
|
||||
}
|
||||
|
||||
export function lastAssistantMessageText(rows: readonly MessageRow[]): string | null {
|
||||
export function lastAssistantMessageText(
|
||||
rows: readonly MessageRow[],
|
||||
turnId?: string,
|
||||
): string | null {
|
||||
function* newestFirst() {
|
||||
for (let index = rows.length - 1; index >= 0; index--) yield rows[index];
|
||||
const start =
|
||||
turnId === undefined
|
||||
? rows.length - 1
|
||||
: rows.findLastIndex(
|
||||
(row) => row.turnId === turnId && row.item.type === "assistant_message",
|
||||
);
|
||||
for (let index = start; index >= 0; index--) yield rows[index];
|
||||
}
|
||||
return readLastAssistantMessage(newestFirst());
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
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,
|
||||
DaemonPermission,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { AgentActiveTurnBehavior, AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
@@ -16,6 +12,7 @@ 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";
|
||||
@@ -95,15 +92,8 @@ export interface ToolHosts {
|
||||
): Promise<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
/** Daemon MCP has the daemon's authority, bounded by the destination's admission of its link. */
|
||||
export function createToolHosts(hosts: ConnectedHosts): ToolHosts {
|
||||
return {
|
||||
directory: () => hosts.list(),
|
||||
async use(serverId, action, signal) {
|
||||
@@ -122,7 +112,7 @@ export function createToolHosts(
|
||||
scopeId: randomUUID(),
|
||||
sourceId: "mcp",
|
||||
originSessionId: "mcp",
|
||||
permissions,
|
||||
permissions: OWNER_PERMISSIONS,
|
||||
signal: signal ? AbortSignal.any([lifetime.signal, signal]) : lifetime.signal,
|
||||
frame: (data) => {
|
||||
for (const listener of messages) listener(data, typeof data !== "string");
|
||||
|
||||
@@ -8,7 +8,6 @@ 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";
|
||||
@@ -61,7 +60,7 @@ function formatHostForHttpUrl(host: string): string {
|
||||
|
||||
function buildExpectedAgentMcpUrl(params: { host: string; port: number; agentId: string }): string {
|
||||
const baseUrl = new URL(
|
||||
"/_internal/mcp/agents",
|
||||
"/mcp/agents",
|
||||
`http://${formatHostForHttpUrl(params.host)}:${params.port}`,
|
||||
);
|
||||
baseUrl.searchParams.set("callerAgentId", params.agentId);
|
||||
@@ -84,10 +83,8 @@ function getStructuredContent(result: McpToolResult): StructuredContent | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function createMcpClient(url: string, authToken: string): Promise<McpClient> {
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: { headers: { Authorization: `Bearer ${authToken}` } },
|
||||
});
|
||||
async function createMcpClient(url: string): Promise<McpClient> {
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url));
|
||||
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(
|
||||
@@ -284,11 +281,7 @@ beforeAll(async () => {
|
||||
agentClients: createRecordingAgentClients(),
|
||||
agentProfiles: [seededAgentProfile],
|
||||
});
|
||||
const localToken = readLocalCredential(daemonHandle.paseoHome)!;
|
||||
topLevelClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents`,
|
||||
localToken,
|
||||
);
|
||||
topLevelClient = await createMcpClient(`http://127.0.0.1:${daemonHandle.port}/mcp/agents`);
|
||||
|
||||
const parentPayload = await callToolStructured(topLevelClient, "create_agent", {
|
||||
relationship: { kind: "detached" },
|
||||
@@ -301,8 +294,7 @@ beforeAll(async () => {
|
||||
parentAgentId = str(parentPayload.agentId);
|
||||
|
||||
agentScopedClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${parentAgentId}`,
|
||||
localToken,
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${parentAgentId}`,
|
||||
);
|
||||
|
||||
execSync("git init -b main", { cwd: worktreeRepoCwd, stdio: "pipe" });
|
||||
@@ -374,7 +366,6 @@ describe("Suite A: Core Fixes", () => {
|
||||
port: daemon.port,
|
||||
agentId: caller.id,
|
||||
}),
|
||||
readLocalCredential(daemon.paseoHome)!,
|
||||
);
|
||||
const created = await callToolStructured(mcp, "create_agent", {
|
||||
relationship: { kind: relationship },
|
||||
@@ -494,7 +485,6 @@ 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" },
|
||||
@@ -665,12 +655,11 @@ describe("Suite A: Core Fixes", () => {
|
||||
);
|
||||
agentId = snapshot.id;
|
||||
|
||||
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 expectedUrl = buildExpectedAgentMcpUrl({
|
||||
host: listenTarget!.host,
|
||||
port: listenTarget!.port,
|
||||
agentId,
|
||||
});
|
||||
|
||||
const launchConfig = launchConfigsByProvider.claude
|
||||
?.toReversed()
|
||||
@@ -679,7 +668,6 @@ describe("Suite A: Core Fixes", () => {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: expectedUrl,
|
||||
headers: { Authorization: `Bearer ${expectedToken!}` },
|
||||
},
|
||||
});
|
||||
expect(snapshot.config.mcpServers?.paseo).toBeUndefined();
|
||||
@@ -707,7 +695,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.providerOptions).toEqual({ test_feature: true });
|
||||
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
|
||||
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
|
||||
@@ -725,7 +713,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
settings: { features: { test_feature: true } },
|
||||
});
|
||||
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
|
||||
expect(internalSnapshot?.config.providerOptions).toEqual({ test_feature: true });
|
||||
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
|
||||
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
|
||||
@@ -745,7 +733,7 @@ describe("Suite A: Core Fixes", () => {
|
||||
});
|
||||
expect(updated.success).toBe(true);
|
||||
const internalSnapshot = daemonHandle.daemon.agentManager.getAgent(agentId);
|
||||
expect(internalSnapshot?.config.providerOptions).toEqual({ test_feature: true });
|
||||
expect(internalSnapshot?.config.featureValues).toEqual({ test_feature: true });
|
||||
|
||||
const status = await callToolStructured(topLevelClient, "get_agent_status", { agentId });
|
||||
const snapshot = z.record(z.string(), z.unknown()).parse(status.snapshot);
|
||||
@@ -1167,7 +1155,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, options: null, thinkingOptionId: null }]);
|
||||
expect(profiles).toEqual([seededAgentProfile]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1231,8 +1219,7 @@ describe("Suite E: Workspace Tools", () => {
|
||||
});
|
||||
const agentId = str(child.agentId);
|
||||
const workerClient = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${agentId}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${agentId}`,
|
||||
);
|
||||
let terminalId: string;
|
||||
try {
|
||||
@@ -1284,8 +1271,7 @@ describe("Suite E: Workspace Tools", () => {
|
||||
initialPrompt: "Say done.",
|
||||
});
|
||||
scoped = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${str(parent.agentId)}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${str(parent.agentId)}`,
|
||||
);
|
||||
const inherited = await callToolStructured(scoped, "create_workspace", {
|
||||
isolation: "local",
|
||||
@@ -1376,8 +1362,7 @@ describe("Suite E: Workspace Tools", () => {
|
||||
initialPrompt: "Say done.",
|
||||
});
|
||||
scoped = await createMcpClient(
|
||||
`http://127.0.0.1:${daemonHandle.port}/_internal/mcp/agents?callerAgentId=${str(child.agentId)}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${str(child.agentId)}`,
|
||||
);
|
||||
|
||||
// Omit workspaceId to update caller's workspace; clear body with null and update issues.
|
||||
@@ -1455,8 +1440,7 @@ 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}/_internal/mcp/agents?callerAgentId=${callerId}`,
|
||||
readLocalCredential(daemonHandle.paseoHome)!,
|
||||
`http://127.0.0.1:${daemonHandle.port}/mcp/agents?callerAgentId=${callerId}`,
|
||||
);
|
||||
const ownedWorkspaces: string[] = [];
|
||||
try {
|
||||
@@ -1517,7 +1501,6 @@ 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/_internal/mcp/agents", {
|
||||
new Request("http://localhost/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 { PaseoToolCatalog, PaseoToolResult } from "./tools/types.js";
|
||||
import type { PaseoToolResult } from "./tools/types.js";
|
||||
|
||||
export type AgentMcpServerOptions = PaseoToolHostDependencies;
|
||||
|
||||
@@ -28,19 +28,11 @@ function toMcpToolResult(result: PaseoToolResult): CallToolResult {
|
||||
}
|
||||
|
||||
export async function createAgentMcpServer(options: AgentMcpServerOptions): Promise<McpServer> {
|
||||
return createPaseoMcpServer(await createPaseoToolCatalog(options), {
|
||||
const catalog = await createPaseoToolCatalog(options);
|
||||
const server = new McpServer({
|
||||
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(
|
||||
|
||||
@@ -1,415 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
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/_internal/mcp/agents?callerAgentId=a1" },
|
||||
"mcp_servers.paseo": { url: "http://127.0.0.1/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/_internal/mcp/agents?callerAgentId=a1",
|
||||
url: "http://127.0.0.1/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/_internal/mcp/agents?callerAgentId=a1" },
|
||||
paseo: { url: "http://127.0.0.1/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/_internal/mcp/agents?callerAgentId=a1",
|
||||
url: "http://127.0.0.1/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/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -3705,10 +3705,7 @@ describe("ACPAgentSession", () => {
|
||||
}
|
||||
|
||||
const mcpServers: AgentSessionConfig["mcpServers"] = {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
local: { type: "stdio", command: "node", args: ["mcp.js"] },
|
||||
};
|
||||
|
||||
@@ -3741,7 +3738,7 @@ describe("ACPAgentSession", () => {
|
||||
{
|
||||
type: "http",
|
||||
name: "paseo",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/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/_internal/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/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/_internal/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1/mcp/agents" } },
|
||||
} as const;
|
||||
await expect(launch(withMcp)).rejects.toThrow("Update Claude Code to 2.1.326 or later");
|
||||
});
|
||||
|
||||
@@ -1832,10 +1832,7 @@ describe("Codex app-server provider", () => {
|
||||
const session = await createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
"plugin-tool": { type: "stdio", command: "node", args: ["server.js"] },
|
||||
},
|
||||
}),
|
||||
@@ -1847,7 +1844,7 @@ describe("Codex app-server provider", () => {
|
||||
?.config;
|
||||
expect(startConfig).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
"mcp_servers.plugin-tool": {
|
||||
command: "node",
|
||||
@@ -1885,10 +1882,7 @@ describe("Codex app-server provider", () => {
|
||||
const session = await createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
"my.dotted": { type: "http", url: "http://127.0.0.1:8080/mcp" },
|
||||
},
|
||||
}),
|
||||
@@ -1901,7 +1895,7 @@ describe("Codex app-server provider", () => {
|
||||
expect(startConfig).toEqual({
|
||||
mcp_servers: {
|
||||
paseo: {
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
"my.dotted": {
|
||||
url: "http://127.0.0.1:8080/mcp",
|
||||
@@ -1922,10 +1916,7 @@ describe("Codex app-server provider", () => {
|
||||
createConfig({
|
||||
modeId: "auto",
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
},
|
||||
}),
|
||||
{ voiceToolsEnabled: true },
|
||||
@@ -1937,7 +1928,7 @@ describe("Codex app-server provider", () => {
|
||||
?.config;
|
||||
expect(startConfig).toEqual({
|
||||
"mcp_servers.paseo": {
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
tools: { speak: { approval_mode: "approve" } },
|
||||
},
|
||||
});
|
||||
@@ -3553,10 +3544,7 @@ describe("Codex app-server provider", () => {
|
||||
daemonAppendSystemPrompt: "Daemon instructions",
|
||||
pluginAppendSystemPrompt: ["Plugin instructions"],
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
},
|
||||
}),
|
||||
null,
|
||||
@@ -3612,7 +3600,7 @@ describe("Codex app-server provider", () => {
|
||||
expect.objectContaining({
|
||||
...customCodexConfig,
|
||||
"mcp_servers.paseo": expect.objectContaining({
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=test-agent",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=test-agent",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=test-agent",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=test-agent",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
+121
@@ -5,6 +5,8 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { DaemonClient } from "../../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import type { AgentLaunchContext, AgentSession, AgentSessionConfig } from "../agent-sdk-types.js";
|
||||
import { OpenCodeBridge } from "./opencode/bridge.js";
|
||||
@@ -315,3 +317,122 @@ describe.each<Mode>(["explicit", "discovered"])("OpenCode v2 %s shared service",
|
||||
expect((await second!.run(afterClose)).finalText).toBe("RESULT HUB_OK_2");
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
test("v2 opens the parent timeline and accepts prompts after a child working directory is removed", async () => {
|
||||
const fixture = await startFixture("explicit");
|
||||
const { root, project, service, bridge } = fixture;
|
||||
const childDirectory = path.join(root, "child");
|
||||
async function connectToDaemon() {
|
||||
const provider = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
bridge,
|
||||
settings: {
|
||||
env: {
|
||||
[EXTERNAL_SERVER_URL_ENV]: service.url,
|
||||
[EXTERNAL_SERVER_PASSWORD_ENV]: service.password,
|
||||
},
|
||||
},
|
||||
});
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "daemon"),
|
||||
staticDir: root,
|
||||
cleanup: false,
|
||||
agentClients: { opencode: provider },
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const close = async () => {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await provider.shutdown();
|
||||
};
|
||||
try {
|
||||
await client.connect();
|
||||
return { client, close };
|
||||
} catch (error) {
|
||||
await close();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function providerHeaders() {
|
||||
return {
|
||||
Authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}`,
|
||||
};
|
||||
}
|
||||
function providerClient() {
|
||||
return OpenCode.make({ baseUrl: service.url, headers: providerHeaders() });
|
||||
}
|
||||
let daemon: Awaited<ReturnType<typeof connectToDaemon>> | undefined;
|
||||
try {
|
||||
await mkdir(childDirectory);
|
||||
daemon = await connectToDaemon();
|
||||
const initialPrompt = scriptedCall("subagent", {
|
||||
agent: "general",
|
||||
description: "Create a child session",
|
||||
prompt: "Say hello",
|
||||
});
|
||||
const parent = await daemon.client.createAgent({
|
||||
cwd: project,
|
||||
provider: "opencode",
|
||||
model: SCRIPTED_MODEL,
|
||||
initialPrompt,
|
||||
});
|
||||
expect((await daemon.client.waitForFinish(parent.id, 30_000)).status).toBe("idle");
|
||||
|
||||
const persistedParent = await daemon.client.fetchAgent(parent.id);
|
||||
const parentSessionId = persistedParent?.agent.persistence?.sessionId;
|
||||
expect(parentSessionId).toBeDefined();
|
||||
const opencode = providerClient();
|
||||
const { data: children } = await opencode.session.list({
|
||||
parentID: parentSessionId,
|
||||
limit: 100,
|
||||
});
|
||||
expect(children).toHaveLength(1);
|
||||
const childId = children[0]!.id;
|
||||
await opencode.session.move({ sessionID: childId, directory: childDirectory });
|
||||
await expect
|
||||
.poll(async () => (await opencode.session.get({ sessionID: childId })).location.directory)
|
||||
.toBe(childDirectory);
|
||||
const readTimeline = (client: DaemonClient) =>
|
||||
client.fetchAgentTimeline(parent.id, {
|
||||
direction: "tail",
|
||||
limit: 0,
|
||||
projection: "canonical",
|
||||
});
|
||||
const before = await readTimeline(daemon.client);
|
||||
expect(
|
||||
before.entries.some(
|
||||
({ item }) => item.type === "user_message" && item.text === initialPrompt,
|
||||
),
|
||||
).toBe(true);
|
||||
await daemon.close();
|
||||
daemon = undefined;
|
||||
|
||||
await rm(childDirectory, { recursive: true });
|
||||
await service.restart();
|
||||
expect((await providerClient().session.get({ sessionID: childId })).id).toBe(childId);
|
||||
const response = await fetch(new URL(`/api/session/${childId}/permission`, service.url), {
|
||||
headers: providerHeaders(),
|
||||
});
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.json()).toMatchObject({ _tag: "LocationNotFoundError" });
|
||||
|
||||
daemon = await connectToDaemon();
|
||||
const after = await readTimeline(daemon.client);
|
||||
expect(after.entries.map(({ item }) => item)).toEqual(before.entries.map(({ item }) => item));
|
||||
const followUp = scriptedCall("shell", {
|
||||
command: "printf parent-resumed",
|
||||
description: "Confirm the parent can run a new turn",
|
||||
});
|
||||
await daemon.client.sendMessage(parent.id, followUp);
|
||||
expect(await daemon.client.waitForFinish(parent.id, 30_000)).toMatchObject({
|
||||
status: "idle",
|
||||
lastMessage: expect.stringContaining("parent-resumed"),
|
||||
});
|
||||
expect(service.agentRequests.some(({ transcript }) => transcript.includes(followUp))).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
await daemon?.close();
|
||||
await stopFixture(fixture);
|
||||
}
|
||||
}, 90_000);
|
||||
|
||||
@@ -5,6 +5,7 @@ export class OpenCodeHttpError extends Error {
|
||||
readonly operation: string,
|
||||
readonly status: number | undefined,
|
||||
readonly html: boolean,
|
||||
readonly errorTag?: string,
|
||||
) {
|
||||
const statusLabel = status === undefined ? "" : ` (HTTP ${status})`;
|
||||
super(
|
||||
@@ -17,6 +18,15 @@ export class OpenCodeHttpError extends Error {
|
||||
|
||||
/** True when OpenCode answered 404, directly or as the cause of the client's transport error. */
|
||||
export function isOpenCodeNotFound(error: unknown): boolean {
|
||||
return getOpenCodeHttpError(error)?.status === 404;
|
||||
}
|
||||
|
||||
export function isOpenCodeLocationNotFound(error: unknown): boolean {
|
||||
const failure = getOpenCodeHttpError(error);
|
||||
return failure?.status === 404 && failure.errorTag === "LocationNotFoundError";
|
||||
}
|
||||
|
||||
function getOpenCodeHttpError(error: unknown): OpenCodeHttpError | undefined {
|
||||
const failure = error instanceof OpenCodeHttpError ? error : (error as Error | null)?.cause;
|
||||
return failure instanceof OpenCodeHttpError && failure.status === 404;
|
||||
return failure instanceof OpenCodeHttpError ? failure : undefined;
|
||||
}
|
||||
|
||||
+35
-10
@@ -47,9 +47,9 @@ export class ScriptedOpenCodeService {
|
||||
private constructor(
|
||||
readonly requests: ScriptedRequest[],
|
||||
readonly root: string,
|
||||
readonly url: string,
|
||||
readonly password: string,
|
||||
private readonly process: ChildProcess,
|
||||
public url: string,
|
||||
public password: string,
|
||||
private process: ChildProcess,
|
||||
private readonly llm: Server,
|
||||
) {}
|
||||
|
||||
@@ -105,6 +105,26 @@ export class ScriptedOpenCodeService {
|
||||
}),
|
||||
);
|
||||
await options.beforeStart?.({ configDirectory });
|
||||
try {
|
||||
const { url, password, child } = await this.launch(root);
|
||||
return new ScriptedOpenCodeService(requests, root, url, password, child, llm);
|
||||
} catch (error) {
|
||||
llm.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async restart() {
|
||||
await this.stopProcess();
|
||||
await rm(path.join(this.root, "state", "opencode", "service.json"), { force: true });
|
||||
const { child, url, password } = await ScriptedOpenCodeService.launch(this.root);
|
||||
this.process = child;
|
||||
this.url = url;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
private static async launch(root: string) {
|
||||
const child = spawn(
|
||||
OPENCODE_V2_COMMAND,
|
||||
["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"],
|
||||
@@ -124,11 +144,10 @@ export class ScriptedOpenCodeService {
|
||||
const parsed = content ? (JSON.parse(content) as { url: string; password: string }) : null;
|
||||
// The service registers before it serves requests.
|
||||
if (parsed && (await isReady(parsed.url, parsed.password))) {
|
||||
return new ScriptedOpenCodeService(requests, root, parsed.url, parsed.password, child, llm);
|
||||
return { ...parsed, child };
|
||||
}
|
||||
if (child.exitCode !== null || Date.now() > deadline) {
|
||||
llm.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
child.kill();
|
||||
throw new Error(`OpenCode v2 service did not register (exit ${child.exitCode})`);
|
||||
}
|
||||
await delay(100);
|
||||
@@ -172,10 +191,17 @@ export class ScriptedOpenCodeService {
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.stopProcess();
|
||||
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
|
||||
await rm(this.root, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
private async stopProcess(): Promise<void> {
|
||||
const exited = new Promise<void>((resolve) => {
|
||||
if (this.process.exitCode !== null) resolve();
|
||||
if (this.process.exitCode !== null || this.process.signalCode !== null) resolve();
|
||||
else this.process.once("exit", () => resolve());
|
||||
});
|
||||
if (this.process.exitCode !== null || this.process.signalCode !== null) return;
|
||||
if (this.process.pid && process.platform !== "win32") {
|
||||
try {
|
||||
process.kill(-this.process.pid, "SIGTERM");
|
||||
@@ -184,9 +210,8 @@ export class ScriptedOpenCodeService {
|
||||
}
|
||||
} else this.process.kill("SIGTERM");
|
||||
await Promise.race([exited, delay(10_000)]);
|
||||
if (this.process.exitCode === null) this.process.kill("SIGKILL");
|
||||
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
|
||||
await rm(this.root, { recursive: true, force: true });
|
||||
if (this.process.exitCode === null && this.process.signalCode === null)
|
||||
this.process.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
|
||||
import type { ProviderSubagentInputEvent } from "../../../provider-subagents/store.js";
|
||||
|
||||
import { syncTailMessages } from "./history.js";
|
||||
import { isOpenCodeLocationNotFound } from "../http-error.js";
|
||||
import { buildOpenCodeSubagentSubtitle } from "../subagent-presentation.js";
|
||||
|
||||
import type { V2Api } from "./api.js";
|
||||
@@ -63,8 +64,8 @@ export class SessionChildren {
|
||||
try {
|
||||
await adoptChild(id);
|
||||
} catch (error) {
|
||||
if (!isSessionNotFoundError(error)) throw error;
|
||||
this.remove(id);
|
||||
if (isSessionNotFoundError(error)) this.remove(id);
|
||||
else if (!isOpenCodeLocationNotFound(error)) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,10 +202,16 @@ export class SessionChildren {
|
||||
});
|
||||
}
|
||||
private async reconcileChild(info: SessionInfo, parentID: string) {
|
||||
await this.options.reconcilePermissions(info.id);
|
||||
let child = this.children.get(info.id);
|
||||
try {
|
||||
await this.options.reconcilePermissions(info.id);
|
||||
if (!child) await this.options.adoptChild?.(info.id);
|
||||
} catch (error) {
|
||||
// A child can outlive its worktree. Its runtime cannot be restored until the location returns.
|
||||
if (isOpenCodeLocationNotFound(error)) return;
|
||||
throw error;
|
||||
}
|
||||
if (!child) {
|
||||
await this.options.adoptChild?.(info.id);
|
||||
child = this.children.get(info.id) ?? { parentID, timeline: new V2Timeline(), history: [] };
|
||||
this.children.set(info.id, child);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ export async function validateOpenCodeResponse(
|
||||
const html = contentType?.includes("text/html") ?? false;
|
||||
if (response.ok && !html) return response;
|
||||
|
||||
let errorTag: string | undefined;
|
||||
// The SDK needs the original body to decode the provider's missing-session error.
|
||||
if (response.status === 404 && !html && contentType?.includes("application/json")) {
|
||||
const body: unknown = await response
|
||||
@@ -16,8 +17,10 @@ export async function validateOpenCodeResponse(
|
||||
.json()
|
||||
.catch(() => null);
|
||||
if (isSessionNotFoundError(body)) return response;
|
||||
if (body && typeof body === "object" && "_tag" in body && typeof body._tag === "string")
|
||||
errorTag = body._tag;
|
||||
}
|
||||
|
||||
const url = request instanceof Request ? request.url : String(request);
|
||||
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html);
|
||||
throw new OpenCodeHttpError(new URL(url).pathname, response.status, html, errorTag);
|
||||
}
|
||||
|
||||
@@ -4226,7 +4226,7 @@ describe("PiRpcAgentClient", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents" },
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/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/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
headers: { Authorization: "Bearer token" },
|
||||
},
|
||||
local: { command: "node", args: ["server.js"], env: { KEY: "`${x}`" } },
|
||||
@@ -4355,10 +4355,7 @@ 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/_internal/mcp/agents?callerAgentId=agent-2",
|
||||
},
|
||||
paseo: { type: "http", url: "http://127.0.0.1:7777/mcp/agents?callerAgentId=agent-2" },
|
||||
},
|
||||
});
|
||||
onTestFinished(() => session.close());
|
||||
@@ -4368,7 +4365,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/_internal/mcp/agents?callerAgentId=agent-2" },
|
||||
paseo: { url: "http://127.0.0.1:7777/mcp/agents?callerAgentId=agent-2" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4382,7 +4379,7 @@ describe("PiRpcAgentClient", () => {
|
||||
]);
|
||||
const session = await createClient(pi).createSession(
|
||||
createConfig({
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1:6767/_internal/mcp/agents" } },
|
||||
mcpServers: { paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" } },
|
||||
}),
|
||||
{ env: { PI_CODING_AGENT_DIR: agentDir } },
|
||||
);
|
||||
@@ -4416,7 +4413,7 @@ describe("PiRpcAgentClient", () => {
|
||||
mcpServers: {
|
||||
paseo: {
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents?callerAgentId=agent-1",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -4445,7 +4442,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/_internal/mcp/agents" },
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents" },
|
||||
} as const;
|
||||
|
||||
interface ArchivedPiSession {
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { AgentSessionConfig } from "./agent-sdk-types.js";
|
||||
import {
|
||||
hasInternalPaseoMcpServer,
|
||||
stripInternalPaseoMcpServer,
|
||||
withRuntimePaseoMcpServer,
|
||||
} from "./runtime-mcp-config.js";
|
||||
import { withRuntimePaseoMcpServer } from "./runtime-mcp-config.js";
|
||||
|
||||
const BASE_CONFIG: AgentSessionConfig = {
|
||||
provider: "claude",
|
||||
@@ -13,74 +9,43 @@ const BASE_CONFIG: AgentSessionConfig = {
|
||||
};
|
||||
|
||||
describe("withRuntimePaseoMcpServer", () => {
|
||||
test("injects the paseo MCP server without callerAgentId in the URL and with a bearer header", () => {
|
||||
test("injects the paseo MCP server with a bearer header when a token is provided", () => {
|
||||
const result = withRuntimePaseoMcpServer({
|
||||
config: BASE_CONFIG,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
agentId: "agent-1",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: "cap-token",
|
||||
});
|
||||
|
||||
expect(result.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
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,
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
agentId: "agent-1",
|
||||
mcpBaseUrl: "http://127.0.0.1:6767/mcp/agents",
|
||||
mcpAuthToken: null,
|
||||
});
|
||||
|
||||
expect(result.mcpServers?.paseo).toEqual({
|
||||
type: "http",
|
||||
url: "http://127.0.0.1:6767/_internal/mcp/agents",
|
||||
url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1",
|
||||
});
|
||||
});
|
||||
|
||||
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,12 +1,7 @@
|
||||
import type { AgentSessionConfig, McpServerConfig } from "./agent-sdk-types.js";
|
||||
|
||||
export const PASEO_MCP_SERVER_NAME = "paseo";
|
||||
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);
|
||||
}
|
||||
const PASEO_MCP_PATHNAME = "/mcp/agents";
|
||||
|
||||
export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSessionConfig {
|
||||
const mcpServers = config.mcpServers;
|
||||
@@ -33,10 +28,12 @@ export function stripInternalPaseoMcpServer(config: AgentSessionConfig): AgentSe
|
||||
|
||||
export function withRuntimePaseoMcpServer(params: {
|
||||
config: AgentSessionConfig;
|
||||
agentId: string;
|
||||
mcpBaseUrl: string | null;
|
||||
/**
|
||||
* Per-agent capability token authenticating the injected connection to the
|
||||
* daemon's `/_internal/mcp/agents` endpoint and binding the caller identity server-side.
|
||||
* 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.
|
||||
*/
|
||||
mcpAuthToken: string | null;
|
||||
}): AgentSessionConfig {
|
||||
@@ -50,7 +47,7 @@ export function withRuntimePaseoMcpServer(params: {
|
||||
mcpServers: {
|
||||
[PASEO_MCP_SERVER_NAME]: {
|
||||
type: "http",
|
||||
url: params.mcpBaseUrl,
|
||||
url: `${params.mcpBaseUrl}?callerAgentId=${params.agentId}`,
|
||||
...(params.mcpAuthToken
|
||||
? { headers: { Authorization: `Bearer ${params.mcpAuthToken}` } }
|
||||
: {}),
|
||||
@@ -66,7 +63,7 @@ function isInternalPaseoMcpServer(config: McpServerConfig): boolean {
|
||||
}
|
||||
|
||||
try {
|
||||
return PASEO_MCP_PATHNAMES.has(new URL(config.url).pathname);
|
||||
return new URL(config.url).pathname === PASEO_MCP_PATHNAME;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -813,8 +813,8 @@ export class TimelineProjection {
|
||||
return last?.endSeq === seq && last.rowIndex >= 0 ? this.rows[last.rowIndex].item : null;
|
||||
}
|
||||
|
||||
getLastAssistantMessage(): string | null {
|
||||
return lastAssistantMessageText(this.rows);
|
||||
getLastAssistantMessage(turnId?: string): string | null {
|
||||
return lastAssistantMessageText(this.rows, turnId);
|
||||
}
|
||||
|
||||
enrichSubmittedUserMessage(
|
||||
|
||||
@@ -212,6 +212,21 @@ describe.each(
|
||||
expect(await timeline.lastAssistantMessage(root("a"))).toBe("Bye");
|
||||
});
|
||||
|
||||
it("reads assistant text only from the requested turn", async () => {
|
||||
const timeline = createTimeline();
|
||||
const scope = root("a");
|
||||
await timeline.create(scope);
|
||||
await timeline.append(scope, [
|
||||
{ turnId: "first", item: { type: "assistant_message", text: "Earlier reply" } },
|
||||
{ turnId: "silent", item: { type: "user_message", text: "Run without replying" } },
|
||||
{ turnId: "latest", item: { type: "assistant_message", text: "New reply" } },
|
||||
]);
|
||||
|
||||
expect(await timeline.lastAssistantMessage(scope, "first")).toBe("Earlier reply");
|
||||
expect(await timeline.lastAssistantMessage(scope, "silent")).toBeNull();
|
||||
expect(await timeline.lastAssistantMessage(scope, "latest")).toBe("New reply");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
scenario: "the same reply",
|
||||
|
||||
@@ -450,8 +450,8 @@ export class AgentTimeline {
|
||||
* The newest assistant reply, with its streamed chunks joined in order. Notifications within
|
||||
* an identified reply can sit between its chunks. Null when there is no assistant message.
|
||||
*/
|
||||
lastAssistantMessage(scope: TimelineScope): Promise<string | null> {
|
||||
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope));
|
||||
lastAssistantMessage(scope: TimelineScope, turnId?: string): Promise<string | null> {
|
||||
return this.run(scope, () => this.backendFor(scope).lastAssistantMessage(scope, turnId));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -214,7 +214,7 @@ export interface AgentTimelineBackend {
|
||||
readRows(scope: TimelineScope): MaybePromise<ProjectedTimelineRow[]>;
|
||||
lastItem(scope: TimelineScope): MaybePromise<AgentTimelineItem | null>;
|
||||
/** The trailing run of assistant messages joined, skipping later non-assistant rows. */
|
||||
lastAssistantMessage(scope: TimelineScope): MaybePromise<string | null>;
|
||||
lastAssistantMessage(scope: TimelineScope, turnId?: string): MaybePromise<string | null>;
|
||||
}
|
||||
|
||||
/** The scope has no history: it was never created, or it was deleted. */
|
||||
|
||||
@@ -273,8 +273,8 @@ export class MemoryTimelineBackend implements AgentTimelineBackend {
|
||||
return state.projection.getLastItem(state.nextSeq - 1);
|
||||
}
|
||||
|
||||
lastAssistantMessage(scope: TimelineScope): string | null {
|
||||
return this.requireState(scope).projection.getLastAssistantMessage();
|
||||
lastAssistantMessage(scope: TimelineScope, turnId?: string): string | null {
|
||||
return this.requireState(scope).projection.getLastAssistantMessage(turnId);
|
||||
}
|
||||
|
||||
private describe(state: MemoryTimelineState): TimelineHead {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user