mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 11:43:20 +00:00
fix(mcp): register fx and MCPorter where they read their configuration (#10698)
* fix(mcp): register fx and MCPorter where they read their configuration fx reads $FX_HOME/mcp.json when FX_HOME is set, and MCPorter reads MCPORTER_CONFIG exclusively or prefers an absolute XDG_CONFIG_HOME file. rea mcp add always wrote ~/.fx/mcp.json and ~/.mcporter/mcporter.json, which those clients then ignored. Resolve both from the clients' own rules, and refuse an FX_HOME fx itself refuses. * fix(mcp): detect MCPorter by its selected file and refuse FX_HOME aliases Address review findings: MCPORTER_CONFIG now also names the detection marker, so default registration includes MCPorter when only that file exists, and is resolved with path.resolve as MCPorter does. FX_HOME with . or .. segments is refused, so the private profile mode cannot reach the home folder through an alias. Override tests use the host's path rules for real temporary paths. * fix(mcp): never apply fx's private folder mode to the home folder A linked parent in FX_HOME can name the caller's home folder after the textual root and home checks pass. The private profile writer now compares the opened folder's identity with the caller's home folder and refuses before changing modes or publishing. * feat(setup): let doctor, update and uninstall see MCPorter registrations (#10702) * feat(setup): let doctor, update and uninstall see MCPorter registrations MCPorter becomes a client-table row, so a registration rea mcp add or rea setup --client mcporter wrote is inspected, refreshed and removed like other clients. MCPorter already imports setup-managed clients' registrations, so the row is applicable only through REA's own registration: setup never selects it from detection and doctor reports it only when its file holds a rea row or the caller selects it. A relative MCPORTER_CONFIG is refused because MCPorter resolves it per command directory. * fix(setup): detect MCPorter by the folder of the file it loads With an absolute XDG_CONFIG_HOME and only a legacy ~/.mcporter file, the row returned the legacy file but the absent XDG folder as its detection evidence, so default registration and setup skipped MCPorter. * fix(setup): keep an unresolved client unknown without blocking others' maintenance A client whose configuration location cannot be resolved (for example a relative MCPORTER_CONFIG) is reported as unknown, never missing or absent. Update maintenance leaves each unresolved client out of its scope and names it with its own recovery, while still maintaining the other clients; uninstall still stops, because it cannot tell whether that client's file holds REA's row. * docs(setup): restore MCPorter's release note and client-table row after rebase * fix(update): keep unknown clients in every failed maintenance plan
This commit is contained in:
1 parent
78fd365bdd
commit
da8f366596
20 files changed
+706
-137
No files matched your search
@@ -161,7 +161,7 @@ Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`,
|
||||
`antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`,
|
||||
`workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`,
|
||||
`zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`,
|
||||
`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`,
|
||||
`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`,
|
||||
or `grok_bot`. If unknown, inspect `doctor --json` before choosing a
|
||||
scope. `grok_bot` uses a chat registration step rather than local `mcp.json`.
|
||||
For unsupported clients, use manual stdio registration with the selected
|
||||
|
||||
+1
-1
@@ -161,7 +161,7 @@ Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`,
|
||||
`antigravity`, `copilot_cli`, `commandcode`, `qwen_code`, `kimi`, `vscode`, `trae`,
|
||||
`workbuddy`, `lm_studio`, `grok_build`, `omp`, `pi`, `hermes`, `qoder`, `droid`,
|
||||
`zcode`, `dsh`, `freebuff`, `cline_vscode`, `cline_vscode_insiders`, `cline_vscodium`,
|
||||
`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`,
|
||||
`cline_cursor`, `cline_windsurf`, `kiro`, `mastracode`, `zed`, `amp`, `mcporter`,
|
||||
or `grok_bot`. If unknown, inspect `doctor --json` before choosing a
|
||||
scope. `grok_bot` uses a chat registration step rather than local `mcp.json`.
|
||||
For unsupported clients, use manual stdio registration with the selected
|
||||
|
||||
@@ -856,6 +856,25 @@ Zed you use and refuses. Zed's comments and formatting are preserved. These
|
||||
locations follow each client's documentation and source; no installed client
|
||||
was run to verify loading.
|
||||
|
||||
## MCPorter
|
||||
|
||||
`rea setup --client mcporter` and `rea mcp add --agent mcporter` write
|
||||
`mcpServers.rea` into MCPorter's home file: the file `MCPORTER_CONFIG` names,
|
||||
otherwise the first existing of `$XDG_CONFIG_HOME/mcporter/mcporter.json[c]`
|
||||
(an absolute `XDG_CONFIG_HOME` only) and `~/.mcporter/mcporter.json[c]`. A new
|
||||
file goes to the XDG path when `XDG_CONFIG_HOME` is set, as
|
||||
`mcporter config add --scope home` does. A relative `MCPORTER_CONFIG` depends on
|
||||
the directory each MCPorter command runs from, so REA refuses writes to
|
||||
MCPorter and doctor and update report its registration as `unknown` while
|
||||
still covering every other client. Uninstall stops until it is repaired,
|
||||
because it cannot tell whether that file holds REA's row.
|
||||
|
||||
MCPorter imports Claude Code, Claude Desktop, Codex, Cursor, Windsurf, OpenCode
|
||||
and VS Code registrations by default, so setup never selects it from detection,
|
||||
and doctor reports it only when its file holds a `rea` row or you select it.
|
||||
Update and uninstall refresh and remove the row REA wrote. A project
|
||||
`config/mcporter.json` entry with the same name overrides the home file.
|
||||
|
||||
## WorkBuddy
|
||||
|
||||
For [WorkBuddy](https://www.workbuddy.cn/docs/workbuddy/From-Beginner-to-Expert-Guide/Function-Description/MCP-Guide), setup writes `mcpServers.rea` into the
|
||||
|
||||
@@ -580,7 +580,9 @@ global directory without its `package.json` is not treated as an owned
|
||||
installation, because Bun would install into the nearest ancestor project
|
||||
instead.
|
||||
Its maintenance plan selects only existing REA registrations and an already
|
||||
installed REA skill. Run the returned scoped setup command to review and approve
|
||||
installed REA skill. A client whose configuration location or registration
|
||||
cannot be resolved is left unmaintained and named with its own recovery; the
|
||||
other clients are still maintained. Run the returned scoped setup command to review and approve
|
||||
those changes, then restart affected agents. The plan is returned in terminal,
|
||||
non-TTY, and JSON modes without applying configuration changes.
|
||||
|
||||
@@ -721,6 +723,7 @@ hosted connector; see [its configuration](client-configuration.md#other-client-s
|
||||
| Mastra Code | `mastracode` |
|
||||
| Zed | `zed` |
|
||||
| Amp | `amp` |
|
||||
| MCPorter | `mcporter` |
|
||||
|
||||
`droid`, `dsh`, `kimi`, `qoder`, `trae`, `workbuddy`, and `zcode` require
|
||||
`rea-agents@6.5.0` or later. The 6.4.0 registry check above does not cover them.
|
||||
@@ -735,7 +738,10 @@ hosted connector; see [its configuration](client-configuration.md#other-client-s
|
||||
and Amp only through `rea mcp add`, and could not register Cline in VS Code
|
||||
Insiders, VSCodium, Cursor or Windsurf at all; doctor, update and uninstall did
|
||||
not see those registrations. Current releases inspect, refresh and remove them
|
||||
like any other setup client.
|
||||
like any other setup client. `mcporter` also requires a release after 6.9.0;
|
||||
setup never selects it from detection, because MCPorter already imports the
|
||||
registrations setup writes for other clients. Select it with
|
||||
`--client mcporter`.
|
||||
|
||||
See [client configuration and troubleshooting](client-configuration.md) for
|
||||
configuration paths, profiles, trust policies, and schema-limit workarounds.
|
||||
@@ -1299,7 +1305,7 @@ status while retaining successful client outcomes and recovery paths.
|
||||
User-level registration for a client that `rea setup` also supports uses that
|
||||
client's setup definition, so the same native read rules apply, and doctor,
|
||||
update and uninstall inspect, refresh and remove what it wrote. Goose, Junie,
|
||||
fx, MCPorter and Kilo Code are registered only by `rea mcp add` until their
|
||||
fx and Kilo Code are registered only by `rea mcp add` until their
|
||||
native layers and path overrides are modeled; doctor, update and uninstall do
|
||||
not yet see those registrations. Gemini CLI
|
||||
registration fails without writing when Gemini's system, defaults or trusted
|
||||
@@ -1311,6 +1317,9 @@ Because `rea mcp add` writes without an approval step, after it changes Claude
|
||||
Desktop's configuration it prints a notice on stderr: a running Claude Desktop
|
||||
can rewrite the file from memory and drop the registration, so quit it fully,
|
||||
rerun `rea mcp add`, then start it again. The JSON report is unchanged.
|
||||
fx registration follows `FX_HOME` and fails without writing when fx would
|
||||
refuse its value or when it contains `.` or `..` segments, which could name the
|
||||
home folder.
|
||||
|
||||
`--no-global` writes only project-level settings. A selection containing Amp or
|
||||
another client without project storage fails before any writes; select those
|
||||
|
||||
@@ -86,7 +86,8 @@ export type ClientRegistrationStatus = ClientRegistrationStatusBase &
|
||||
readonly remediation: string;
|
||||
}
|
||||
| {
|
||||
readonly command: RegistrationCommand;
|
||||
/** Empty when the client's configuration location is unresolved. */
|
||||
readonly command: RegistrationCommand | readonly [];
|
||||
readonly state: "unknown";
|
||||
readonly remediation: string;
|
||||
}
|
||||
@@ -165,13 +166,15 @@ export const readClientRegistrationInspections = async (
|
||||
options.environment,
|
||||
)) {
|
||||
const selected = options.selectedClientIds?.includes(client.name) === true;
|
||||
// An unresolved location leaves this client's registration unknown, never
|
||||
// absent; diagnostics and maintenance still cover every other client.
|
||||
if (client.configPathError !== undefined) {
|
||||
record({
|
||||
client: client.name,
|
||||
config_path: client.configPath,
|
||||
command: [],
|
||||
command_identity: "unknown",
|
||||
state: "invalid",
|
||||
state: "unknown",
|
||||
remediation: client.configPathError,
|
||||
});
|
||||
continue;
|
||||
@@ -230,8 +233,12 @@ export const readClientRegistrationInspections = async (
|
||||
}
|
||||
const { document: parsed, configPath } = configuration.value;
|
||||
selectedConfigPath = configPath;
|
||||
// A client applicable only through REA's registration has none to report.
|
||||
const reportsAbsence =
|
||||
selected || client.registrationApplicability !== true;
|
||||
if (parsed === undefined) {
|
||||
record(unavailableStatus(client, "missing", configPath));
|
||||
if (reportsAbsence)
|
||||
record(unavailableStatus(client, "missing", configPath));
|
||||
continue;
|
||||
}
|
||||
const policy = await readClientPolicyBlock(
|
||||
@@ -274,7 +281,8 @@ export const readClientRegistrationInspections = async (
|
||||
});
|
||||
continue;
|
||||
}
|
||||
record(unavailableStatus(client, "missing", configPath));
|
||||
if (reportsAbsence)
|
||||
record(unavailableStatus(client, "missing", configPath));
|
||||
continue;
|
||||
}
|
||||
const effectiveClient: SetupClient =
|
||||
@@ -671,7 +679,10 @@ const clientEvidencePresent = async (
|
||||
if (evidence.selected) return ok(true);
|
||||
const discoveryPaths = new Set(client.discoveryPaths ?? []);
|
||||
const paths = [
|
||||
...clientEvidencePaths(client),
|
||||
// Only the registration file can hold what REA wrote.
|
||||
...(client.registrationApplicability === true
|
||||
? [client.configPath, ...(client.configPaths ?? [])]
|
||||
: clientEvidencePaths(client)),
|
||||
...(evidence.ownership ? clientOwnershipEvidencePaths(client) : []),
|
||||
];
|
||||
let unavailable:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { chmod, readFile, stat, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
@@ -123,12 +124,11 @@ it("secures fx permissions on owned directory and staged file, including a seman
|
||||
const { path, directory } = await settingsFixture(
|
||||
'{"mcp":{"rea":{"type":"local","command":["/fixture/server path","","a\'b","--mcp"],"enabled":true}}}',
|
||||
);
|
||||
const { chmod } = await import("node:fs/promises");
|
||||
await chmod(directory, 0o755);
|
||||
await chmod(path, 0o644);
|
||||
const client = {
|
||||
...clientFor(path, "fx", "fx"),
|
||||
privateProfile: true,
|
||||
privateProfile: { home: tmpdir() },
|
||||
} as const;
|
||||
const result = await registerMcpClient(
|
||||
client,
|
||||
@@ -260,7 +260,7 @@ it.runIf(process.platform === "win32")(
|
||||
const { path } = await settingsFixture("{}");
|
||||
const client = {
|
||||
...clientFor(path, "fx", "fx"),
|
||||
privateProfile: true,
|
||||
privateProfile: { home: tmpdir() },
|
||||
} as const;
|
||||
const result = await registerMcpClient(
|
||||
client,
|
||||
@@ -331,11 +331,34 @@ it.each([
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"refuses to make the home folder private through a linked profile path",
|
||||
async () => {
|
||||
const { path, directory } = await settingsFixture("{}");
|
||||
await chmod(directory, 0o755);
|
||||
const links = await createTestTempDirectory("rea-private-profile-link-");
|
||||
await symlink(dirname(directory), join(links, "parent"));
|
||||
const linked = join(links, "parent", basename(directory), basename(path));
|
||||
const result = await registerMcpClient(
|
||||
{ ...clientFor(linked, "fx", "fx"), privateProfile: { home: directory } },
|
||||
launcher,
|
||||
undefined,
|
||||
resources,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { message: expect.stringContaining("home folder") },
|
||||
});
|
||||
expect((await stat(directory)).mode & 0o777).toBe(0o755);
|
||||
expect(await readFile(path, "utf8")).toBe("{}");
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the private directory close owner during a semantic no-op", async () => {
|
||||
const { path } = await settingsFixture("{}");
|
||||
const client = {
|
||||
...clientFor(path, "fx", "fx"),
|
||||
privateProfile: true,
|
||||
privateProfile: { home: tmpdir() },
|
||||
} as const;
|
||||
expect(
|
||||
await registerMcpClient(client, launcher, undefined, resources),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, mkdir, open } from "node:fs/promises";
|
||||
import { lstat, mkdir, open, stat } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
@@ -177,12 +177,13 @@ export const registerMcpClient = async (
|
||||
checkCancellation();
|
||||
await mkdir(dirname(path), {
|
||||
recursive: true,
|
||||
...(client.privateProfile === true ? { mode: 0o700 } : {}),
|
||||
...(client.privateProfile !== undefined ? { mode: 0o700 } : {}),
|
||||
});
|
||||
checkCancellation();
|
||||
if (client.privateProfile === true && process.platform !== "win32")
|
||||
if (client.privateProfile !== undefined && process.platform !== "win32")
|
||||
await securePrivateDirectory(
|
||||
dirname(path),
|
||||
client.privateProfile.home,
|
||||
checkCancellation,
|
||||
resources,
|
||||
);
|
||||
@@ -194,7 +195,7 @@ export const registerMcpClient = async (
|
||||
{
|
||||
requestedPath: settingsPath,
|
||||
state: snapshot?.state,
|
||||
...(client.privateProfile === true
|
||||
...(client.privateProfile !== undefined
|
||||
? { requiredMode: 0o600 as const }
|
||||
: {}),
|
||||
},
|
||||
@@ -206,7 +207,7 @@ export const registerMcpClient = async (
|
||||
return ok({
|
||||
status: "configured",
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
...(client.privateProfile === true
|
||||
...(client.privateProfile !== undefined
|
||||
? { permissions: privateProfilePermissions() }
|
||||
: {}),
|
||||
});
|
||||
@@ -274,7 +275,7 @@ const unchangedRegistration = async (
|
||||
if (
|
||||
parsed.requiresRewrite === true ||
|
||||
!clientConfigurationValuesEqual(parsed.document, updated) ||
|
||||
(client.privateProfile === true &&
|
||||
(client.privateProfile !== undefined &&
|
||||
process.platform !== "win32" &&
|
||||
((snapshot?.state.mode ?? 0) & 0o777) !== 0o600)
|
||||
)
|
||||
@@ -291,16 +292,17 @@ const unchangedRegistration = async (
|
||||
checkCancellation();
|
||||
await verifyEffectiveRegistration(prepared, current.text);
|
||||
const permissionsChanged =
|
||||
client.privateProfile === true && process.platform !== "win32"
|
||||
client.privateProfile !== undefined && process.platform !== "win32"
|
||||
? await securePrivateDirectory(
|
||||
dirname(path),
|
||||
client.privateProfile.home,
|
||||
checkCancellation,
|
||||
resources,
|
||||
)
|
||||
: false;
|
||||
return {
|
||||
status: permissionsChanged ? "configured" : "unchanged",
|
||||
...(client.privateProfile === true
|
||||
...(client.privateProfile !== undefined
|
||||
? { permissions: privateProfilePermissions() }
|
||||
: {}),
|
||||
};
|
||||
@@ -353,6 +355,7 @@ const verifyRegistration = async (
|
||||
/** fx's profile permissions are applied through the selected directory descriptor. */
|
||||
const securePrivateDirectory = async (
|
||||
path: string,
|
||||
home: string,
|
||||
checkCancellation: () => void,
|
||||
resources: ArtifactResourceScope,
|
||||
): Promise<boolean> => {
|
||||
@@ -379,6 +382,12 @@ const securePrivateDirectory = async (
|
||||
!named.isDirectory()
|
||||
)
|
||||
throw new RegularFileChangedError(path);
|
||||
// A linked parent can make a profile path name the home folder itself.
|
||||
const homeFolder = await stat(home);
|
||||
if (homeFolder.dev === before.dev && homeFolder.ino === before.ino)
|
||||
throw new ConfigurationError(
|
||||
`The private profile folder ${path} is the home folder; REA will not make the home folder private. Point the client at its own profile folder; no settings were written.`,
|
||||
);
|
||||
changed = (before.mode & 0o777) !== 0o700;
|
||||
checkCancellation();
|
||||
if (changed) await owner.handle.chmod(0o700);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -68,7 +68,7 @@ const clientSchema = z.object({
|
||||
configPaths: z.array(z.string()).optional(),
|
||||
scope: z.enum(["global", "project"]),
|
||||
format: z.string(),
|
||||
privateProfile: z.literal(true).optional(),
|
||||
privateProfile: z.object({ home: z.string() }).optional(),
|
||||
inlineConfiguration: z
|
||||
.object({ origin: z.literal("KILO_CONFIG_CONTENT"), parsed: z.unknown() })
|
||||
.optional(),
|
||||
@@ -358,7 +358,7 @@ it(
|
||||
);
|
||||
expect(
|
||||
result.explicit.value.find((client) => client.id === "fx"),
|
||||
).toMatchObject({ format: "fx", privateProfile: true });
|
||||
).toMatchObject({ format: "fx", privateProfile: { home } });
|
||||
expect(result.detected.ok).toBe(true);
|
||||
if (!result.detected.ok) throw new Error(result.detected.error.message);
|
||||
expect(result.detected.value.map((client) => client.id)).toEqual([
|
||||
@@ -553,3 +553,170 @@ const assertKiloNativeLayers = (
|
||||
error: { tag: "ConfigurationError" },
|
||||
});
|
||||
};
|
||||
|
||||
const resolveWith = async (
|
||||
agent: string,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
prepare: (home: string) => Promise<void> = async () => {},
|
||||
) => {
|
||||
const home = await createTestTempDirectory("rea-mcp-override-");
|
||||
await prepare(home);
|
||||
const resources = new ArtifactResourceScope();
|
||||
try {
|
||||
const result = await resolveMcpRegistrationClients(
|
||||
{
|
||||
agents: agent === "" ? [] : [agent],
|
||||
global: true,
|
||||
cwd: home,
|
||||
home,
|
||||
// Real temporary paths need the host's path rules.
|
||||
platform: process.platform,
|
||||
environment: Object.fromEntries(
|
||||
Object.entries(environment).map(([key, value]) => [
|
||||
key,
|
||||
value?.replace("<home>", home),
|
||||
]),
|
||||
),
|
||||
},
|
||||
resources,
|
||||
);
|
||||
return { home, result };
|
||||
} finally {
|
||||
await resources.close();
|
||||
}
|
||||
};
|
||||
|
||||
it.each([
|
||||
{ name: "default", env: {}, path: ".fx/mcp.json" },
|
||||
{
|
||||
name: "FX_HOME",
|
||||
env: { FX_HOME: "<home>/profile/" },
|
||||
path: "profile/mcp.json",
|
||||
},
|
||||
])(
|
||||
"registers fx in the profile folder fx reads ($name)",
|
||||
async ({ env, path }) => {
|
||||
const { home, result } = await resolveWith("fx", env);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value[0]?.configPath).toBe(join(home, path));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"relative/fx",
|
||||
"/",
|
||||
"<home>",
|
||||
"<home>/",
|
||||
// Aliases of the home folder would give it the profile's private mode.
|
||||
"<home>/.",
|
||||
"<home>/profile/..",
|
||||
])("refuses an FX_HOME of %s that fx itself refuses", async (value) => {
|
||||
const { result } = await resolveWith("fx", { FX_HOME: value });
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { message: expect.stringContaining("FX_HOME") },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "legacy default",
|
||||
env: {},
|
||||
existing: [],
|
||||
path: ".mcporter/mcporter.json",
|
||||
},
|
||||
{
|
||||
name: "absolute XDG default",
|
||||
env: { XDG_CONFIG_HOME: "<home>/xdg" },
|
||||
existing: [],
|
||||
path: "xdg/mcporter/mcporter.json",
|
||||
},
|
||||
{
|
||||
name: "existing legacy file under XDG",
|
||||
env: { XDG_CONFIG_HOME: "<home>/xdg" },
|
||||
existing: [".mcporter/mcporter.jsonc"],
|
||||
path: ".mcporter/mcporter.jsonc",
|
||||
},
|
||||
{
|
||||
name: "XDG file before legacy file",
|
||||
env: { XDG_CONFIG_HOME: "<home>/xdg" },
|
||||
existing: [".mcporter/mcporter.json", "xdg/mcporter/mcporter.jsonc"],
|
||||
path: "xdg/mcporter/mcporter.jsonc",
|
||||
},
|
||||
{
|
||||
name: "relative XDG ignored",
|
||||
env: { XDG_CONFIG_HOME: "xdg" },
|
||||
existing: [],
|
||||
path: ".mcporter/mcporter.json",
|
||||
},
|
||||
{
|
||||
name: "MCPORTER_CONFIG exclusive",
|
||||
env: { MCPORTER_CONFIG: " ~/selected.json " },
|
||||
existing: [".mcporter/mcporter.json"],
|
||||
path: "selected.json",
|
||||
},
|
||||
{
|
||||
name: "MCPORTER_CONFIG resolved lexically like path.resolve",
|
||||
env: { MCPORTER_CONFIG: "<home>/missing/../selected.json" },
|
||||
existing: [],
|
||||
path: "selected.json",
|
||||
},
|
||||
])(
|
||||
"registers MCPorter in the home file it loads ($name)",
|
||||
async ({ env, existing, path }) => {
|
||||
const { home, result } = await resolveWith(
|
||||
"mcporter",
|
||||
env,
|
||||
async (root) => {
|
||||
for (const file of existing) {
|
||||
await mkdir(join(root, file, ".."), { recursive: true });
|
||||
await writeFile(join(root, file), "{}\n");
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value[0]?.configPath).toBe(join(home, path));
|
||||
},
|
||||
);
|
||||
|
||||
it("detects MCPorter from the file MCPORTER_CONFIG selects in default registration", async () => {
|
||||
const { home, result } = await resolveWith(
|
||||
"",
|
||||
{ MCPORTER_CONFIG: "<home>/elsewhere/mcporter.json" },
|
||||
async (root) => {
|
||||
await mkdir(join(root, ".cursor"), { recursive: true });
|
||||
await mkdir(join(root, "elsewhere"), { recursive: true });
|
||||
await writeFile(join(root, "elsewhere", "mcporter.json"), "{}\n");
|
||||
},
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
result.value.find((client) => client.id === "mcporter")?.configPath,
|
||||
).toBe(join(home, "elsewhere", "mcporter.json"));
|
||||
});
|
||||
|
||||
it("detects MCPorter from an existing legacy file when XDG_CONFIG_HOME is absolute", async () => {
|
||||
const { home, result } = await resolveWith(
|
||||
"",
|
||||
{ XDG_CONFIG_HOME: "<home>/xdg" },
|
||||
async (root) => {
|
||||
await mkdir(join(root, ".cursor"), { recursive: true });
|
||||
await mkdir(join(root, ".mcporter"), { recursive: true });
|
||||
await writeFile(join(root, ".mcporter", "mcporter.json"), "{}\n");
|
||||
},
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
result.value.find((client) => client.id === "mcporter")?.configPath,
|
||||
).toBe(join(home, ".mcporter", "mcporter.json"));
|
||||
});
|
||||
|
||||
it("refuses a relative MCPORTER_CONFIG whose file depends on each command's directory", async () => {
|
||||
const { result } = await resolveWith("mcporter", {
|
||||
MCPORTER_CONFIG: "config/selected.json",
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { message: expect.stringContaining("MCPORTER_CONFIG is relative") },
|
||||
});
|
||||
});
|
||||
@@ -37,7 +37,6 @@ import {
|
||||
fxLocation,
|
||||
gooseLocation,
|
||||
junieLocation,
|
||||
mcporterLocation,
|
||||
type McpRegistrationLocationContext,
|
||||
type McpRegistrationGlobalLocation,
|
||||
type McpRegistrationLocation,
|
||||
@@ -91,39 +90,6 @@ interface ClientDescriptor {
|
||||
readonly setupName?: SupportedClientName;
|
||||
}
|
||||
|
||||
/** mcporter getUrl's native nullish priority; an empty first value suppresses later aliases. */
|
||||
const MCPORTER_URL_FIELDS = [
|
||||
"baseUrl",
|
||||
"base_url",
|
||||
"url",
|
||||
"serverUrl",
|
||||
"server_url",
|
||||
] as const;
|
||||
const MCPORTER_STDIO_INCOMPATIBILITIES: readonly NativeStdioIncompatibility[] =
|
||||
[
|
||||
// RawEntrySchema admits only optional strings, including an empty string.
|
||||
...MCPORTER_URL_FIELDS.map((field): NativeStdioIncompatibility => ({
|
||||
kind: "invalid-string",
|
||||
field,
|
||||
})),
|
||||
...MCPORTER_URL_FIELDS.map((field, index): NativeStdioIncompatibility =>
|
||||
index === 0
|
||||
? { kind: "truthy", field }
|
||||
: {
|
||||
kind: "all",
|
||||
conditions: [
|
||||
...MCPORTER_URL_FIELDS.slice(0, index).map(
|
||||
(prior): NativeStdioIncompatibility => ({
|
||||
kind: "nullish",
|
||||
field: prior,
|
||||
}),
|
||||
),
|
||||
{ kind: "truthy", field },
|
||||
],
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
/**
|
||||
* Reviewed add-mcp 2.6.1 agent ids plus Incur's separate Amp contract, in
|
||||
* add-mcp's order. Table-backed agents carry only their row name; the row owns
|
||||
@@ -201,18 +167,7 @@ export const MCP_REGISTRATION_CLIENTS = {
|
||||
"kimi-code": tableClient("kimi"),
|
||||
"kiro-cli": tableClient("kiro"),
|
||||
mastracode: tableClient("mastracode"),
|
||||
mcporter: {
|
||||
kind: "registration-only",
|
||||
displayName: "MCPorter",
|
||||
format: "json",
|
||||
globalLocation: mcporterLocation,
|
||||
projectLocation: fixedProjectLocation(["config/mcporter.json"]),
|
||||
registrationConnection: {
|
||||
kind: "flat",
|
||||
fields: [...MCPORTER_URL_FIELDS, "executable"],
|
||||
stdio: MCPORTER_STDIO_INCOMPATIBILITIES,
|
||||
},
|
||||
},
|
||||
mcporter: tableClient("mcporter"),
|
||||
opencode: tableClient("opencode"),
|
||||
pi: tableClient("pi"),
|
||||
vscode: tableClient("vscode"),
|
||||
@@ -281,7 +236,11 @@ export interface McpRegistrationClient {
|
||||
readonly inlineConfiguration?: McpRegistrationInlineConfiguration;
|
||||
readonly scope: "global" | "project";
|
||||
readonly format: ClientConfigurationFormat;
|
||||
readonly privateProfile?: true;
|
||||
/**
|
||||
* fx keeps a profile only its owner may read. `home` is the caller's home
|
||||
* folder, which the private folder mode must never reach through a link.
|
||||
*/
|
||||
readonly privateProfile?: { readonly home: string };
|
||||
/**
|
||||
* The table row resolved for this user-scope registration. Its read-scope
|
||||
* facts (Gemini settings policy, MSIX package storage) govern the write.
|
||||
@@ -373,7 +332,7 @@ const globalTarget = async (
|
||||
...(resolved.inlineConfiguration === undefined
|
||||
? {}
|
||||
: { inlineConfiguration: resolved.inlineConfiguration }),
|
||||
...(id === "fx" ? { privateProfile: true } : {}),
|
||||
...(id === "fx" ? { privateProfile: { home: context.home } } : {}),
|
||||
...(setupClient === undefined ? {} : { setupClient }),
|
||||
},
|
||||
markers: resolved.markers.map((marker) => selectedPath(marker, context)),
|
||||
|
||||
@@ -156,18 +156,33 @@ export const fixedProjectLocation =
|
||||
),
|
||||
};
|
||||
};
|
||||
export const mcporterLocation = async (
|
||||
context: McpRegistrationLocationContext,
|
||||
): Promise<McpRegistrationGlobalLocation> => {
|
||||
const root = join(context.home, ".mcporter");
|
||||
const primary = join(root, "mcporter.json");
|
||||
return location(
|
||||
await firstExisting([primary, join(root, "mcporter.jsonc")], primary),
|
||||
root,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* fx's profile folder: `$FX_HOME` when set, which fx admits only as an
|
||||
* absolute path other than the root and the home folder (`useFxHome`), else
|
||||
* `~/.fx`. fx refuses an invalid value, so registration does too.
|
||||
*/
|
||||
export const fxLocation = async (
|
||||
context: McpRegistrationLocationContext,
|
||||
): Promise<McpRegistrationGlobalLocation> =>
|
||||
location(join(context.home, ".fx", "mcp.json"));
|
||||
): Promise<McpRegistrationGlobalLocation> => {
|
||||
const value = context.environment.FX_HOME;
|
||||
if (!value) return location(join(context.home, ".fx", "mcp.json"));
|
||||
const pathApi = context.platform === "win32" ? win32 : posix;
|
||||
const trimmed = value.replace(/\/+$/u, "");
|
||||
// fx opens FX_HOME as written, so `.` and `..` resolve through links on the
|
||||
// filesystem. Refusing them keeps REA's file and its root/home check on the
|
||||
// folder fx opens, so the private profile mode can never land on home.
|
||||
const dotSegment = trimmed
|
||||
.split(/[\\/]/u)
|
||||
.some((segment) => segment === "." || segment === "..");
|
||||
if (
|
||||
!pathApi.isAbsolute(value) ||
|
||||
trimmed.length === 0 ||
|
||||
dotSegment ||
|
||||
pathApi.parse(trimmed).root === trimmed ||
|
||||
trimmed === context.home.replace(/[\\/]+$/u, "")
|
||||
)
|
||||
throw new ConfigurationError(
|
||||
"FX_HOME must be an absolute path without . or .. segments, other than the root and home folders. Repair FX_HOME before registering; no settings were written.",
|
||||
);
|
||||
return location(pathApi.join(trimmed, "mcp.json"));
|
||||
};
|
||||
@@ -471,7 +471,11 @@ export const detectClients = async (
|
||||
): Promise<readonly SetupClient[]> => {
|
||||
const detected: SetupClient[] = [];
|
||||
for (const candidate of supportedClients(home, platform, environment)) {
|
||||
if (candidate.configPathError !== undefined) continue;
|
||||
if (
|
||||
candidate.configPathError !== undefined ||
|
||||
candidate.registrationApplicability === true
|
||||
)
|
||||
continue;
|
||||
if (await clientEvidencePresent(candidate)) detected.push(candidate);
|
||||
}
|
||||
return detected;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
ClientRegistrationConnectionProfile,
|
||||
ClientRegistrationProfile,
|
||||
NativeStdioIncompatibility,
|
||||
} from "./ClientRegistrationProfile.js";
|
||||
import type { ClientConfigurationFormat } from "./ClientConfigurationDocument.js";
|
||||
import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
|
||||
@@ -53,6 +54,11 @@ export interface SetupClient {
|
||||
* ownership of a registration REA wrote.
|
||||
*/
|
||||
readonly sharedRegistration?: boolean;
|
||||
/**
|
||||
* Only a registration REA wrote makes this client applicable: setup never
|
||||
* detects it, and doctor reports it only when its file holds a `rea` row.
|
||||
*/
|
||||
readonly registrationApplicability?: true;
|
||||
/** MSIX package storage that decides which configuration the client reads. */
|
||||
readonly msixPackage?: MsixPackageView;
|
||||
/** A running client can rewrite its configuration from memory. */
|
||||
@@ -142,6 +148,7 @@ interface ClientDefinitionBase {
|
||||
readonly mcpAdd?: McpAddExposure;
|
||||
readonly discoveryPaths?: (context: ClientPathContext) => readonly string[];
|
||||
readonly sharedRegistration?: true;
|
||||
readonly registrationApplicability?: true;
|
||||
readonly format: NonNullable<SetupClient["format"]>;
|
||||
readonly quitBeforeSetup?: boolean;
|
||||
readonly zcodeFallbackPath?: (context: ClientPathContext) => string;
|
||||
@@ -649,6 +656,117 @@ const zedLocation = ({
|
||||
});
|
||||
};
|
||||
|
||||
/** MCPorter's expandHome: a leading `~` path segment names the home folder. */
|
||||
const mcporterExpandHome = (value: string, home: string): string =>
|
||||
value === "~"
|
||||
? home
|
||||
: value.startsWith("~/") || value.startsWith("~\\")
|
||||
? join(home, value.slice(2))
|
||||
: value;
|
||||
|
||||
const regularPathPresent = (
|
||||
path: string,
|
||||
): Result<boolean, ClientPathFailure> => {
|
||||
try {
|
||||
lstatSync(path);
|
||||
return ok(true);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return ok(false);
|
||||
return err({
|
||||
path,
|
||||
message: `Cannot determine whether ${path} exists: ${cause instanceof Error ? cause.message : String(cause)}. Repair its access before configuring MCPorter.`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* MCPorter's home layer (`listConfigLayerPaths`): a non-empty
|
||||
* `MCPORTER_CONFIG` is the only file it loads; otherwise the first existing of
|
||||
* the XDG and legacy `~/.mcporter` candidates (`mcporterConfigCandidates`),
|
||||
* where only an absolute `XDG_CONFIG_HOME` counts. A new file goes where
|
||||
* `mcporter config add --scope home` puts it. A relative `MCPORTER_CONFIG`
|
||||
* follows each invocation's directory, which REA cannot know.
|
||||
*/
|
||||
const mcporterLocation = ({
|
||||
home,
|
||||
platform,
|
||||
env,
|
||||
}: ClientPathContext): Result<ClientLocation, ClientPathFailure> => {
|
||||
const pathApi = platform === "win32" ? win32 : posix;
|
||||
const legacy = join(home, ".mcporter");
|
||||
const selected = env.MCPORTER_CONFIG?.trim();
|
||||
if (selected) {
|
||||
const path = mcporterExpandHome(selected, home);
|
||||
// MCPorter applies path.resolve: `..` collapses lexically, not through
|
||||
// links. The selected file is also the evidence that MCPorter is in use.
|
||||
return pathApi.isAbsolute(path)
|
||||
? ok({
|
||||
configPath: pathApi.resolve(path),
|
||||
markerPath: pathApi.resolve(path),
|
||||
})
|
||||
: err({
|
||||
path,
|
||||
message:
|
||||
"MCPORTER_CONFIG is relative, so the file MCPorter loads depends on the directory each command runs from. Set an absolute MCPORTER_CONFIG before configuring MCPorter.",
|
||||
});
|
||||
}
|
||||
const configHome = mcporterExpandHome(
|
||||
env.XDG_CONFIG_HOME?.trim() ?? "",
|
||||
home,
|
||||
);
|
||||
const base = pathApi.isAbsolute(configHome)
|
||||
? join(configHome, "mcporter")
|
||||
: legacy;
|
||||
const candidates = [base, ...(base === legacy ? [] : [legacy])].flatMap(
|
||||
(directory) => [
|
||||
join(directory, "mcporter.json"),
|
||||
join(directory, "mcporter.jsonc"),
|
||||
],
|
||||
);
|
||||
for (const candidate of candidates) {
|
||||
const present = regularPathPresent(candidate);
|
||||
if (!present.ok) return present;
|
||||
// The loaded file's folder is the evidence, even when it is the legacy one.
|
||||
if (present.value)
|
||||
return ok({ configPath: candidate, markerPath: dirname(candidate) });
|
||||
}
|
||||
return ok({ configPath: join(base, "mcporter.json"), markerPath: base });
|
||||
};
|
||||
|
||||
/** mcporter getUrl's native nullish priority; an empty first value suppresses later aliases. */
|
||||
const MCPORTER_URL_FIELDS = [
|
||||
"baseUrl",
|
||||
"base_url",
|
||||
"url",
|
||||
"serverUrl",
|
||||
"server_url",
|
||||
] as const;
|
||||
const MCPORTER_STDIO_INCOMPATIBILITIES: readonly NativeStdioIncompatibility[] =
|
||||
[
|
||||
// RawEntrySchema admits only optional strings, including an empty string.
|
||||
...MCPORTER_URL_FIELDS.map((field): NativeStdioIncompatibility => ({
|
||||
kind: "invalid-string",
|
||||
field,
|
||||
})),
|
||||
...MCPORTER_URL_FIELDS.map((field, index): NativeStdioIncompatibility =>
|
||||
index === 0
|
||||
? { kind: "truthy", field }
|
||||
: {
|
||||
kind: "all",
|
||||
conditions: [
|
||||
...MCPORTER_URL_FIELDS.slice(0, index).map(
|
||||
(prior): NativeStdioIncompatibility => ({
|
||||
kind: "nullish",
|
||||
field: prior,
|
||||
}),
|
||||
),
|
||||
{ kind: "truthy", field },
|
||||
],
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
/**
|
||||
* Amp's user settings: `settings.json` or `settings.jsonc` in
|
||||
* `~/.config/amp` on every platform. Amp does not document which one wins
|
||||
@@ -1322,6 +1440,21 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
location: ampLocation,
|
||||
format: "amp",
|
||||
}),
|
||||
defineClient({
|
||||
name: "mcporter",
|
||||
mcpAdd: { projectPaths: ["config/mcporter.json"] },
|
||||
registrationConnection: {
|
||||
kind: "flat",
|
||||
fields: [...MCPORTER_URL_FIELDS, "executable"],
|
||||
stdio: MCPORTER_STDIO_INCOMPATIBILITIES,
|
||||
},
|
||||
displayName: "MCPorter",
|
||||
location: mcporterLocation,
|
||||
// MCPorter imports setup-managed clients' registrations by default, so a
|
||||
// registration of its own is opt-in.
|
||||
registrationApplicability: true,
|
||||
format: "json",
|
||||
}),
|
||||
defineClient({
|
||||
name: "grok_bot",
|
||||
registrationConnection: {
|
||||
@@ -1493,6 +1626,9 @@ export const supportedClients = (
|
||||
...(definition.discoveryPaths === undefined
|
||||
? {}
|
||||
: { discoveryPaths: definition.discoveryPaths(context) }),
|
||||
...(definition.registrationApplicability === true
|
||||
? { registrationApplicability: true }
|
||||
: {}),
|
||||
...(definition.sharedRegistration === true
|
||||
? { sharedRegistration: true }
|
||||
: {}),
|
||||
|
||||
@@ -227,6 +227,31 @@ describe("REA update", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("update maintenance notices", () => {
|
||||
it("names a client left unmaintained because its registration is unknown", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.maintenance = {
|
||||
status: "current",
|
||||
plannedActions: [],
|
||||
unresolved: [
|
||||
{
|
||||
client: "mcporter",
|
||||
config_path: "config/mcporter.json",
|
||||
command: [],
|
||||
command_identity: "unknown",
|
||||
state: "unknown",
|
||||
remediation: "Set an absolute MCPORTER_CONFIG.",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = await runUpdate("3.2.1", host);
|
||||
expect(result).toMatchObject({ status: "updated" });
|
||||
expect(result.status === "updated" && result.remediation).toBe(
|
||||
"REA is updated. Restart agents running this installation to load the new version. REA did not maintain one client whose registration is unknown: mcporter (config/mcporter.json): Set an absolute MCPORTER_CONFIG.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("update failures and version boundaries", () => {
|
||||
it("normalizes accepted release metadata before installing and comparing versions", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
|
||||
@@ -2,7 +2,11 @@ import { gt, valid } from "semver";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { IntegrationMaintenance } from "./UpdateMaintenance.js";
|
||||
import {
|
||||
unresolvedMaintenanceClients,
|
||||
unresolvedMaintenanceRemediation,
|
||||
type IntegrationMaintenance,
|
||||
} from "./UpdateMaintenance.js";
|
||||
|
||||
/** Global npm installation that owns the running package and its entry point. */
|
||||
export interface NpmInstallation {
|
||||
@@ -236,6 +240,11 @@ const runUpdateWorkflow = async (
|
||||
remediation: `${installation.manager} completed, but REA could not verify ${targetVersion} in ${installation.packageRoot}: ${verified.ok ? `the executable reported ${verified.value}` : verified.error}. The installation may have changed; repair it before retrying.`,
|
||||
};
|
||||
const maintenance = await host.planMaintenance(installation);
|
||||
const unresolved = unresolvedMaintenanceClients(maintenance);
|
||||
const unresolvedNotice =
|
||||
maintenance.status === "unavailable" || unresolved.length === 0
|
||||
? ""
|
||||
: ` ${unresolvedMaintenanceRemediation(unresolved)}`;
|
||||
return {
|
||||
status: "updated",
|
||||
previousVersion: currentVersion,
|
||||
@@ -244,11 +253,12 @@ const runUpdateWorkflow = async (
|
||||
installMethod: installation.manager,
|
||||
command: updateInstallCommand(installation, targetVersion),
|
||||
maintenance,
|
||||
remediation:
|
||||
remediation: `${
|
||||
maintenance.status === "planned"
|
||||
? "REA is updated. Run the maintenance command to review and approve changes to existing REA integrations, then restart affected agents."
|
||||
: maintenance.status === "unavailable"
|
||||
? "REA is updated. Integration maintenance could not be planned; inspect the maintenance diagnostic before changing configuration."
|
||||
: "REA is updated. Restart agents running this installation to load the new version.",
|
||||
: "REA is updated. Restart agents running this installation to load the new version."
|
||||
}${unresolvedNotice}`,
|
||||
};
|
||||
};
|
||||
@@ -27,7 +27,12 @@ export interface MaintenanceScope {
|
||||
|
||||
/** Unapplied maintenance evidence produced by the updated setup executable. */
|
||||
export type IntegrationMaintenance =
|
||||
| { readonly status: "current"; readonly plannedActions: readonly [] }
|
||||
| {
|
||||
readonly status: "current";
|
||||
readonly plannedActions: readonly [];
|
||||
/** Clients left unmaintained because their registration is unknown. */
|
||||
readonly unresolved?: readonly ClientRegistrationStatus[];
|
||||
}
|
||||
| {
|
||||
readonly status: "planned";
|
||||
readonly scope: MaintenanceScope;
|
||||
@@ -57,6 +62,43 @@ const setupPlanSchema = z.object({
|
||||
),
|
||||
});
|
||||
|
||||
const unresolvedRegistrationDetail = ({
|
||||
client,
|
||||
config_path,
|
||||
remediation,
|
||||
}: ClientRegistrationStatus): string =>
|
||||
`${client} (${config_path}): ${remediation ?? "Registration identity is unresolved"}`;
|
||||
|
||||
/** Clients a maintenance result left alone because their registration is unknown. */
|
||||
export const unresolvedMaintenanceClients = (
|
||||
maintenance: IntegrationMaintenance,
|
||||
): readonly ClientRegistrationStatus[] =>
|
||||
(maintenance.status === "current"
|
||||
? maintenance.unresolved
|
||||
: maintenance.scope?.unresolved) ?? [];
|
||||
|
||||
/** One sentence naming each unknown client and its own recovery. */
|
||||
export const unresolvedMaintenanceRemediation = (
|
||||
unresolved: readonly ClientRegistrationStatus[],
|
||||
): string =>
|
||||
`REA did not maintain ${unresolved.length === 1 ? "one client" : `${String(unresolved.length)} clients`} whose registration is unknown: ${unresolved.map(unresolvedRegistrationDetail).join(" ")}`;
|
||||
|
||||
/** A maintenance failure that still reports the unknown clients it found. */
|
||||
const unavailableMaintenance = (
|
||||
remediation: string,
|
||||
scope: MaintenanceScope | undefined,
|
||||
): IntegrationMaintenance => {
|
||||
const unresolved = scope?.unresolved ?? [];
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation:
|
||||
unresolved.length === 0
|
||||
? remediation
|
||||
: `${remediation} ${unresolvedMaintenanceRemediation(unresolved)}`,
|
||||
...(scope === undefined ? {} : { scope }),
|
||||
};
|
||||
};
|
||||
|
||||
/** Discover owned registrations and REA skills without writes. */
|
||||
export const existingMaintenanceScope = async (
|
||||
home: string,
|
||||
@@ -122,34 +164,36 @@ export const planIntegrationMaintenance = async (
|
||||
execute: (command: readonly string[]) => Promise<Result<string, string>>,
|
||||
resources?: ArtifactResourceScope,
|
||||
): Promise<IntegrationMaintenance> => {
|
||||
let scope: MaintenanceScope | undefined;
|
||||
try {
|
||||
const scope = await existingMaintenanceScope(
|
||||
scope = await existingMaintenanceScope(
|
||||
home,
|
||||
entryPoint,
|
||||
environment,
|
||||
resources,
|
||||
);
|
||||
if (
|
||||
(scope.unresolved?.length ?? 0) > 0 ||
|
||||
(scope.skillIssues?.length ?? 0) > 0
|
||||
)
|
||||
return {
|
||||
status: "unavailable",
|
||||
scope,
|
||||
remediation: `Integration maintenance is unresolved: ${[
|
||||
...(scope.unresolved ?? []).map(
|
||||
({ client, config_path, remediation }) =>
|
||||
`${client} (${config_path}): ${remediation ?? "Registration identity is unresolved"}`,
|
||||
),
|
||||
...(scope.skillIssues ?? []).map(
|
||||
// An unresolved client fails closed on its own: it stays out of the
|
||||
// maintained clients and is reported, while every resolved client is
|
||||
// still maintained. Skill destinations are one shared selection.
|
||||
if ((scope.skillIssues?.length ?? 0) > 0)
|
||||
return unavailableMaintenance(
|
||||
`Integration maintenance is unresolved: ${(scope.skillIssues ?? [])
|
||||
.map(
|
||||
({ client, path, detail }) =>
|
||||
`${client ?? "skill"} (${path}): ${detail}`,
|
||||
),
|
||||
].join(" ")}`,
|
||||
};
|
||||
)
|
||||
.join(" ")}`,
|
||||
scope,
|
||||
);
|
||||
const current: IntegrationMaintenance = {
|
||||
status: "current",
|
||||
plannedActions: [],
|
||||
...(scope.unresolved === undefined
|
||||
? {}
|
||||
: { unresolved: scope.unresolved }),
|
||||
};
|
||||
const skillDestinations = scope.skillDestinations ?? [];
|
||||
if (scope.clients.length === 0 && !scope.skill)
|
||||
return { status: "current", plannedActions: [] };
|
||||
if (scope.clients.length === 0 && !scope.skill) return current;
|
||||
const command = [
|
||||
process.execPath,
|
||||
entryPoint,
|
||||
@@ -159,16 +203,14 @@ export const planIntegrationMaintenance = async (
|
||||
`--skill=${String(scope.skill)}`,
|
||||
];
|
||||
const execution = await execute([...command, "--dry-run", "--json"]);
|
||||
if (!execution.ok)
|
||||
return { status: "unavailable", remediation: execution.error };
|
||||
if (!execution.ok) return unavailableMaintenance(execution.error, scope);
|
||||
const plan = setupPlanSchema.safeParse(JSON.parse(execution.value));
|
||||
if (!plan.success)
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation: `The updated setup executable returned an invalid maintenance plan: ${plan.error.message}`,
|
||||
};
|
||||
if (plan.data.plannedActions.length === 0)
|
||||
return { status: "current", plannedActions: [] };
|
||||
return unavailableMaintenance(
|
||||
`The updated setup executable returned an invalid maintenance plan: ${plan.error.message}`,
|
||||
scope,
|
||||
);
|
||||
if (plan.data.plannedActions.length === 0) return current;
|
||||
const allowedIds = new Set(
|
||||
scope.clients.map((client) => `configure_client:${client}`),
|
||||
);
|
||||
@@ -180,11 +222,10 @@ export const planIntegrationMaintenance = async (
|
||||
: !allowedIds.has(action.id),
|
||||
)
|
||||
)
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation:
|
||||
"The updated setup plan included an integration outside the existing REA maintenance scope.",
|
||||
};
|
||||
return unavailableMaintenance(
|
||||
"The updated setup plan included an integration outside the existing REA maintenance scope.",
|
||||
scope,
|
||||
);
|
||||
return {
|
||||
status: "planned",
|
||||
scope,
|
||||
@@ -201,9 +242,9 @@ export const planIntegrationMaintenance = async (
|
||||
// Without a supplied scope, the typed failure is the caller's cleanup capability.
|
||||
if (resources === undefined && cause instanceof RegularFileCleanupFailure)
|
||||
throw cause;
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation: cause instanceof Error ? cause.message : String(cause),
|
||||
};
|
||||
return unavailableMaintenance(
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
scope,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -228,7 +228,7 @@ describe("Windows Claude Desktop configuration location", () => {
|
||||
environment: env,
|
||||
})
|
||||
).find(({ client: name }) => name === "claude_desktop");
|
||||
expect(status).toMatchObject({ state: "invalid", config_path: foreign });
|
||||
expect(status).toMatchObject({ state: "unknown", config_path: foreign });
|
||||
await expect(
|
||||
inspectClientConfiguration(client, {}, command),
|
||||
).resolves.toMatchObject({ status: "invalid" });
|
||||
|
||||
@@ -872,6 +872,28 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an unresolved client location as unknown and still inspects other clients", async () => {
|
||||
const home = await createTestTempDirectory("rea-registration-unknown-path-");
|
||||
await writeFile(
|
||||
join(home, ".claude.json"),
|
||||
JSON.stringify({ mcpServers: { rea: { command: "/old/rea", args: [] } } }),
|
||||
);
|
||||
const statuses = await readClientRegistrationStatuses(home, "/current/rea", {
|
||||
environment: { MCPORTER_CONFIG: "config/mcporter.json" },
|
||||
});
|
||||
expect(statuses.find(({ client }) => client === "mcporter")).toEqual({
|
||||
client: "mcporter",
|
||||
config_path: "config/mcporter.json",
|
||||
command: [],
|
||||
command_identity: "unknown",
|
||||
state: "unknown",
|
||||
remediation: expect.stringContaining("MCPORTER_CONFIG is relative"),
|
||||
});
|
||||
expect(statuses.find(({ client }) => client === "claude_code")).toMatchObject(
|
||||
{ state: "stale" },
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a dangling configuration entry as missing without losing the detected client", async () => {
|
||||
const home = await createTestTempDirectory(
|
||||
"rea-registration-dangling-config-",
|
||||
|
||||
@@ -36,6 +36,7 @@ it.each([
|
||||
{ agent: "mastracode", client: "mastracode" },
|
||||
{ agent: "zed", client: "zed" },
|
||||
{ agent: "amp", client: "amp" },
|
||||
{ agent: "mcporter", client: "mcporter" },
|
||||
])(
|
||||
"inspects, refreshes and removes the $agent registration that mcp add wrote as $client",
|
||||
async ({ agent, client }) => {
|
||||
@@ -267,3 +268,56 @@ it("selects the Zed configuration a Linux Flatpak Zed reads", async () => {
|
||||
zed({ FLATPAK_XDG_CONFIG_HOME: "relative" })?.configPathError,
|
||||
).toContain("FLATPAK_XDG_CONFIG_HOME is relative");
|
||||
});
|
||||
|
||||
it("keeps MCPorter out of setup detection and doctor until REA registers it", async () => {
|
||||
const home = await createTestTempDirectory("rea-mcporter-applicability-");
|
||||
const environment = {};
|
||||
const row = supportedClients(home, platform, environment).find(
|
||||
({ name }) => name === "mcporter",
|
||||
);
|
||||
if (row === undefined) throw new Error("mcporter has no table row");
|
||||
await mkdir(join(home, ".mcporter"), { recursive: true });
|
||||
await writeFile(
|
||||
row.configPath,
|
||||
`${JSON.stringify({ mcpServers: { peer: { command: "peer" } } })}\n`,
|
||||
);
|
||||
expect(
|
||||
(await detectClients(home, platform, environment)).map(({ name }) => name),
|
||||
).not.toContain("mcporter");
|
||||
const statuses = await readClientRegistrationStatuses(home, command[1], {
|
||||
platform,
|
||||
environment,
|
||||
});
|
||||
expect(statuses.map(({ client }) => client)).not.toContain("mcporter");
|
||||
// An explicit selection still reports the missing registration.
|
||||
const selected = await readClientRegistrationStatuses(home, command[1], {
|
||||
platform,
|
||||
environment,
|
||||
selectedClientIds: ["mcporter"],
|
||||
});
|
||||
expect(selected.find(({ client }) => client === "mcporter")).toMatchObject({
|
||||
state: "missing",
|
||||
});
|
||||
});
|
||||
|
||||
it("stops uninstall with MCPorter's recovery while its location is unknown", async () => {
|
||||
const home = await createTestTempDirectory("rea-mcporter-unknown-uninstall-");
|
||||
const environment = { MCPORTER_CONFIG: "config/mcporter.json" };
|
||||
const claude = join(home, ".claude.json");
|
||||
const original = `${JSON.stringify({ mcpServers: { rea: { command: command[0], args: command.slice(1) } } })}\n`;
|
||||
await writeFile(claude, original);
|
||||
const uninstall = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, undefined, environment, platform),
|
||||
);
|
||||
// REA cannot tell whether MCPorter's file holds its row, so nothing is
|
||||
// removed and the result names MCPorter's own recovery.
|
||||
expect(uninstall.items).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "mcporter",
|
||||
status: "failed",
|
||||
detail: expect.stringContaining("MCPORTER_CONFIG is relative"),
|
||||
}),
|
||||
);
|
||||
expect(await readFile(claude, "utf8")).toBe(original);
|
||||
});
|
||||
@@ -790,7 +790,7 @@ it("keeps setup and registration diagnostics blocked for an unrecognized Claude
|
||||
})
|
||||
).find((status) => status.client === "claude_desktop"),
|
||||
).toMatchObject({
|
||||
state: "invalid",
|
||||
state: "unknown",
|
||||
command: [],
|
||||
remediation: expect.stringContaining("does not fall back"),
|
||||
});
|
||||
|
||||
@@ -140,16 +140,33 @@ describe("maintenance activation and layered configuration", () => {
|
||||
}),
|
||||
);
|
||||
const before = await readFile(cursor, "utf8");
|
||||
const commands: (readonly string[])[] = [];
|
||||
const result = await planIntegrationMaintenance(
|
||||
home,
|
||||
entryPoint,
|
||||
process.env,
|
||||
() => {
|
||||
throw new Error("An unresolved maintenance scope must not be executed");
|
||||
async (command) => {
|
||||
commands.push(command);
|
||||
return ok(
|
||||
JSON.stringify({
|
||||
status: "planned",
|
||||
// An action for the unresolved client is outside the scope.
|
||||
plannedActions: [{ ...action, id: "configure_client:cursor" }],
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
status: "unavailable",
|
||||
expect(result).toMatchObject({ status: "unavailable" });
|
||||
expect(commands[0]).not.toContain("cursor");
|
||||
const planned = await planIntegrationMaintenance(
|
||||
home,
|
||||
entryPoint,
|
||||
process.env,
|
||||
async () =>
|
||||
ok(JSON.stringify({ status: "planned", plannedActions: [action] })),
|
||||
);
|
||||
expect(planned).toMatchObject({
|
||||
status: "planned",
|
||||
scope: {
|
||||
clients: ["codex"],
|
||||
unresolved: [
|
||||
@@ -160,7 +177,6 @@ describe("maintenance activation and layered configuration", () => {
|
||||
}),
|
||||
],
|
||||
},
|
||||
remediation: expect.stringContaining("cursor"),
|
||||
});
|
||||
expect(await readFile(cursor, "utf8")).toBe(before);
|
||||
});
|
||||
@@ -239,6 +255,54 @@ describe("maintenance activation and layered configuration", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown client locations in maintenance", () => {
|
||||
it("maintains other clients while an unresolved MCPorter location stays unknown", async () => {
|
||||
vi.stubEnv("MCPORTER_CONFIG", "config/mcporter.json");
|
||||
await writeClient("codex", staleCodex);
|
||||
const scope = await existingMaintenanceScope(home, entryPoint, process.env);
|
||||
expect(scope).toMatchObject({
|
||||
clients: ["codex"],
|
||||
unresolved: [
|
||||
{
|
||||
client: "mcporter",
|
||||
state: "unknown",
|
||||
command: [],
|
||||
remediation: expect.stringContaining("MCPORTER_CONFIG is relative"),
|
||||
},
|
||||
],
|
||||
});
|
||||
const current = await planIntegrationMaintenance(
|
||||
home,
|
||||
entryPoint,
|
||||
process.env,
|
||||
async () => ok(JSON.stringify({ status: "planned", plannedActions: [] })),
|
||||
);
|
||||
// Nothing else needs maintenance, yet the unknown client is not hidden.
|
||||
expect(current).toMatchObject({
|
||||
status: "current",
|
||||
unresolved: [{ client: "mcporter", state: "unknown" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("names an unknown MCPorter client when planning the known clients fails", async () => {
|
||||
vi.stubEnv("MCPORTER_CONFIG", "config/mcporter.json");
|
||||
await writeClient("codex", staleCodex);
|
||||
const failed = await planIntegrationMaintenance(
|
||||
home,
|
||||
entryPoint,
|
||||
process.env,
|
||||
async () => err("EACCES codex backup"),
|
||||
);
|
||||
expect(failed).toMatchObject({
|
||||
status: "unavailable",
|
||||
remediation: expect.stringMatching(
|
||||
/^EACCES codex backup REA did not maintain one client .*MCPORTER_CONFIG is relative/u,
|
||||
),
|
||||
scope: { unresolved: [{ client: "mcporter", state: "unknown" }] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("registration ownership in maintenance", () => {
|
||||
it("selects owned registrations while preserving unconfigured, foreign, and disabled choices", async () => {
|
||||
await writeClient("codex", staleCodex);
|
||||
@@ -427,9 +491,10 @@ describe("existing REA integration maintenance", () => {
|
||||
process.env,
|
||||
async () => err("EACCES /test/.codex/config.toml"),
|
||||
),
|
||||
).toEqual({
|
||||
).toMatchObject({
|
||||
status: "unavailable",
|
||||
remediation: "EACCES /test/.codex/config.toml",
|
||||
scope: { clients: ["codex"] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user