Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions apps/contract/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
StoredAuthType,
} from "@codeworksh/schema/connector";
import { Machine } from "@codeworksh/schema/machine";
import { McpEdit, McpView } from "@codeworksh/schema/mcp";
import { Schema } from "effect";
import { Rpc, RpcGroup } from "effect/rpc";
import {
Expand Down Expand Up @@ -283,6 +284,13 @@ export class SettingsError extends Schema.TaggedError<SettingsError>()("Server.S
message: Schema.String,
}) {}

/** An MCP layer change the server refused, saying why: a server a file locks, an unknown account. */
export class McpRefused extends Schema.TaggedError<McpRefused>()("Server.McpRefused", {
message: Schema.String,
}) {}

export { McpEdit, McpView };

/** A settings file changed since it was read; nothing was written. */
export class SettingsConflict extends Schema.TaggedError<SettingsConflict>()("Server.SettingsConflict", {
path: Schema.String,
Expand Down Expand Up @@ -997,6 +1005,30 @@ export const Api = RpcGroup.make(
success: Schema.Struct({ version: Schema.String }),
error: Schema.Union(SettingsErrors),
}),
/**
* A project's MCP servers as Project Settings shows them, and with `sessionId` as This Session shows
* them over it, read from the machine the project or session is on.
*/
Rpc.make("mcp.view", {
payload: {
...OnMachine,
projectId: Schema.optionalKey(Schema.String),
sessionId: Schema.optionalKey(Schema.String),
},
success: McpView,
error: Schema.Union([...SettingsErrors, McpRefused]),
}),
/** One change to Project Settings (`projectId`) or This Session (`sessionId`); never writes mcp.json. */
Rpc.make("mcp.edit", {
payload: {
...OnMachine,
projectId: Schema.optionalKey(Schema.String),
sessionId: Schema.optionalKey(Schema.String),
edit: McpEdit,
},
success: McpView,
error: Schema.Union([...SettingsErrors, McpRefused]),
}),
/** Renames a project on the CodeWork server; the sidebar follows once the change syncs back. */
Rpc.make("projects.rename", {
payload: { ...OnMachine, projectId: Schema.String, name: Schema.Trimmed.check(Schema.isNonEmpty()) },
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import { Effect, Predicate, Schema, Stream } from "effect";
import { SqlClient } from "effect/sql";
import { Changes } from "./changes.ts";
import { Cli } from "./cli.ts";
import { SessionID } from "@codeworksh/schema/ids";
import { Codework } from "./codework.ts";
import {
type CliAction,
CodeworkUnavailable,
Contract,
DesktopConnectorError,
McpRefused,
ModelsError,
type OAuthRunEvent,
ProjectError,
Expand Down Expand Up @@ -49,6 +51,12 @@ const refusals: ReadonlyArray<string> = [
const isRefusal = (error: unknown): error is SettingsRefusal =>
Predicate.hasProperty(error, "_tag") && refusals.includes(error._tag as string);

/** Project Settings by `projectId`, or This Session by `sessionId`. */
const mcpTarget = (projectId: string | undefined, sessionId: string | undefined) => ({
...(projectId === undefined ? {} : { projectId }),
...(sessionId === undefined ? {} : { sessionId: SessionID.make(sessionId) }),
});

const refusal = (error: SettingsRefusal) => {
switch (error._tag) {
case "SettingsError":
Expand Down Expand Up @@ -162,6 +170,17 @@ export const layer = Contract.Api.toLayer(
).pipe(
Effect.flatMap((reply) => ("failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.value))),
);
// An MCP layer change is refused with the harness's own reason; a session gone is the project's error.
const mcpCall = <A, E>(use: Parameters<typeof Codework.call<A, E>>[0]) =>
settingsCall(use).pipe(
Effect.mapError((error) =>
Predicate.isTagged(error, "Mcp.EditError")
? new McpRefused({ message: String((error as { readonly message?: unknown }).message) })
: Predicate.isTagged(error, "SessionNotFoundError")
? new ProjectError({ message: "This session is no longer on its server." })
: error,
),
);
const connectorErrorTags: ReadonlyArray<string> = [
"Connector.NotFoundError",
"Connection.NotFoundError",
Expand Down Expand Up @@ -320,6 +339,10 @@ export const layer = Contract.Api.toLayer(
onMachine(machineId)(settingsCall((client) => client("settings.write", input))),
"settings.set": ({ machineId, ...input }) =>
onMachine(machineId)(settingsCall((client) => client("settings.set", input))),
"mcp.view": ({ machineId, projectId, sessionId }) =>
onMachine(machineId)(mcpCall((client) => client("mcp.view", mcpTarget(projectId, sessionId)))),
"mcp.edit": ({ machineId, projectId, sessionId, edit }) =>
onMachine(machineId)(mcpCall((client) => client("mcp.edit", { ...mcpTarget(projectId, sessionId), edit }))),
"projects.rename": Effect.fn("projects.rename")(function* ({ machineId, projectId, name }) {
return yield* onMachine(machineId)(projectCall((client) => client("project.rename", { projectId, name })));
}),
Expand Down
100 changes: 100 additions & 0 deletions apps/server/test/__artifacts__/mcp.machines.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
{
"cw-a": {
"project": {
"layer": {
"off": [],
"added": [],
"account": {
"app.linear": "app.linear/side"
}
},
"linear": {
"on": true,
"connection": "app.linear/side",
"state": "connected",
"accounts": [
"app.linear/work",
"app.linear/side"
]
}
},
"session": {
"layer": {
"off": [
"app.linear"
],
"added": [],
"account": {}
},
"linear": {
"on": false,
"connection": "app.linear/side",
"state": "connected",
"accounts": [
"app.linear/work",
"app.linear/side"
]
}
}
},
"cw-b": {
"project": {
"layer": {
"off": [],
"added": [],
"account": {}
},
"linear": {
"on": true,
"connection": "app.linear/solo",
"state": "connected",
"accounts": [
"app.linear/solo"
]
}
},
"session": {
"layer": {
"off": [],
"added": [],
"account": {}
},
"linear": {
"on": true,
"connection": "app.linear/solo",
"state": "connected",
"accounts": [
"app.linear/solo"
]
}
}
},
"cw-c": {
"project": {
"layer": {
"off": [],
"added": [],
"account": {}
},
"linear": {
"on": true,
"connection": null,
"state": "not_connected",
"accounts": []
}
},
"session": {
"layer": {
"off": [],
"added": [],
"account": {}
},
"linear": {
"on": true,
"connection": null,
"state": "not_connected",
"accounts": []
}
}
}
}
144 changes: 144 additions & 0 deletions apps/server/test/mcp.machines.live.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/* @effect-diagnostics nodeBuiltinImport:off -- the suite runs CodeWork servers on OrbStack Linux machines. */
import { Effect } from "effect";
import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
import "../../../packages/harness/test/utils/env.ts";
import { available, ensure, machine, type Machine } from "./machines/orb.ts";

/*
* MCP layers live on the machine that runs the session: three CodeWork servers on OrbStack Linux
* machines, each with its own connection vault and its own Project Settings and This Session layers,
* driven from the Mac. The same project mcp.json names Linear on every machine; each resolves it
* against its own vault only, and an edit on one machine never shows on another.
*/

const machines = [machine("cw-a"), machine("cw-b"), machine("cw-c")] as const;
const [a] = machines;

/** Linear connections each machine holds: two, one, none. */
const vaults: Record<string, ReadonlyArray<string>> = { "cw-a": ["work", "side"], "cw-b": ["solo"], "cw-c": [] };

const project = (cw: Machine) => `${cw.cwHome}/../mcp-demo`;

const prepare = async (cw: Machine) => {
await cw.stop("KILL").catch(() => undefined);
await cw.wipe();
const dir = project(cw);
await cw.sh(
`rm -rf ${dir} && mkdir -p ${dir}/.codework && cd ${dir} && git init -q && echo demo > README.md && git add -A && git -c user.email=t@t -c user.name=t commit -qm init`,
);
await cw.sh(
`cat > ${dir}/.codework/mcp.json`,
JSON.stringify({ mcpServers: { linear: { connector: "app.linear" } } }),
);
await cw.start();
};

/** A session in the project on `cw`, its machine's Linear connections, and the session's view. */
const seed = (cw: Machine) =>
cw.run((rpc) =>
Effect.gen(function* () {
for (const slug of vaults[cw.name] ?? []) {
const made = yield* rpc["connections.create"]({ connector: "app.linear", slug, authType: "apikey" });
yield* rpc["connections.setApiKey"]({ ref: made.uid, apiKey: `lin_api_${cw.name}_${slug}` });
}
const dir = yield* Effect.promise(() => cw.sh(`cd ${project(cw)} && pwd -P`));
const created = yield* rpc["session.create"]({ directory: dir.trim(), hostDir: dir.trim() as never });
return { sessionId: created.session.id, projectId: created.session.project?.id ?? "" };
}),
);

const linearOf = (view: {
readonly rows: ReadonlyArray<{
readonly slot: string;
readonly on: boolean;
readonly connection?: string | undefined;
readonly state?: string | undefined;
readonly accounts: ReadonlyArray<{ readonly uid: string }>;
}>;
}) => {
const row = view.rows.find((one) => one.slot === "app.linear");
return row === undefined
? null
: {
on: row.on,
connection: row.connection ?? null,
state: row.state ?? null,
accounts: row.accounts.map((one) => one.uid),
};
};

describe.skipIf(!available)("mcp layers across machines", () => {
beforeAll(async () => {
await Promise.all(machines.map((cw) => ensure(cw.name)));
await Promise.all(machines.map((cw) => cw.setup()));
await Promise.all(machines.map(prepare));
}, 2_400_000);

afterAll(async () => {
await Promise.all(machines.map((cw) => cw.stop("KILL").catch(() => undefined)));
}, 120_000);

it("each machine resolves its own vault and layers, and an edit on one never reaches another", async () => {
const seeded = await Promise.all(machines.map(seed));
const onA = seeded[0]!;

// On cw-a only: Project Settings runs Linear on the side account; This Session switches it off.
await a.run((rpc) =>
Effect.gen(function* () {
yield* rpc["mcp.edit"]({
projectId: onA.projectId,
edit: { _tag: "account", connector: "app.linear", connection: "app.linear/side" },
});
yield* rpc["mcp.edit"]({
sessionId: onA.sessionId as never,
edit: { _tag: "switch", slot: "app.linear", on: false },
});
}),
);

const views = await Promise.all(
machines.map((cw, index) =>
cw.run((rpc) => rpc["mcp.view"]({ sessionId: seeded[index]!.sessionId as never })),
),
);
const artifact = Object.fromEntries(
machines.map((cw, index) => {
const view = views[index]!;
return [
cw.name,
{
project: { layer: view.project.layer, linear: linearOf(view.project) },
session: {
layer: view.session?.layer ?? null,
linear: view.session === undefined ? null : linearOf(view.session),
},
},
];
}),
);

expect(artifact["cw-a"]?.project.linear).toEqual({
on: true,
connection: "app.linear/side",
state: "connected",
accounts: ["app.linear/work", "app.linear/side"],
});
expect(artifact["cw-a"]?.session.linear?.on).toBe(false);
expect(artifact["cw-b"]?.project.linear).toEqual({
on: true,
connection: "app.linear/solo",
state: "connected",
accounts: ["app.linear/solo"],
});
expect(artifact["cw-b"]?.project.layer).toEqual({ off: [], added: [], account: {} });
expect(artifact["cw-c"]?.project.linear).toEqual({
on: true,
connection: null,
state: "not_connected",
accounts: [],
});
await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot(
"./__artifacts__/mcp.machines.json",
);
}, 300_000);
});
11 changes: 10 additions & 1 deletion apps/web/src/routes/_shell.settings.mcp.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import { createFileRoute } from "@tanstack/react-router";

import { Group, Section } from "../settings/blocks";
import { ConnectorsPage } from "../settings/connectors/page";
import { UserMcpFile } from "../widgets/session/config";

function McpConnectorsSettings() {
return (
<ConnectorsPage
kind="mcp"
title="MCP Connectors"
description="Connect hosted MCP servers like Linear. Active MCP connections are automatically available in sessions."
description="Connect hosted MCP servers like Linear. Add them to a project or session from its settings."
emptyTitle="No MCP Connectors Available"
emptyDescription="Refresh the catalog to load available MCP connectors."
advanced={(machineId) => (
<Section title="Advanced">
<Group>
<UserMcpFile machineId={machineId} />
</Group>
</Section>
)}
/>
);
}
Expand Down
11 changes: 8 additions & 3 deletions apps/web/src/settings/connectors/atoms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@ export const catalogAtom = (kind: ConnectorKind, machineId?: string) =>
});

export const connectionsAtom = (kind: ConnectorKind, machineId?: string) =>
Server.query("connections.list", machineId === undefined ? { kind } : { kind, machineId }, {
reactivityKeys: ["connections", kind, machineId ?? "default"],
});
// MCP uses stored connections only, so an environment variable is never listed as one.
Server.query(
"connections.list",
{ kind, ...(kind === "mcp" ? { includeEnv: false } : {}), ...(machineId === undefined ? {} : { machineId }) },
{
reactivityKeys: ["connections", kind, machineId ?? "default"],
},
);

export const createConnectionAtom = Server.mutation("connections.create");
export const updateConnectionAtom = Server.mutation("connections.update");
Expand Down
Loading