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
2 changes: 1 addition & 1 deletion docs/internals/07_settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Settings entries extend the built-ins. An embedder that passes `plugins` to the

`mcp.json` sits beside each settings file: in the user directory (the home, or `--user-config-dir`) and in the project's `.codework/`. See [config.ts](../../packages/harness/src/mcp/config.ts).

A project entry replaces the user entry with the same name. A project entry with no `command`, `url` or `type` overrides only `enabled`, `exposure` and `toolExposure`, and keeps the rest of the user entry, including credentials the project could not set itself. Only the `.json` spelling is read. Unlike settings, a broken file or entry is reported and skipped, so one bad server never stops the others.
A project entry replaces the user entry with the same name or connector, whole: entries are never merged. Only the `.json` spelling is read. Unlike settings, a broken file or entry is reported and skipped, so one bad server never stops the others.

## Writing Settings

Expand Down
6 changes: 5 additions & 1 deletion docs/internals/08_plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,11 @@ MCP servers always run on the host, never in a sandbox ([mcp.ts](../../packages/

A stdio server starts in a directory chosen by its `scope`. A `session` server starts in the thread's directory when the sandbox is local. Otherwise that directory does not exist on the host, so it starts in `hostDir`, else `hostCwd`, and gets no roots. A `space` server follows the same rule with the space root. An `app` server starts in `hostCwd`. The server's own relative `cwd` resolves against that start directory.

Servers come from two sources: `mcp.json` beside each settings file, in the `mcpServers` shape other clients use ([config.ts](../../packages/harness/src/mcp/config.ts)), and enabled `mcp` Connections from `Connector.Broker` (auto-registered in [state.ts](../../packages/harness/src/state/state.ts), with an explicit `mcp.json` entry of the same name winning). A project entry with no `command`, `url` or `type` only overrides `enabled` and exposure of the user server of that name, keeping credentials a project could not set. Unlike settings, a broken `mcp.json` entry is reported and skipped. `mcp` plugins can edit the servers before tools exist.
Servers come from `mcp.json` beside each settings file, in the `mcpServers` shape other clients use ([config.ts](../../packages/harness/src/mcp/config.ts)), and nothing else: a stored connection is never attached on its own. An entry is a `command`, a `url` or a `connector`, used as written. The project file replaces the user file's entry of the same name or connector, like a `.env` file, and nothing is ever merged from both: a merged entry is one no file shows. A connector entry names the catalog connector only; its account comes from the vault, so a file never sends a credential anywhere. Unlike settings, a broken `mcp.json` entry is reported and skipped. `mcp` plugins can edit the servers before tools exist.

Over the files sit two soft layers the host stores, never in a file: Project Settings, then This Session ([layers.ts](../../packages/harness/src/mcp/layers.ts)). One rule holds at each: a layer switches off what the layer below has on, never switches on what it has off (a file's `"enabled": false` included), and adds or removes what no layer below names. The desktop's switches write these layers; only the raw editors write `mcp.json`, because a switch that edits a shared file makes git changes the person never meant to make.

A connector runs on the session's pick, else Project Settings', else the vault's Default, and only on a stored, enabled connection: no environment variable, no next connection when the Default is off. That is stricter than providers on purpose, since an MCP server acts on the person's data as them. The account is pinned for a run (`mcp_account`), so a Make Default lands at the next run, and a run resumed after a restart keeps it. A connection turned off mid-turn refuses the rest of that turn's calls as disabled, never as "sign in".

Connections never open a browser. They use stored tokens, refresh them, or move to `authenticate`, and the user signs in with `codework connect` (for connector-backed servers) or `codework mcp login` (for legacy `mcp.json` OAuth servers). Server states are single words. Connector-backed MCP credentials live in `<home>/connections.db`, validated against the connection's `allowedHosts` before any token is injected, with single-flight refresh locking; legacy `mcp.json` OAuth tokens live in `<home>/mcpauth.json` under a cross-process refresh lock because servers rotate refresh tokens and a token used twice loses the grant ([oauth.ts](../../packages/harness/src/mcp/oauth.ts)). A tool call is never retried once the server may have run it.

Expand Down
103 changes: 103 additions & 0 deletions packages/codework/src/cli/cmd/cmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,28 @@ const McpControlParams = {
server: RunningServer,
};

/**
* The soft layer an MCP command acts on, on this home's server: This Session with --session, else
* Project Settings of --project or of the project this directory is in.
*/
const McpLayerTarget = {
session: Flag.String("session").pipe(
Flag.withAlias("s"),
Flag.withDescription("Act on This Session of this session instead of Project Settings"),
Flag.optional,
),
project: Flag.String("project").pipe(
Flag.withDescription("Project ID (default: the project of this directory)"),
Flag.optional,
),
server: RunningServer,
};

const McpSlot = Argument.String("slot").pipe(
Argument.withDescription("A connector id for a connector server, else the server name"),
);
const McpConnector = Argument.String("connector").pipe(Argument.withDescription("Connector id, e.g. app.linear"));

const JsonFlag = Flag.Boolean("json").pipe(
Flag.withDescription("Print machine-readable output"),
Flag.withDefault(false),
Expand Down Expand Up @@ -149,6 +171,12 @@ export const Cmd = Spec.make("codework", {
Flag.withDescription("Streamable HTTP server URL (instead of a command)"),
Flag.optional,
),
connector: Flag.String("connector").pipe(
Flag.withDescription(
"Catalog connector id, run on your stored connection (instead of a url or command)",
),
Flag.optional,
),
env: Flag.KeyValuePair("env").pipe(
Flag.withDescription("Environment variable of a stdio server, as KEY=VALUE"),
Flag.optional,
Expand Down Expand Up @@ -209,6 +237,10 @@ export const Cmd = Spec.make("codework", {
command: "codework mcp add tools -l --url http://127.0.0.1:8080/mcp",
description: "Add a server to this project only",
},
{
command: "codework mcp add linear --connector app.linear",
description: "Add a catalog connector; it runs on your app.linear connection",
},
],
}),
Spec.make("remove", {
Expand Down Expand Up @@ -283,6 +315,77 @@ export const Cmd = Spec.make("codework", {
},
],
}),
Spec.make("view", {
description: "Show Project Settings, and with --session This Session, as the server resolves them",
params: { ...McpLayerTarget, json: JsonFlag },
examples: [
{ command: "codework mcp view", description: "Project Settings of this directory's project" },
{ command: "codework mcp view --session ses_01h9", description: "This Session over its project's" },
],
}),
Spec.make("off", {
description: "Switch a server off in Project Settings, or in This Session with --session",
params: { slot: McpSlot, ...McpLayerTarget },
examples: [
{
command: "codework mcp off app.linear",
description: "Switch the Linear connector off for this project",
},
{
command: "codework mcp off fs --session ses_01h9",
description: "Switch the fs server off in one session",
},
],
}),
Spec.make("on", {
description: "Switch back on a server this layer switched off",
params: { slot: McpSlot, ...McpLayerTarget },
examples: [{ command: "codework mcp on app.linear", description: "Undo this project's off" }],
}),
Spec.make("attach", {
description: "Add a connector no mcp.json names to Project Settings, or This Session with --session",
params: {
connector: McpConnector,
account: Flag.String("account").pipe(
Flag.withDescription("Connection uid to run it on (default: the layer's account)"),
Flag.optional,
),
...McpLayerTarget,
},
examples: [
{ command: "codework mcp attach app.linear", description: "Add Linear to this project" },
{
command: "codework mcp attach app.linear --account app.linear/side --session ses_01h9",
description: "Add it to one session on another account",
},
],
}),
Spec.make("detach", {
description: "Remove a connector this layer attached",
params: { connector: McpConnector, ...McpLayerTarget },
examples: [
{ command: "codework mcp detach app.linear", description: "Remove Linear from this project" },
],
}),
Spec.make("account", {
description: "Pick the connection a connector runs on in this layer",
params: {
connector: McpConnector,
uid: Argument.String("uid").pipe(Argument.withDescription("Connection uid, e.g. app.linear/side")),
...McpLayerTarget,
},
examples: [
{
command: "codework mcp account app.linear app.linear/side",
description: "Run Linear on the side account for this project",
},
],
}),
Spec.make("reset", {
description: "Drop this layer's off and account pick for a server",
params: { slot: McpSlot, ...McpLayerTarget },
examples: [{ command: "codework mcp reset app.linear", description: "Follow the layer below again" }],
}),
],
}),
Spec.make("run", {
Expand Down
1 change: 1 addition & 0 deletions packages/codework/src/cli/cmd/handlers/mcp/account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { account as default } from "./layer.ts";
36 changes: 22 additions & 14 deletions packages/codework/src/cli/cmd/handlers/mcp/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,28 @@ export default Runtime.handler(
const dash = process.argv.indexOf("--");
const command = dash === -1 ? [...input.command] : process.argv.slice(dash + 1);
const url = Option.getOrUndefined(input.url);
if (url === undefined && command.length === 0)
const connector = Option.getOrUndefined(input.connector);
const given = [url, connector, command.length > 0 ? command : undefined].filter(
(one) => one !== undefined,
).length;
if (given !== 1)
return yield* new InvalidInputError({
message: "give either --url <url> or the server's command after --",
message: `give one of --url <url>, --connector <id> or the server's command after --${given > 1 ? ", not several" : ""}`,
});
if (url !== undefined && command.length > 0)
return yield* new InvalidInputError({
message: "give either --url <url> or the server's command after --, not both",
});
const misplaced = (url === undefined ? HTTP_ONLY : STDIO_ONLY).find((key) =>
Option.isSome(input[key] as Option.Option<unknown>),
);
const misplaced = (
connector !== undefined ? [...HTTP_ONLY, ...STDIO_ONLY] : url === undefined ? HTTP_ONLY : STDIO_ONLY
).find((key) => Option.isSome(input[key] as Option.Option<unknown>));
if (misplaced !== undefined)
return yield* new InvalidInputError({
message: `${FLAGS[misplaced]} only applies to ${url === undefined ? "HTTP servers (--url)" : "stdio servers"}`,
message:
connector !== undefined
? `${FLAGS[misplaced]} does not apply to a connector server; its connection says where it runs and how it signs in`
: `${FLAGS[misplaced]} only applies to ${url === undefined ? "HTTP servers (--url)" : "stdio servers"}`,
});

let config: Record<string, unknown>;
if (url !== undefined) {
if (connector !== undefined) config = { connector };
else if (url !== undefined) {
const headers = { ...Option.getOrElse(input.header, () => ({})) };
if (Option.isSome(input.bearerTokenEnvVar))
headers.Authorization = `Bearer \${${input.bearerTokenEnvVar.value}}`;
Expand Down Expand Up @@ -103,9 +107,13 @@ export default Runtime.handler(
const signIn =
"url" in validated &&
!Object.keys(validated.headers ?? {}).some((header) => header.toLowerCase() === "authorization");
yield* writeOut(
`Check it with: codework mcp list${signIn ? `. If it requires sign-in: codework mcp login ${name}` : ""}\n`,
);
const hint =
connector !== undefined
? `. It runs on your Default ${connector} connection; create one with: codework connect create ${connector}`
: signIn
? `. If it requires sign-in: codework mcp login ${name}`
: "";
yield* writeOut(`Check it with: codework mcp list${hint}\n`);
});
return yield* program.pipe(Effect.catch(reportFailure));
}),
Expand Down
1 change: 1 addition & 0 deletions packages/codework/src/cli/cmd/handlers/mcp/attach.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { attach as default } from "./layer.ts";
1 change: 1 addition & 0 deletions packages/codework/src/cli/cmd/handlers/mcp/detach.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { detach as default } from "./layer.ts";
120 changes: 120 additions & 0 deletions packages/codework/src/cli/cmd/handlers/mcp/layer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { AbsolutePath } from "@codeworksh/schema/common";
import type { McpEdit, McpView } from "@codeworksh/schema/mcp";
import { ProjectCheckoutError, ProjectNotFoundError } from "@codeworksh/schema/project";
import { SessionNotFoundError } from "@codeworksh/schema/session";
import { Effect, FileSystem, Option, Path, Schema } from "effect";
import * as Runtime from "../../../../framework/runtime.ts";
import * as Client from "../../../../server/client.ts";
import { InvalidInputError, reportFailure } from "../../../error.ts";
import { sessionId } from "../../../ids.ts";
import { writeOut } from "../../../output.ts";
import * as Service from "../../../service.ts";
import { Cmd } from "../../cmd.ts";

interface Target {
readonly session: Option.Option<string>;
readonly project: Option.Option<string>;
}

/** The layer a command addresses: This Session with --session, else Project Settings of --project or this directory. */
export const resolveTarget = Effect.fn("CLI.mcp.target")(function* (target: Target) {
if (Option.isSome(target.session) && Option.isSome(target.project))
return yield* new InvalidInputError({ message: "give --session or --project, not both" });
if (Option.isSome(target.session)) {
const id = yield* sessionId(target.session.value);
return { payload: { sessionId: id }, label: () => `This Session (${id})` };
}
const label = (view: McpView) => `Project Settings (${view.projectId})`;
if (Option.isSome(target.project)) return { payload: { projectId: target.project.value }, label };
// The server maps the directory to its project, and creates none.
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = AbsolutePath.make(yield* fs.realPath(path.resolve(".")));
return { payload: { directory }, label };
});

const isSessionNotFound = Schema.is(SessionNotFoundError);
const isProjectNotFound = Schema.is(ProjectNotFoundError);
const isProjectCheckout = Schema.is(ProjectCheckoutError);

/** The server's typed refusals, said plainly. */
export const plainly = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError((error) => {
if (isSessionNotFound(error))
return new InvalidInputError({ message: `no session ${error.sessionId} on this home's server` });
if (isProjectNotFound(error))
return new InvalidInputError({
message: error.projectId.startsWith("/")
? `${error.projectId} is in no project this home's server knows; start a session there, or pass --project <id>`
: `no project ${error.projectId} on this home's server`,
});
if (isProjectCheckout(error))
return new InvalidInputError({
message: `project ${error.projectId} has no checkout on this home's machine`,
});
return error;
}),
);

const done = (edit: McpEdit, label: string) => {
switch (edit._tag) {
case "switch":
return `Switched ${edit.slot} ${edit.on ? "on" : "off"} in ${label}.`;
case "add":
return `Attached ${edit.connector}${edit.connection === undefined ? "" : ` on ${edit.connection}`} in ${label}.`;
case "remove":
return `Detached ${edit.connector} from ${label}.`;
case "account":
return `${edit.connector} runs on ${edit.connection} in ${label}.`;
case "reset":
return `Reset ${edit.slot} in ${label}.`;
}
};

/** One `mcp.edit` on this home's server; the server checks it against the layers below. */
const edit = <I extends Target & { readonly server: Option.Option<string> }>(
name: string,
change: (input: I) => McpEdit,
) =>
Effect.fn(`CLI.mcp.${name}`)(function* (input: I) {
const program = Effect.gen(function* () {
const rpc = yield* Client.make;
const target = yield* resolveTarget(input);
const one = change(input);
const view = yield* plainly(rpc["mcp.edit"]({ ...target.payload, edit: one }));
yield* writeOut(`${done(one, target.label(view))}\n`);
});
return yield* program.pipe(Service.connect(Option.getOrUndefined(input.server)), Effect.catch(reportFailure));
});

const commands = Cmd.commands.mcp.commands;

export const off = Runtime.handler(
commands.off,
edit("off", ({ slot }) => ({ _tag: "switch", slot, on: false })),
);
export const on = Runtime.handler(
commands.on,
edit("on", ({ slot }) => ({ _tag: "switch", slot, on: true })),
);
export const attach = Runtime.handler(
commands.attach,
edit("attach", ({ connector, account }) => ({
_tag: "add",
connector,
...(Option.isSome(account) ? { connection: account.value } : {}),
})),
);
export const detach = Runtime.handler(
commands.detach,
edit("detach", ({ connector }) => ({ _tag: "remove", connector })),
);
export const account = Runtime.handler(
commands.account,
edit("account", ({ connector, uid }) => ({ _tag: "account", connector, connection: uid })),
);
export const reset = Runtime.handler(
commands.reset,
edit("reset", ({ slot }) => ({ _tag: "reset", slot })),
);
Loading