From 0b19d512e80431b5a19678b26efb7f49a707dba2 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 7 Oct 2026 23:55:00 -0700
Subject: [PATCH 01/35] =?UTF-8?q?feat:=20manage=20skills=20and=20MCP=20ser?=
=?UTF-8?q?vers=20in=20Settings=20=E2=86=92=20Tools?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Adds a Tools settings page with Skills and MCP servers tabs, scoped to
environments and projects like other settings.
- MCP servers added in T3 are injected into every provider session next to
the t3-code server (Claude, Codex, Cursor, OpenCode 1/2, Grok and ACP
agents). Sensitive env/header values live in the secret store.
- Skills can be switched off by name; Claude, Codex and OpenCode 1.x hide
them from the session, and the composer drops them from its menu.
- Projects override servers and skill switches per name instead of
replacing the environment's list.
Co-Authored-By: Claude Opus 5.5 (1M context)
---
apps/server/src/mcp/McpProviderSession.ts | 37 +-
apps/server/src/mcp/resolveAgentTools.ts | 27 +
apps/server/src/mcpServerSecrets.ts | 221 ++++++
.../orchestration-v2/Adapters/AcpAdapterV2.ts | 38 +-
.../Adapters/ClaudeAdapterV2.test.ts | 75 ++
.../Adapters/ClaudeAdapterV2.ts | 54 +-
.../Adapters/CodexAdapterV2.test.ts | 44 ++
.../Adapters/CodexAdapterV2.ts | 33 +
.../Adapters/CursorAdapterV2.ts | 19 +
.../Adapters/OpenCode2AdapterV2.ts | 144 +++-
.../Adapters/OpenCodeAdapterV2.ts | 57 +-
.../ProviderSessionManager.ts | 32 +-
.../src/provider/acp/AcpSessionRuntime.ts | 17 +-
apps/server/src/serverSettings.test.ts | 68 ++
apps/server/src/serverSettings.ts | 57 +-
apps/web/src/components/ChatView.tsx | 1 +
apps/web/src/components/chat/ChatComposer.tsx | 28 +-
.../components/settings/McpServerDialog.tsx | 331 ++++++++
.../settings/SettingsSidebarNav.tsx | 2 +
.../src/components/settings/ToolsSettings.tsx | 717 ++++++++++++++++++
.../src/components/settings/settingsSearch.ts | 21 +
.../settings/toolsSettings.logic.test.ts | 189 +++++
.../settings/toolsSettings.logic.ts | 468 ++++++++++++
apps/web/src/routeTree.gen.ts | 21 +
apps/web/src/routes/settings.tools.tsx | 27 +
docs/README.md | 1 +
docs/user/composer.md | 3 +-
docs/user/project-settings.md | 4 +-
docs/user/tools.md | 39 +
packages/contracts/src/agentTools.ts | 130 ++++
packages/contracts/src/index.ts | 1 +
packages/contracts/src/settings.ts | 40 +-
packages/shared/src/agentTools.test.ts | 133 ++++
packages/shared/src/projectSettings.ts | 58 ++
packages/shared/src/serverSettings.ts | 7 +
35 files changed, 3099 insertions(+), 45 deletions(-)
create mode 100644 apps/server/src/mcp/resolveAgentTools.ts
create mode 100644 apps/server/src/mcpServerSecrets.ts
create mode 100644 apps/web/src/components/settings/McpServerDialog.tsx
create mode 100644 apps/web/src/components/settings/ToolsSettings.tsx
create mode 100644 apps/web/src/components/settings/toolsSettings.logic.test.ts
create mode 100644 apps/web/src/components/settings/toolsSettings.logic.ts
create mode 100644 apps/web/src/routes/settings.tools.tsx
create mode 100644 docs/user/tools.md
create mode 100644 packages/contracts/src/agentTools.ts
create mode 100644 packages/shared/src/agentTools.test.ts
diff --git a/apps/server/src/mcp/McpProviderSession.ts b/apps/server/src/mcp/McpProviderSession.ts
index 5bf76d85b7b54..a9c41f0ccb28b 100644
--- a/apps/server/src/mcp/McpProviderSession.ts
+++ b/apps/server/src/mcp/McpProviderSession.ts
@@ -1,4 +1,32 @@
-import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import type {
+ EnvironmentId,
+ ProviderInstanceId,
+ ResolvedMcpServer,
+ ThreadId,
+} from "@t3tools/contracts";
+
+/**
+ * The user's tools for one thread, resolved from Settings → Tools when the
+ * session is prepared. Adapters add the servers next to `t3-code` and hide
+ * the skills where their provider can.
+ */
+export interface McpProviderSessionTools {
+ /** Enabled servers with secrets materialized, sorted by name. */
+ readonly servers: ReadonlyArray;
+ /** Skill names hidden from the agent, sorted. */
+ readonly disabledSkills: ReadonlyArray;
+ /**
+ * Changes whenever `servers` or `disabledSkills` do, without exposing a
+ * secret. Adapters compare it to decide when a live process is stale.
+ */
+ readonly fingerprint: string;
+}
+
+export const EMPTY_MCP_PROVIDER_SESSION_TOOLS: McpProviderSessionTools = {
+ servers: [],
+ disabledSkills: [],
+ fingerprint: "",
+};
export interface McpProviderSessionConfig {
readonly environmentId: EnvironmentId;
@@ -22,6 +50,13 @@ export interface McpProviderSessionConfig {
* already pointed at the server's daemon; the agent never handles a token.
*/
readonly agentDeviceEnvironment?: Readonly>;
+ /** Servers and skill switches from Settings → Tools; absent means none. */
+ readonly tools?: McpProviderSessionTools;
+}
+
+/** The thread's user tools, or none when its session has no MCP config. */
+export function readMcpProviderSessionTools(threadId: ThreadId): McpProviderSessionTools {
+ return sessionsByThread.get(threadId)?.tools ?? EMPTY_MCP_PROVIDER_SESSION_TOOLS;
}
/** Provider env with the device variables applied over `base`, or `base` untouched. */
diff --git a/apps/server/src/mcp/resolveAgentTools.ts b/apps/server/src/mcp/resolveAgentTools.ts
new file mode 100644
index 0000000000000..f0e8dbc2c9753
--- /dev/null
+++ b/apps/server/src/mcp/resolveAgentTools.ts
@@ -0,0 +1,27 @@
+import type { ProjectId, ResolvedMcpServer, ServerSettings } from "@t3tools/contracts";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
+
+import type { McpProviderSessionTools } from "./McpProviderSession.ts";
+
+/**
+ * A thread's tools from settings whose secrets are already materialized:
+ * the project's overrides applied, disabled servers dropped. The fingerprint
+ * covers the full config so a rotated secret also counts as a change; it
+ * stays on the server and is only ever compared, never sent or logged.
+ */
+export function resolveAgentTools(
+ settings: ServerSettings,
+ projectId: ProjectId | null,
+): McpProviderSessionTools {
+ const effective = resolveProjectSettings(settings, projectId).settings;
+ const servers: ResolvedMcpServer[] = Object.entries(effective.mcpServers)
+ .filter(([, server]) => server.enabled)
+ .map(([name, server]) => ({ name, transport: server.transport }))
+ .toSorted((left, right) => left.name.localeCompare(right.name));
+ const disabledSkills = [...new Set(effective.disabledSkills)].toSorted();
+ const fingerprint =
+ servers.length === 0 && disabledSkills.length === 0
+ ? ""
+ : JSON.stringify({ servers, disabledSkills });
+ return { servers, disabledSkills, fingerprint };
+}
diff --git a/apps/server/src/mcpServerSecrets.ts b/apps/server/src/mcpServerSecrets.ts
new file mode 100644
index 0000000000000..ad58df7c577c6
--- /dev/null
+++ b/apps/server/src/mcpServerSecrets.ts
@@ -0,0 +1,221 @@
+/**
+ * Sensitive MCP server variables (env values, HTTP headers) live in the
+ * secret store, never in settings.json or on the wire. Servers sit in two
+ * places, the environment's `mcpServers` and each project's override entry,
+ * so every helper here walks both.
+ *
+ * On disk and towards clients a sensitive variable is `{value: "",
+ * valueRedacted: true}`. A client that sends that back keeps the stored
+ * secret; a new value replaces it; turning `sensitive` off moves the value
+ * back into settings.
+ */
+import type {
+ McpServerConfig,
+ McpServerProjectOverride,
+ McpServerVariable,
+ ProjectSettingsOverrides,
+ ServerSettings,
+} from "@t3tools/contracts";
+
+/** Where a server lives: the environment, or one project's overrides. */
+type McpServerOwner = { readonly kind: "environment" } | { readonly kind: "project"; id: string };
+
+type ServerEntry = McpServerConfig | McpServerProjectOverride;
+
+const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url");
+
+/** Deterministic per (owner, server, variable kind, variable name). */
+export function mcpServerSecretName(input: {
+ readonly owner: McpServerOwner;
+ readonly server: string;
+ readonly variableKind: "env" | "header";
+ readonly variable: string;
+}): string {
+ const owner = input.owner.kind === "environment" ? "env" : `project-${encode(input.owner.id)}`;
+ return `mcp-${owner}-${encode(input.server)}-${input.variableKind}-${encode(input.variable)}`;
+}
+
+interface VariableSite {
+ readonly owner: McpServerOwner;
+ readonly server: string;
+ readonly variableKind: "env" | "header";
+ readonly variable: McpServerVariable;
+}
+
+function variablesOf(entry: ServerEntry): {
+ readonly kind: "env" | "header";
+ readonly variables: ReadonlyArray;
+} | null {
+ const transport = entry.transport;
+ if (transport === undefined) return null;
+ return transport.type === "stdio"
+ ? { kind: "env", variables: transport.env }
+ : { kind: "header", variables: transport.headers };
+}
+
+function* variableSites(settings: ServerSettings): Generator {
+ for (const [server, entry] of Object.entries(settings.mcpServers)) {
+ const variables = variablesOf(entry);
+ if (variables === null) continue;
+ for (const variable of variables.variables) {
+ yield { owner: { kind: "environment" }, server, variableKind: variables.kind, variable };
+ }
+ }
+ for (const [id, overrides] of Object.entries(settings.projectSettingsOverrides)) {
+ for (const [server, entry] of Object.entries(overrides.mcpServers ?? {})) {
+ const variables = variablesOf(entry);
+ if (variables === null) continue;
+ for (const variable of variables.variables) {
+ yield { owner: { kind: "project", id }, server, variableKind: variables.kind, variable };
+ }
+ }
+ }
+}
+
+const siteSecretName = (site: VariableSite) =>
+ mcpServerSecretName({
+ owner: site.owner,
+ server: site.server,
+ variableKind: site.variableKind,
+ variable: site.variable.name,
+ });
+
+/**
+ * Rebuild every server in `settings` with `map` applied to each variable.
+ * Returns the input unchanged when no server has variables.
+ */
+function mapVariables(
+ settings: ServerSettings,
+ map: (site: VariableSite) => McpServerVariable,
+): ServerSettings {
+ const mapEntry = (
+ owner: McpServerOwner,
+ server: string,
+ entry: Entry,
+ ): Entry => {
+ const transport = entry.transport;
+ if (transport === undefined) return entry;
+ if (transport.type === "stdio") {
+ if (transport.env.length === 0) return entry;
+ return {
+ ...entry,
+ transport: {
+ ...transport,
+ env: transport.env.map((variable) =>
+ map({ owner, server, variableKind: "env", variable }),
+ ),
+ },
+ };
+ }
+ if (transport.headers.length === 0) return entry;
+ return {
+ ...entry,
+ transport: {
+ ...transport,
+ headers: transport.headers.map((variable) =>
+ map({ owner, server, variableKind: "header", variable }),
+ ),
+ },
+ };
+ };
+ const mcpServers = Object.fromEntries(
+ Object.entries(settings.mcpServers).map(([server, entry]) => [
+ server,
+ mapEntry({ kind: "environment" }, server, entry),
+ ]),
+ ) as ServerSettings["mcpServers"];
+ const projectSettingsOverrides = Object.fromEntries(
+ Object.entries(settings.projectSettingsOverrides).map(([id, overrides]) => [
+ id,
+ overrides.mcpServers === undefined
+ ? overrides
+ : ({
+ ...overrides,
+ mcpServers: Object.fromEntries(
+ Object.entries(overrides.mcpServers).map(([server, entry]) => [
+ server,
+ mapEntry({ kind: "project", id }, server, entry),
+ ]),
+ ),
+ } satisfies ProjectSettingsOverrides),
+ ]),
+ ) as ServerSettings["projectSettingsOverrides"];
+ return { ...settings, mcpServers, projectSettingsOverrides };
+}
+
+/** What a client sees: sensitive values blanked, with a flag that one is stored. */
+export function redactMcpServerSecrets(settings: ServerSettings): ServerSettings {
+ return mapVariables(settings, ({ variable }) => {
+ if (!variable.sensitive) {
+ const { valueRedacted: _omit, ...rest } = variable;
+ return rest;
+ }
+ return {
+ ...variable,
+ value: "",
+ ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),
+ };
+ });
+}
+
+export type McpSecretChange =
+ | { readonly kind: "write"; readonly secretName: string; readonly value: string }
+ | { readonly kind: "remove"; readonly secretName: string };
+
+/**
+ * Plan the secret-store writes for moving from `current` to `next`, and the
+ * settings to persist (sensitive values replaced by the redaction flag).
+ * A sensitive variable sent back redacted with no value keeps its secret;
+ * a value the user typed replaces it; an empty value or a variable that is
+ * no longer sensitive (or no longer exists) removes it.
+ */
+export function planMcpServerSecrets(
+ current: ServerSettings,
+ next: ServerSettings,
+): { readonly settings: ServerSettings; readonly changes: ReadonlyArray } {
+ const stored = new Set();
+ for (const site of variableSites(current)) {
+ if (site.variable.sensitive) stored.add(siteSecretName(site));
+ }
+ const changes: McpSecretChange[] = [];
+ const kept = new Set();
+ const settings = mapVariables(next, (site) => {
+ const secretName = siteSecretName(site);
+ const { variable } = site;
+ const { valueRedacted: _omit, ...plain } = variable;
+ if (!variable.sensitive) return plain;
+ if (variable.value.length === 0) {
+ if (!variable.valueRedacted) return plain;
+ kept.add(secretName);
+ return { ...variable, value: "", valueRedacted: true };
+ }
+ kept.add(secretName);
+ changes.push({ kind: "write", secretName, value: variable.value });
+ return { ...variable, value: "", valueRedacted: true };
+ });
+ for (const secretName of stored) {
+ if (!kept.has(secretName)) changes.push({ kind: "remove", secretName });
+ }
+ return { settings, changes };
+}
+
+/** The secret names whose values `materializeMcpServerSecrets` needs. */
+export function mcpServerSecretNames(settings: ServerSettings): ReadonlyArray {
+ const names: string[] = [];
+ for (const site of variableSites(settings)) {
+ if (site.variable.sensitive && site.variable.valueRedacted) names.push(siteSecretName(site));
+ }
+ return names;
+}
+
+/** Settings with stored secret values filled back in, for server-side consumers. */
+export function materializeMcpServerSecrets(
+ settings: ServerSettings,
+ secrets: ReadonlyMap,
+): ServerSettings {
+ if (secrets.size === 0) return settings;
+ return mapVariables(settings, (site) => {
+ if (!site.variable.sensitive || !site.variable.valueRedacted) return site.variable;
+ return { ...site.variable, value: secrets.get(siteSecretName(site)) ?? "" };
+ });
+}
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
index 179455cb64a8b..903c83a0dad35 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
@@ -28,6 +28,8 @@ import {
type ProviderRequestKind,
type ProviderThreadId,
type ProviderUserInputAnswers,
+ mcpServerVariableRecord,
+ type ResolvedMcpServer,
type RuntimeRequestId,
type ThreadTokenUsageSnapshot,
type ThreadId,
@@ -680,12 +682,45 @@ interface AcpMcpContext {
readonly authorization?: string;
}
+/**
+ * The user's servers from Settings → Tools, passed through as plain ACP
+ * entries. A bare command name is left to the agent's PATH lookup. Http
+ * entries are dropped later for agents that do not advertise http support.
+ */
+function acpUserMcpServers(
+ servers: ReadonlyArray,
+): ReadonlyArray {
+ return servers.map((server) =>
+ server.transport.type === "stdio"
+ ? {
+ // Untyped like T3's own entry: the shape every ACP version accepts.
+ name: server.name,
+ command: server.transport.command,
+ args: [...server.transport.args],
+ env: Object.entries(mcpServerVariableRecord(server.transport.env)).map(
+ ([name, value]) => ({ name, value }),
+ ),
+ }
+ : {
+ type: "http" as const,
+ name: server.name,
+ url: server.transport.url,
+ headers: Object.entries(mcpServerVariableRecord(server.transport.headers)).map(
+ ([name, value]) => ({ name, value }),
+ ),
+ },
+ );
+}
+
function acpMcpContext(threadId: ThreadId | null, self: SelfInvocation): AcpMcpContext {
if (threadId === null) return { servers: [], acpServers: [] };
const session = McpProviderSession.readMcpProviderSession(threadId);
if (session === undefined) {
return { servers: [], acpServers: [] };
}
+ // Both lists carry them: an agent that takes T3's server over ACP gets
+ // only `acpServers`, so the user's servers would otherwise be lost.
+ const userServers = acpUserMcpServers(session.tools?.servers ?? []);
// Stdio is ACP's required baseline MCP transport. Agents that advertise
// optional http support still routinely fail to wire injected http servers
// through to their backend (codex-acp 1.2.0 and pi-acp both drop them), so
@@ -704,8 +739,9 @@ function acpMcpContext(threadId: ThreadId | null, self: SelfInvocation): AcpMcpC
{ name: "T3_ACP_MCP_AUTHORIZATION", value: session.authorizationHeader },
],
},
+ ...userServers,
],
- acpServers: [{ type: "acp", name: "t3-code", serverId: "t3-code" }],
+ acpServers: [{ type: "acp", name: "t3-code", serverId: "t3-code" }, ...userServers],
endpoint: session.endpoint,
authorization: session.authorizationHeader,
processEnvironment: {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 595fe28b1b9e5..ccaebc0930c23 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -650,6 +650,81 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
});
});
+ it("adds the user's servers and skill switches next to t3-code, and reopens when they change", () => {
+ const threadId = ThreadId.make("thread-claude-user-tools");
+ const session = {
+ environmentId: EnvironmentId.make(`environment-${threadId}`),
+ threadId,
+ providerSessionId: `mcp-session-${threadId}`,
+ providerInstanceId: ProviderInstanceId.make("claudeAgent"),
+ endpoint: "http://127.0.0.1:43123/mcp",
+ authorizationHeader: "Bearer secret-claude-token",
+ browserToolsAvailable: true,
+ };
+ McpProviderSession.setMcpProviderSession({
+ ...session,
+ tools: {
+ servers: [
+ {
+ name: "supabase",
+ transport: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "@supabase/mcp-server-supabase"],
+ env: [{ name: "SUPABASE_ACCESS_TOKEN", value: "token", sensitive: true }],
+ },
+ },
+ ],
+ disabledSkills: ["grill-me"],
+ fingerprint: "a",
+ },
+ });
+ try {
+ const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
+ ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: "/workspace",
+ }),
+ );
+ const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({
+ threadId,
+ readOnlySandbox: false,
+ });
+ assert.deepEqual(overrides, {
+ allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD, "mcp__supabase__*"],
+ mcpServers: {
+ supabase: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "@supabase/mcp-server-supabase"],
+ env: { SUPABASE_ACCESS_TOKEN: "token" },
+ },
+ ...T3_MCP_SERVERS,
+ },
+ sdkSettings: { skillOverrides: { "grill-me": "off" } },
+ });
+ // Read-only sandboxes keep the user's servers behind the permission prompt.
+ assert.deepEqual(
+ ClaudeAdapterV2.claudeMcpQueryOverrides({ threadId, readOnlySandbox: true }).allowedTools,
+ ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS,
+ );
+
+ const initialKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy, overrides);
+ McpProviderSession.setMcpProviderSession({
+ ...session,
+ tools: { servers: [], disabledSkills: [], fingerprint: "" },
+ });
+ const clearedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
+ queryPolicy,
+ ClaudeAdapterV2.claudeMcpQueryOverrides({ threadId, readOnlySandbox: false }),
+ );
+ assert.notEqual(clearedKey, initialKey);
+ } finally {
+ McpProviderSession.clearMcpProviderSession(threadId);
+ }
+ });
+
it("matches the read-only allowlist to the orchestrator toolkit annotations", () => {
const readOnlyToolNames = [
...Object.values(OrchestratorToolkit.tools),
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 1ad916ec2548b..2a24c8a46a545 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -41,6 +41,7 @@ import {
type ChatAttachment,
ClaudeSettings,
defaultInstanceIdForDriver,
+ mcpServerVariableRecord,
type ModelSelection,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
@@ -65,6 +66,7 @@ import {
type ProviderRequestKind,
type ProviderUserInputAnswers,
type ProviderThreadId,
+ type ResolvedMcpServer,
type ThreadId,
} from "@t3tools/contracts";
@@ -905,7 +907,7 @@ export function makeClaudeQueryOptions(input: {
preset: "claude_code" as const,
append:
buildRuntimeInstructions({ harness: "Claude Code" }) +
- (input.mcpServers === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS),
+ (input.mcpServers?.["t3-code"] === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS),
},
...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
};
@@ -964,17 +966,28 @@ export function claudeMcpQueryOverrides(input: {
}): {
readonly allowedTools?: ReadonlyArray;
readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
+ readonly sdkSettings?: ClaudeSdkSettings;
} {
const session = McpProviderSession.readMcpProviderSession(input.threadId);
if (session === undefined) {
return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };
}
+ const tools = session.tools ?? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS;
const mcpAllowedTools = input.readOnlySandbox
? CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS
: [CLAUDE_T3_MCP_TOOL_WILDCARD];
+ // Servers the user added in T3 are trusted like T3's own: their tools are
+ // pre-approved outside read-only sandboxes, where the permission prompt
+ // still decides.
+ const userAllowedTools = input.readOnlySandbox
+ ? []
+ : tools.servers.map((server) => `mcp__${server.name}__*`);
return {
- allowedTools: Array.from(new Set([...(input.allowedTools ?? []), ...mcpAllowedTools])),
+ allowedTools: Array.from(
+ new Set([...(input.allowedTools ?? []), ...mcpAllowedTools, ...userAllowedTools]),
+ ),
mcpServers: {
+ ...claudeUserMcpServers(tools.servers),
"t3-code": {
type: "http",
url: session.endpoint,
@@ -984,9 +997,43 @@ export function claudeMcpQueryOverrides(input: {
timeout: CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,
},
},
+ ...(tools.disabledSkills.length === 0
+ ? {}
+ : {
+ // The flag-settings layer outranks the user's and project's
+ // settings files, so an "off" here hides the skill from both the
+ // model and the slash menu whatever those files say.
+ sdkSettings: {
+ skillOverrides: Object.fromEntries(
+ tools.disabledSkills.map((name) => [name, "off" as const]),
+ ),
+ },
+ }),
};
}
+function claudeUserMcpServers(
+ servers: ReadonlyArray,
+): NonNullable {
+ return Object.fromEntries(
+ servers.map((server) => [
+ server.name,
+ server.transport.type === "stdio"
+ ? {
+ type: "stdio" as const,
+ command: server.transport.command,
+ args: [...server.transport.args],
+ env: mcpServerVariableRecord(server.transport.env),
+ }
+ : {
+ type: "http" as const,
+ url: server.transport.url,
+ headers: mcpServerVariableRecord(server.transport.headers),
+ },
+ ]),
+ );
+}
+
function providerSession(input: {
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
readonly providerInstanceId: ProviderInstanceId;
@@ -1613,6 +1660,7 @@ export function claudeEffectiveQueryPolicyKey(
mcpOverrides: {
readonly allowedTools?: ReadonlyArray;
readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
+ readonly sdkSettings?: ClaudeSdkSettings;
},
): string {
return JSON.stringify({
@@ -1623,6 +1671,8 @@ export function claudeEffectiveQueryPolicyKey(
: { allowedTools: mcpOverrides.allowedTools }),
}),
mcpServers: mcpOverrides.mcpServers,
+ // Skill switches load at process start, so a change reopens the query.
+ sdkSettings: mcpOverrides.sdkSettings,
});
}
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 602052f08ea78..138fe54b3acc7 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -690,6 +690,50 @@ describe("CodexAdapterV2 process spawning", () => {
}
});
+ it("adds the user's servers and disabled skills to thread config", () => {
+ const threadId = ThreadId.make("thread-codex-user-tools");
+ McpProviderSession.setMcpProviderSession({
+ environmentId: EnvironmentId.make("environment-codex-user-tools"),
+ threadId,
+ providerSessionId: "mcp-session-codex-user-tools",
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ endpoint: "http://127.0.0.1:43123/mcp",
+ authorizationHeader: "Bearer secret-codex-token",
+ browserToolsAvailable: true,
+ tools: {
+ servers: [
+ {
+ name: "linear",
+ transport: {
+ type: "http",
+ url: "https://mcp.linear.app/mcp",
+ headers: [{ name: "Authorization", value: "Bearer lin", sensitive: true }],
+ },
+ },
+ ],
+ disabledSkills: ["grill-me"],
+ fingerprint: "a",
+ },
+ });
+
+ try {
+ const { config } = CodexAdapterV2.codexThreadRuntimeParams({ threadId });
+ assert.deepEqual(config.mcp_servers, {
+ linear: {
+ url: "https://mcp.linear.app/mcp",
+ http_headers: { Authorization: "Bearer lin" },
+ },
+ "t3-code": {
+ url: "http://127.0.0.1:43123/mcp",
+ http_headers: { Authorization: "Bearer secret-codex-token" },
+ },
+ });
+ assert.deepEqual(config.skills, { config: [{ name: "grill-me", enabled: false }] });
+ } finally {
+ McpProviderSession.clearMcpProviderSession(threadId);
+ }
+ });
+
it.effect("resolves Windows command shims through the shared spawn policy", () =>
Effect.gen(function* () {
const command = yield* CodexAdapterV2.makeCodexAppServerSpawnCommand({
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index da0de5d48fc21..403cbec3b9e98 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -25,6 +25,7 @@ import {
CodexSettings,
defaultInstanceIdForDriver,
isOrchestrationV2WorkActive,
+ mcpServerVariableRecord,
OrchestrationV2ProviderGoal,
ProviderDriverKind,
type ProviderSetupError,
@@ -58,6 +59,7 @@ import type {
ProviderThreadId,
ProviderTurnId,
ProviderInstanceId,
+ ResolvedMcpServer,
RuntimeMode,
RuntimeRequestId,
ThreadId,
@@ -1327,6 +1329,7 @@ export function codexThreadRuntimeParams(input: {
} {
const mcpSession =
input.threadId === null ? undefined : McpProviderSession.readMcpProviderSession(input.threadId);
+ const tools = mcpSession?.tools ?? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS;
return {
...(input.runtimePolicy?.cwd == null ? {} : { cwd: input.runtimePolicy.cwd }),
...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }),
@@ -1336,6 +1339,7 @@ export function codexThreadRuntimeParams(input: {
? {}
: {
mcp_servers: {
+ ...codexUserMcpServers(tools.servers),
"t3-code": {
url: mcpSession.endpoint,
http_headers: {
@@ -1344,10 +1348,39 @@ export function codexThreadRuntimeParams(input: {
},
},
}),
+ // Thread config is Codex's session-flags layer, which its skill rules
+ // read alongside the user's config.toml; a later name rule wins.
+ ...(tools.disabledSkills.length === 0
+ ? {}
+ : {
+ skills: {
+ config: tools.disabledSkills.map((name) => ({ name, enabled: false })),
+ },
+ }),
},
};
}
+function codexUserMcpServers(
+ servers: ReadonlyArray,
+): Record {
+ return Object.fromEntries(
+ servers.map((server) => [
+ server.name,
+ server.transport.type === "stdio"
+ ? {
+ command: server.transport.command,
+ args: [...server.transport.args],
+ env: mcpServerVariableRecord(server.transport.env),
+ }
+ : {
+ url: server.transport.url,
+ http_headers: mcpServerVariableRecord(server.transport.headers),
+ },
+ ]),
+ );
+}
+
const decodeCodexResumeMetadata = Schema.decodeUnknownEffect(
Schema.Struct({ thread: Schema.Struct({ id: Schema.String, updatedAt: Schema.Number }) }),
);
diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts
index 5ade7c13911b0..bf4f61486c390 100644
--- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts
@@ -27,6 +27,7 @@ import {
type OrchestrationV2ProviderTurn,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
+ mcpServerVariableRecord,
type ProviderInstanceId,
type ThreadId,
} from "@t3tools/contracts";
@@ -207,7 +208,25 @@ export function cursorMcpServers(threadId: ThreadId): Record [
+ server.name,
+ server.transport.type === "stdio"
+ ? {
+ type: "stdio",
+ command: server.transport.command,
+ args: [...server.transport.args],
+ env: mcpServerVariableRecord(server.transport.env),
+ }
+ : {
+ type: "http",
+ url: server.transport.url,
+ headers: mcpServerVariableRecord(server.transport.headers),
+ },
+ ]),
+ ),
"t3-code": {
type: "http",
url: session.endpoint,
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts
index 102eb721bb1a6..9827c37c0de4d 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts
@@ -51,9 +51,11 @@ import {
type OrchestrationV2UserInputQuestion,
type ModelSelection,
type ProviderApprovalDecision,
+ mcpServerVariableRecord,
type ProviderInstanceId,
type RunId,
type RuntimeRequestId,
+ ThreadId,
} from "@t3tools/contracts";
import type * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
@@ -400,9 +402,17 @@ interface ThreadState {
mcp:
| { readonly name: string; readonly directory: string; readonly credential: string }
| undefined;
+ /** The user's servers from Settings → Tools as registered for this thread. */
+ userMcp: UserMcpRegistration | undefined;
instructions: string | undefined;
}
+interface UserMcpRegistration {
+ readonly names: ReadonlyArray;
+ readonly directory: string;
+ readonly fingerprint: string;
+}
+
type TurnTerminal =
| { readonly status: "completed" | "interrupted" }
| { readonly status: "failed"; readonly failure: ReturnType };
@@ -464,25 +474,49 @@ export const t3McpServerName = Effect.fn("t3McpServerName")(function* (threadId:
return `t3-code-${Hex.encode(digest).slice(0, 16)}`;
});
+/**
+ * The user's servers are registered per directory like T3's own, so each
+ * thread registers its own copies under `t3u--` (at most
+ * 61 characters, under OpenCode's 64) and its rules allow only those.
+ */
+export const userMcpServerPrefix = Effect.fn("userMcpServerPrefix")(function* (threadId: string) {
+ const crypto = yield* Crypto.Crypto;
+ const digest = yield* crypto
+ .digest("SHA-256", new TextEncoder().encode(threadId))
+ .pipe(Effect.orDie);
+ return `t3u-${Hex.encode(digest).slice(0, 8)}`;
+});
+
/**
* The rules that keep T3's MCP servers to their own thread, after the mode's:
* the last matching rule wins, so every thread's T3 server is denied and then
* this thread's own is allowed again, in every mode. A subagent's session
* inherits the thread's.
*/
-const mcpRules = (mcpServerName: string | null): ReadonlyArray =>
- mcpServerName === null
+const mcpRules = (
+ mcpServerName: string | null,
+ userMcpPrefix: string | null = null,
+): ReadonlyArray => [
+ ...(mcpServerName === null
+ ? []
+ : [
+ { action: "t3-code-*", resource: "*", effect: "deny" as const },
+ { action: `${mcpServerName}_*`, resource: "*", effect: "allow" as const },
+ ]),
+ ...(userMcpPrefix === null
? []
: [
- { action: "t3-code-*", resource: "*", effect: "deny" },
- { action: `${mcpServerName}_*`, resource: "*", effect: "allow" },
- ];
+ { action: "t3u-*", resource: "*", effect: "deny" as const },
+ { action: `${userMcpPrefix}-*`, resource: "*", effect: "allow" as const },
+ ]),
+];
const sessionRules = (
policy: RulesPolicy,
paths: ReadonlyArray,
grants: ReadonlyArray,
mcpServerName: string | null,
+ userMcpPrefix: string | null = null,
): ReadonlyArray => [
...(policy.runtimeMode === "full-access"
? [rule("*", "allow")]
@@ -496,7 +530,7 @@ const sessionRules = (
// are never denied: the free tier refuses sessions whose rules deny them.
...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []),
...paths,
- ...mcpRules(mcpServerName),
+ ...mcpRules(mcpServerName, userMcpPrefix),
];
const sameRules = (left: ReadonlyArray | undefined, right: ReadonlyArray) =>
@@ -836,6 +870,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
const driver = OPENCODE_PROVIDER;
const mcpServerNameFor = (threadId: string) =>
t3McpServerName(threadId).pipe(Effect.provideService(Crypto.Crypto, crypto));
+ const userMcpPrefixFor = (threadId: string) =>
+ userMcpServerPrefix(threadId).pipe(Effect.provideService(Crypto.Crypto, crypto));
/**
* Lends the instance's server to a session until its scope closes. A spawned
@@ -940,6 +976,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
stoppedChildren: new Set(),
strandedSteers: new Set(),
mcp: undefined,
+ userMcp: undefined,
instructions: undefined,
});
@@ -2841,7 +2878,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
currentScope = scope;
yield* Scope.close(previous, Exit.void);
// A restarted server forgot T3's MCP servers; the next turn adds them again.
- for (const state of threads.values()) state.mcp = undefined;
+ for (const state of threads.values()) {
+ state.mcp = undefined;
+ state.userMcp = undefined;
+ }
yield* lock.withPermit(reconcile).pipe(Effect.timeout(RECONCILE_TIMEOUT));
return stream;
}).pipe(
@@ -2984,11 +3024,18 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
policy.runtimeMode === "full-access" && !plan
? []
: yield* pathsFor(thread.directory, plan ? [thread.agent, "plan"] : [thread.agent]);
+ // Rules for the user's servers only exist once a thread has some, so a
+ // session without them keeps exactly the rules it always had.
+ const hasUserMcp =
+ appThreadId !== null &&
+ McpProviderSession.readMcpProviderSessionTools(ThreadId.make(appThreadId)).servers.length >
+ 0;
return sessionRules(
policy,
paths,
policy.runtimeMode === "full-access" ? [] : thread.grants,
appThreadId === null ? null : yield* mcpServerNameFor(appThreadId),
+ hasUserMcp ? yield* userMcpPrefixFor(appThreadId) : null,
);
});
@@ -3220,16 +3267,95 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
client.mcp.remove({ server: mcp.name, location: { directory: mcp.directory } }),
).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true }));
+ const removeUserMcp = (registration: UserMcpRegistration) =>
+ Effect.forEach(
+ registration.names,
+ (name) => removeMcp({ name, directory: registration.directory }),
+ { concurrency: 8, discard: true },
+ );
+
// T3's MCP registrations outlive a session only on an external server; a
// spawned one forgets them when it stops.
yield* Effect.addFinalizer(() =>
Effect.forEach(
- [...threads.values()].flatMap((state) => (state.mcp === undefined ? [] : [state.mcp])),
+ [...threads.values()].flatMap((state) => [
+ ...(state.mcp === undefined ? [] : [state.mcp]),
+ ...(state.userMcp === undefined
+ ? []
+ : state.userMcp.names.map((name) => ({
+ name,
+ directory: state.userMcp!.directory,
+ }))),
+ ]),
removeMcp,
{ concurrency: 8, discard: true },
),
);
+ /**
+ * Registers the thread's servers from Settings → Tools, replacing the
+ * previous set when the directory or the settings changed. Each server is
+ * optional: one OpenCode rejects is logged and the turn still runs.
+ */
+ const prepareUserMcp = Effect.fnUntraced(function* (
+ state: ThreadState,
+ threadId: ThreadId,
+ directory: string,
+ mcpSession: McpProviderSession.McpProviderSessionConfig | undefined,
+ ) {
+ const tools =
+ mcpSession === undefined || connection.external
+ ? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS
+ : (mcpSession.tools ?? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS);
+ const current = state.userMcp;
+ if (
+ current !== undefined &&
+ current.directory === directory &&
+ current.fingerprint === tools.fingerprint
+ ) {
+ return;
+ }
+ if (current !== undefined) {
+ yield* removeUserMcp(current);
+ state.userMcp = undefined;
+ }
+ if (tools.servers.length === 0) return;
+ const prefix = yield* userMcpPrefixFor(threadId);
+ const names: string[] = [];
+ for (const server of tools.servers) {
+ const name = `${prefix}-${server.name}`;
+ const added = yield* client.mcp
+ .add({
+ server: name,
+ location: { directory },
+ config:
+ server.transport.type === "stdio"
+ ? new Mcp.LocalConfig({
+ type: "local",
+ command: [server.transport.command, ...server.transport.args],
+ environment: mcpServerVariableRecord(server.transport.env),
+ })
+ : new Mcp.RemoteConfig({
+ type: "remote",
+ url: server.transport.url,
+ headers: mcpServerVariableRecord(server.transport.headers),
+ }),
+ })
+ .pipe(
+ Effect.timeout(INVENTORY_TIMEOUT),
+ Effect.as(true),
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Could not add an MCP server to OpenCode.", {
+ server: server.name,
+ cause,
+ }).pipe(Effect.as(false)),
+ ),
+ );
+ if (added) names.push(name);
+ }
+ state.userMcp = { names, directory, fingerprint: tools.fingerprint };
+ });
+
/**
* T3's MCP server for this thread, and the per-turn instructions. The MCP
* server is registered for the session's directory under the thread's own
@@ -3284,6 +3410,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
);
if (added) state.mcp = wanted;
}
+ yield* prepareUserMcp(state, turnInput.threadId, directory, mcpSession);
const instructions = [
buildRuntimeInstructions({ harness: "OpenCode", model: turnInput.modelSelection.model }),
t3OrchestrationSystemPrompt(state.mcp !== undefined),
@@ -4007,6 +4134,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
threads.delete(child);
}
if (state.mcp !== undefined) yield* removeMcp(state.mcp);
+ if (state.userMcp !== undefined) yield* removeUserMcp(state.userMcp);
}),
respondToRuntimeRequest: (requestInput) =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts
index 510a4c859d362..52a5eb9963604 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts
@@ -35,6 +35,7 @@ import {
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderSessionId,
+ mcpServerVariableRecord,
type RuntimeRequestId,
type ThreadId,
} from "@t3tools/contracts";
@@ -624,6 +625,20 @@ const OPENCODE_RESTRICTED_PERMISSIONS = [
*/
export function openCodePermissionRules(
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
+ disabledSkills: ReadonlyArray = [],
+): PermissionRuleset {
+ // Skills switched off in Settings → Tools; the last matching rule wins, so
+ // these follow every allow below.
+ const skillRules = disabledSkills.map((name) => ({
+ permission: "skill",
+ pattern: name,
+ action: "deny" as const,
+ }));
+ return [...openCodeRuntimePermissionRules(runtimePolicy), ...skillRules];
+}
+
+function openCodeRuntimePermissionRules(
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
): PermissionRuleset {
const sandboxPolicy = recordValue(runtimePolicy, "sandboxPolicy");
const sandboxType = recordString(sandboxPolicy, "type");
@@ -987,6 +1002,34 @@ export function makeOpenCodeAdapterV2(
},
}),
);
+ // The user's servers are additions: one that fails to register must
+ // not stop the session, so each logs and moves on.
+ for (const server of mcpSession.tools?.servers ?? []) {
+ yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
+ client.mcp.add({
+ name: server.name,
+ config:
+ server.transport.type === "stdio"
+ ? {
+ type: "local",
+ command: [server.transport.command, ...server.transport.args],
+ environment: mcpServerVariableRecord(server.transport.env),
+ }
+ : {
+ type: "remote",
+ url: server.transport.url,
+ headers: mcpServerVariableRecord(server.transport.headers),
+ },
+ }),
+ ).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Could not add an MCP server to OpenCode.", {
+ server: server.name,
+ cause,
+ }),
+ ),
+ );
+ }
}
const now = yield* DateTime.now;
@@ -3050,10 +3093,20 @@ export function makeOpenCodeAdapterV2(
// session.create leaves it unset (SessionPrompt.ensureTitle).
const response = yield* sdkCall(
"session.create",
- { permission: openCodePermissionRules(threadInput.runtimePolicy) },
+ {
+ permission: openCodePermissionRules(
+ threadInput.runtimePolicy,
+ McpProviderSession.readMcpProviderSessionTools(threadInput.threadId)
+ .disabledSkills,
+ ),
+ },
() =>
client.session.create({
- permission: openCodePermissionRules(threadInput.runtimePolicy),
+ permission: openCodePermissionRules(
+ threadInput.runtimePolicy,
+ McpProviderSession.readMcpProviderSessionTools(threadInput.threadId)
+ .disabledSkills,
+ ),
}),
);
const nativeSession = unwrapData("session.create", response);
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts
index d181497ec2754..643e252865d70 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts
@@ -41,6 +41,7 @@ import {
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as McpProviderSession from "../mcp/McpProviderSession.ts";
+import { resolveAgentTools } from "../mcp/resolveAgentTools.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
import * as EventSink from "./EventSink.ts";
@@ -355,7 +356,12 @@ export const layerWithOptions = (
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")(
function* (threadId: ThreadId) {
- if (Option.isNone(serverSettings)) return { browser: true, device: false };
+ if (Option.isNone(serverSettings))
+ return {
+ browser: true,
+ device: false,
+ tools: McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS,
+ };
return yield* Effect.gen(function* () {
const settings = yield* serverSettings.value.getSettings;
const thread = yield* projectionStore.getThread(threadId);
@@ -374,19 +380,27 @@ export const layerWithOptions = (
return {
browser: browserOverridden ? false : settings.enableAgentBrowserAccess,
device: deviceOverridden ? false : settings.enableAgentDeviceAccess,
+ tools: resolveAgentTools(settings, null),
};
}
const effective = resolveProjectSettings(settings, thread.projectId).settings;
return {
browser: effective.enableAgentBrowserAccess,
device: effective.enableAgentDeviceAccess,
+ tools: resolveAgentTools(settings, thread.projectId),
};
}).pipe(
Effect.catch((cause) =>
Effect.logWarning(
- "Could not resolve agent access; withholding browser and device tools.",
+ "Could not resolve agent access; withholding browser, device and user tools.",
{ threadId, cause },
- ).pipe(Effect.as({ browser: false, device: false })),
+ ).pipe(
+ Effect.as({
+ browser: false,
+ device: false,
+ tools: McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS,
+ }),
+ ),
),
);
},
@@ -482,8 +496,11 @@ export const layerWithOptions = (
// the credential it started with, so a thread that detaches and
// re-attaches across a workspace handoff must come back to the
// same token or the process's tool calls fail auth.
- const { browser: browserToolsAvailable, device: deviceToolsAvailable } =
- yield* agentAccessSettings(threadId);
+ const {
+ browser: browserToolsAvailable,
+ device: deviceToolsAvailable,
+ tools,
+ } = yield* agentAccessSettings(threadId);
const capabilities = new Set<
import("../mcp/McpInvocationContext.ts").McpCapability
>(["orchestration", "worktree", "pull-requests"]);
@@ -515,6 +532,9 @@ export const layerWithOptions = (
resolved.capabilities.has("preview") === browserToolsAvailable &&
resolved.capabilities.has("device") === deviceToolsAvailable
) {
+ // The credential stays; the user's tools are re-read on
+ // every prepare so a reopened process picks up an edit.
+ McpProviderSession.setMcpProviderSession({ ...existing, tools });
return { mcpCredentialId: existing.providerSessionId, issued: false };
}
dropMcpCredentialReservation(threadId, existing.providerSessionId);
@@ -526,7 +546,7 @@ export const layerWithOptions = (
browserToolsAvailable,
capabilities,
});
- McpProviderSession.setMcpProviderSession(credential.config);
+ McpProviderSession.setMcpProviderSession({ ...credential.config, tools });
reserveMcpCredential(threadId, credential.config.providerSessionId);
return { mcpCredentialId: credential.config.providerSessionId, issued: true };
}),
diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts
index 3ab2154b91fe6..5c1bb2bbc8e04 100644
--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts
+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts
@@ -2213,14 +2213,17 @@ export const make = (
initializeResult: EffectAcpSchema.InitializeResponse,
activationOptions?: AcpSessionActivationOptions,
): ReadonlyArray => {
+ const capabilities = initializeResult.agentCapabilities?.mcpCapabilities;
const acpServers = activationOptions?.acpMcpServers ?? options.acpMcpServers ?? [];
- if (
- initializeResult.agentCapabilities?.mcpCapabilities?.acp === true &&
- acpServers.length > 0
- ) {
- return acpServers;
- }
- return activationOptions?.mcpServers ?? options.mcpServers ?? [];
+ const selected =
+ capabilities?.acp === true && acpServers.length > 0
+ ? acpServers
+ : (activationOptions?.mcpServers ?? options.mcpServers ?? []);
+ // Stdio is the only transport every agent must accept; an agent that
+ // does not advertise http rejects the whole session over one entry.
+ return capabilities?.http === true
+ ? selected
+ : selected.filter((server) => !("type" in server) || server.type !== "http");
};
const startOnce = Effect.gen(function* () {
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index 051f053316136..41da2cf3b0561 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1714,6 +1714,74 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(layerServerSettingsWithSecrets())),
);
+ it.effect(
+ "keeps MCP server secrets in the secret store for the environment and each project",
+ () =>
+ Effect.gen(function* () {
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const projectId = ProjectId.make("project-mcp");
+ const stdio = (token: string) => ({
+ enabled: true,
+ transport: {
+ type: "stdio" as const,
+ command: "npx",
+ args: ["-y", "@supabase/mcp-server-supabase"],
+ env: [
+ { name: "SUPABASE_ACCESS_TOKEN", value: token, sensitive: true },
+ { name: "READ_ONLY", value: "true", sensitive: false },
+ ],
+ },
+ });
+
+ const saved = yield* serverSettings.updateSettings({
+ mcpServers: { supabase: stdio("env-token") },
+ projectSettingsOverrides: {
+ [projectId]: { mcpServers: { supabase: stdio("project-token") } },
+ },
+ });
+ // The server reads real values.
+ const envVars = (settings: typeof saved, scope: "env" | "project") => {
+ const server =
+ scope === "env"
+ ? settings.mcpServers.supabase
+ : settings.projectSettingsOverrides[projectId]?.mcpServers?.supabase;
+ return server?.transport?.type === "stdio" ? server.transport.env : [];
+ };
+ assert.equal(envVars(saved, "env")[0]?.value, "env-token");
+ assert.equal(envVars(saved, "project")[0]?.value, "project-token");
+
+ // Neither the file nor a client sees them; plain values stay readable.
+ const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
+ assert.notInclude(raw, "env-token");
+ assert.notInclude(raw, "project-token");
+ const forClient = ServerSettingsModule.redactServerSettingsForClient(saved);
+ assert.deepEqual(envVars(forClient, "env"), [
+ { name: "SUPABASE_ACCESS_TOKEN", value: "", sensitive: true, valueRedacted: true },
+ { name: "READ_ONLY", value: "true", sensitive: false },
+ ]);
+ assert.equal(envVars(forClient, "project")[0]?.value, "");
+
+ // Echoing the redacted server back (an edit that changed only args) keeps its secret.
+ const echoed = forClient.mcpServers.supabase!;
+ yield* serverSettings.updateSettings({
+ mcpServers: {
+ supabase: {
+ ...echoed,
+ transport: { ...echoed.transport, args: ["--read-only"] } as never,
+ },
+ },
+ });
+ assert.equal(envVars(yield* serverSettings.getSettings, "env")[0]?.value, "env-token");
+
+ // Removing the environment server drops its secret, not the project's.
+ const removed = yield* serverSettings.updateSettings({ mcpServers: { supabase: null } });
+ assert.isUndefined(removed.mcpServers.supabase);
+ assert.equal(envVars(removed, "project")[0]?.value, "project-token");
+ }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
+ );
+
it.effect("removes a Bitbucket secret once its token is cleared by hand in settings.json", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 7cbcd895ac140..bfd51701cc048 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -62,6 +62,12 @@ import {
isModelSelectionProviderEnabled,
} from "@t3tools/shared/serverSettings";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
+import {
+ materializeMcpServerSecrets,
+ mcpServerSecretNames,
+ planMcpServerSecrets,
+ redactMcpServerSecrets,
+} from "./mcpServerSecrets.ts";
export { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
@@ -215,7 +221,13 @@ export function redactServerSettingsForClient(settings: ServerSettings): ServerS
Object.entries(settings.github.tokens).map(([host, token]) => [host, redactSecret(token)]),
),
};
- return { ...settings, providerInstances, usageLimitSources, bitbucket, github };
+ return redactMcpServerSecrets({
+ ...settings,
+ providerInstances,
+ usageLimitSources,
+ bitbucket,
+ github,
+ });
}
export function applyProviderInstanceMutation(
@@ -925,13 +937,27 @@ const make = Effect.gen(function* () {
);
tokens[host] = Option.isSome(secret) ? textDecoder.decode(secret.value) : "";
}
- return {
- ...settings,
- providerInstances: providerInstances as ServerSettings["providerInstances"],
- usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
- bitbucket,
- github: { ...settings.github, tokens },
- };
+ const mcpSecrets = new Map();
+ for (const secretName of mcpServerSecretNames(settings)) {
+ const secret = yield* secretStore
+ .get(secretName)
+ .pipe(
+ Effect.mapError(
+ (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
+ ),
+ );
+ if (Option.isSome(secret)) mcpSecrets.set(secretName, textDecoder.decode(secret.value));
+ }
+ return materializeMcpServerSecrets(
+ {
+ ...settings,
+ providerInstances: providerInstances as ServerSettings["providerInstances"],
+ usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
+ bitbucket,
+ github: { ...settings.github, tokens },
+ },
+ mcpSecrets,
+ );
});
const materializeChanges = (changes: Stream.Stream) =>
@@ -1124,9 +1150,22 @@ const make = Effect.gen(function* () {
});
}
+ const mcp = planMcpServerSecrets(current, next);
+ for (const change of mcp.changes) {
+ changes.push(
+ change.kind === "write"
+ ? {
+ kind: "write",
+ secretName: change.secretName,
+ value: textEncoder.encode(change.value),
+ }
+ : { kind: "remove", secretName: change.secretName, operation: "remove-secret" },
+ );
+ }
+
return {
settings: {
- ...next,
+ ...mcp.settings,
providerInstances: providerInstances as ServerSettings["providerInstances"],
usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
bitbucket,
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 6a021ef7e5e2e..61abcbf14d391 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -11604,6 +11604,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
+ skillsProjectId={activeProject?.id ?? null}
pullRequestProjectId={
supportsPullRequests ? (activeProject?.id ?? null) : null
}
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index c7eb2628e1c9a..b385275d65149 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -1132,6 +1132,7 @@ import {
resolveProviderSkillsForCwd,
resolveProviderSlashCommandsForCwd,
} from "@t3tools/client-runtime/providerSkills";
+import { mergeProjectDisabledSkills } from "@t3tools/shared/projectSettings";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useDelayedStatus } from "../../hooks/useDelayedStatus";
import { useMediaQuery } from "../../hooks/useMediaQuery";
@@ -1615,6 +1616,8 @@ export interface ChatComposerProps {
keybindings: ResolvedKeybindingsConfig;
terminalOpen: boolean;
gitCwd: string | null;
+ /** The thread's project, for its Settings → Tools skill switches. */
+ skillsProjectId: ProjectId | null;
pullRequestProjectId: ProjectId | null;
pullRequestRepository: string | null;
restingControlsHost: HTMLDivElement | null;
@@ -1760,6 +1763,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
keybindings,
terminalOpen,
gitCwd,
+ skillsProjectId,
pullRequestProjectId,
pullRequestRepository,
restingControlsHost,
@@ -2193,11 +2197,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry);
// Memoized so the composer menu memo below can cache between renders.
- const selectedProviderSkills = useMemo(
- () =>
- selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd) : [],
- [gitCwd, selectedProviderStatus],
- );
+ // Skills switched off in Settings → Tools leave the menu; the server keeps
+ // them out of the session where the provider allows it.
+ const disabledSkillNames = useMemo(() => {
+ const disabled = mergeProjectDisabledSkills(
+ settings.disabledSkills,
+ skillsProjectId === null
+ ? undefined
+ : settings.projectSettingsOverrides[skillsProjectId]?.disabledSkills,
+ );
+ return new Set(disabled.map((name) => name.toLowerCase()));
+ }, [settings.disabledSkills, settings.projectSettingsOverrides, skillsProjectId]);
+ const selectedProviderSkills = useMemo(() => {
+ const skills = selectedProviderStatus
+ ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd)
+ : [];
+ return disabledSkillNames.size === 0
+ ? skills
+ : skills.filter((skill) => !disabledSkillNames.has(skill.name.toLowerCase()));
+ }, [disabledSkillNames, gitCwd, selectedProviderStatus]);
const selectedProviderSlashCommands = useMemo(
() =>
selectedProviderStatus
diff --git a/apps/web/src/components/settings/McpServerDialog.tsx b/apps/web/src/components/settings/McpServerDialog.tsx
new file mode 100644
index 0000000000000..115cf09485eeb
--- /dev/null
+++ b/apps/web/src/components/settings/McpServerDialog.tsx
@@ -0,0 +1,331 @@
+import type { McpServerConfig, McpServerTransport } from "@t3tools/contracts";
+import { LockIcon, LockOpenIcon, PlusIcon, XIcon } from "lucide-react";
+import { useId, useState } from "react";
+
+import { Button } from "../ui/button";
+import {
+ Dialog,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogPanel,
+ DialogPopup,
+ DialogTitle,
+} from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Label } from "../ui/label";
+import { Textarea } from "../ui/textarea";
+import { Toggle, ToggleGroup } from "../ui/toggle-group";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import {
+ EMPTY_MCP_SERVER_DRAFT,
+ mcpServerDraftFrom,
+ type McpServerDraft,
+ mcpServerFromDraft,
+ type McpVariableDraft,
+ nextMcpVariableDraftId,
+ parseMcpServerJson,
+} from "./toolsSettings.logic";
+
+/**
+ * Add or edit one MCP server. Pasting the JSON snippet from a vendor's docs
+ * fills the form; secrets in env vars and headers default to sensitive, so
+ * they are stored on the environment's secret store and never sent back.
+ */
+export function McpServerDialog({
+ open,
+ onOpenChange,
+ scopeLabel,
+ initial,
+ takenNames,
+ onSave,
+}: {
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+ /** Where the server is saved, e.g. "This Mac" or a project name. */
+ readonly scopeLabel: string;
+ readonly initial: { readonly name: string; readonly config: McpServerConfig } | null;
+ readonly takenNames: ReadonlySet;
+ readonly onSave: (server: { name: string; transport: McpServerTransport }) => void;
+}) {
+ const id = useId();
+ const [draft, setDraft] = useState(() =>
+ initial ? mcpServerDraftFrom(initial.name, initial.config) : EMPTY_MCP_SERVER_DRAFT,
+ );
+ const [paste, setPaste] = useState("");
+ const [pasteError, setPasteError] = useState(false);
+ const [attempted, setAttempted] = useState(false);
+ const result = mcpServerFromDraft(draft, takenNames);
+ const error = attempted && !result.ok ? result : null;
+
+ const update = (patch: Partial) =>
+ setDraft((current) => ({ ...current, ...patch }));
+ const variablesKey = draft.type === "stdio" ? "env" : "headers";
+ const variables = draft[variablesKey];
+ const setVariables = (next: ReadonlyArray) => update({ [variablesKey]: next });
+
+ const applyPaste = (text: string) => {
+ setPaste(text);
+ if (text.trim().length === 0) {
+ setPasteError(false);
+ return;
+ }
+ const parsed = parseMcpServerJson(text);
+ setPasteError(parsed === null);
+ if (parsed !== null) {
+ setDraft((current) => ({ ...parsed, name: parsed.name || current.name }));
+ }
+ };
+
+ const save = () => {
+ setAttempted(true);
+ if (!result.ok) return;
+ onSave({ name: result.name, transport: result.transport });
+ };
+
+ return (
+
+
+
+ {initial ? `Edit ${initial.name}` : "Add MCP server"}
+
+ Saved for {scopeLabel}. Agents get it in their next session.
+
+
+
+
+
+
+ onOpenChange(false)}>
+ Cancel
+
+ {initial ? "Save" : "Add server"}
+
+
+
+ );
+}
+
+function VariablesEditor({
+ label,
+ namePlaceholder,
+ variables,
+ onChange,
+}: {
+ readonly label: string;
+ readonly namePlaceholder: string;
+ readonly variables: ReadonlyArray;
+ readonly onChange: (next: ReadonlyArray) => void;
+}) {
+ const update = (id: string, patch: Partial) =>
+ onChange(
+ variables.map((variable) =>
+ variable.id === id
+ ? {
+ ...variable,
+ ...patch,
+ // Typing a value replaces a stored secret.
+ ...(patch.value !== undefined ? { stored: false } : {}),
+ }
+ : variable,
+ ),
+ );
+ return (
+
+
+
{label}
+
+ onChange([
+ ...variables,
+ { id: nextMcpVariableDraftId(), name: "", value: "", sensitive: true, stored: false },
+ ])
+ }
+ >
+
+ Add
+
+
+ {variables.length === 0 ? null : (
+
+ )}
+
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index 048e19b7a6b51..9ddc9010cb796 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -23,6 +23,7 @@ import {
PaletteIcon,
SearchIcon,
Settings2Icon,
+ WrenchIcon,
XIcon,
} from "lucide-react";
import { useLocation, useNavigate } from "@tanstack/react-router";
@@ -83,6 +84,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/keybindings": KeyboardIcon,
"/settings/snap-shot": SnapShotIcon,
"/settings/providers": BotIcon,
+ "/settings/tools": WrenchIcon,
"/settings/integrations": BlocksIcon,
"/settings/scheduled-tasks": CalendarClockIcon,
"/settings/source-control": GitBranchIcon,
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
new file mode 100644
index 0000000000000..e79e2546d2ac5
--- /dev/null
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -0,0 +1,717 @@
+import {
+ AuthProvidersManageScope,
+ type EnvironmentId,
+ mcpServerTransportSummary,
+ type McpServerConfig,
+ type McpServerProjectOverride,
+ type McpServerTransport,
+ type ProjectId,
+ type ServerProvider,
+ type ServerSettingsPatch,
+} from "@t3tools/contracts";
+import { useAtomValue } from "@effect/atom-react";
+import { MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+
+import { serverEnvironment } from "../../state/server";
+import { useEnvironmentsWithScope } from "../../state/session";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogPopup,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
+import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
+import { Switch } from "../ui/switch";
+import { Toggle, ToggleGroup } from "../ui/toggle-group";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { McpServerDialog } from "./McpServerDialog";
+import { useSettingsScope } from "./SettingsScopeContext";
+import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
+import { searchableSetting } from "./settingsSearch";
+import {
+ collectSkillRows,
+ filterSkillRows,
+ groupSkillRows,
+ isSkillDisabled,
+ listMcpServerRows,
+ type McpServerRow,
+ SKILL_GROUP_LABELS,
+ skillReachesSomeProviders,
+ type SkillRow,
+ type ToolsTab,
+ withSkillDisabled,
+} from "./toolsSettings.logic";
+import { useScopedSettings, useScopedSettingsWriteAllowed } from "./useScopedSettings";
+
+const EMPTY_PROVIDERS: ReadonlyArray = [];
+
+interface ToolsTarget {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly projectId: ProjectId | null;
+ readonly cwd: string | null;
+}
+
+/**
+ * The environments and project checkouts a Tools change writes to. Project
+ * scope writes the project's override on each member's environment, so one
+ * edit reaches the project everywhere it is checked out.
+ */
+function useToolsTargets(): ReadonlyArray {
+ const { scope, connectedEnvironments } = useSettingsScope();
+ return useMemo(() => {
+ const connected = new Map(
+ connectedEnvironments.map((environment) => [environment.environmentId, environment]),
+ );
+ if (scope.kind === "project" || scope.kind === "checkout") {
+ return scope.members.flatMap((member) => {
+ const environment = connected.get(member.environmentId);
+ return environment
+ ? [
+ {
+ environmentId: member.environmentId,
+ label: environment.label,
+ projectId: member.id,
+ cwd: member.workspaceRoot,
+ },
+ ]
+ : [];
+ });
+ }
+ return connectedEnvironments.map((environment) => ({
+ environmentId: environment.environmentId,
+ label: environment.label,
+ projectId: null,
+ cwd: null,
+ }));
+ }, [connectedEnvironments, scope]);
+}
+
+/**
+ * Write a Tools change to every target. `apply` receives the target's raw
+ * environment settings and returns its patch: the environment's own key at
+ * environment scope, or the project's override entry at project scope.
+ */
+function usePersistToolsPatch() {
+ const targets = useToolsTargets();
+ const { connectedEnvironments } = useSettingsScope();
+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
+ label: "update tools",
+ });
+ return useCallback(
+ (
+ apply: (input: {
+ readonly settings: NonNullable<
+ (typeof connectedEnvironments)[number]["serverConfig"]
+ >["settings"];
+ readonly projectId: ProjectId | null;
+ }) => ServerSettingsPatch | null,
+ ) => {
+ for (const target of targets) {
+ const settings = connectedEnvironments.find(
+ (environment) => environment.environmentId === target.environmentId,
+ )?.serverConfig?.settings;
+ if (!settings) continue;
+ const patch = apply({ settings, projectId: target.projectId });
+ if (patch === null) continue;
+ void updateSettings({ environmentId: target.environmentId, input: { patch } });
+ }
+ },
+ [connectedEnvironments, targets, updateSettings],
+ );
+}
+
+/** Replace one key of a project's override entry, dropping the key (or the entry) when empty. */
+function projectOverridePatch(
+ settings: {
+ readonly projectSettingsOverrides: Readonly>>;
+ },
+ projectId: ProjectId,
+ key: K,
+ value: Readonly>,
+): ServerSettingsPatch {
+ const { [key]: _previous, ...rest } = settings.projectSettingsOverrides[projectId] ?? {};
+ const next = Object.keys(value).length === 0 ? rest : { ...rest, [key]: value };
+ return {
+ projectSettingsOverrides: {
+ [projectId]: Object.keys(next).length === 0 ? null : next,
+ },
+ } as ServerSettingsPatch;
+}
+
+export function ToolsSettings({
+ tab = "skills",
+ onTabChange,
+}: {
+ readonly tab?: ToolsTab;
+ readonly onTabChange: (tab: ToolsTab) => void;
+}) {
+ const selectTab = onTabChange;
+ return (
+
+
+ {
+ const value = next[0];
+ if (value === "skills" || value === "mcp") selectTab(value);
+ }}
+ >
+ Skills
+ MCP servers
+
+
+ {tab === "mcp" ? : }
+
+ );
+}
+
+// ── Skills ───────────────────────────────────────────────────────────
+
+function SkillsPanel() {
+ const { scope, target } = useSettingsScope();
+ const environmentId = target?.environmentId ?? null;
+ const targets = useToolsTargets();
+ const cwd = targets.find((candidate) => candidate.environmentId === environmentId)?.cwd ?? null;
+ const providers =
+ useAtomValue(serverEnvironment.providersValueAtom(environmentId ?? ("" as EnvironmentId))) ??
+ EMPTY_PROVIDERS;
+ const disabledSkills = useScopedSettings((settings) => settings.disabledSkills);
+ const canWrite = useScopedSettingsWriteAllowed();
+ const persist = usePersistToolsPatch();
+ const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
+ reportFailure: false,
+ });
+ const [query, setQuery] = useState("");
+ const [refreshing, setRefreshing] = useState(false);
+ const enabledProviders = useMemo(
+ () => providers.filter((provider) => provider.enabled),
+ [providers],
+ );
+ const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
+
+ const refresh = async (fresh: boolean) => {
+ if (environmentId === null) return;
+ setRefreshing(true);
+ try {
+ await Promise.all(
+ enabledProviders.map((provider) =>
+ refreshProviders({
+ environmentId,
+ input: {
+ instanceId: provider.instanceId,
+ ...(cwd === null ? {} : { cwd }),
+ ...(fresh ? { fresh: true } : {}),
+ },
+ }),
+ ),
+ );
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ // A project's skills live in its checkout, which each provider only scans
+ // when asked; the composer does the same before showing its skill menu.
+ // Keyed on the checkout and provider set, not on every status push, which
+ // would rescan each time the scan's own result arrives.
+ const scanKey = `${environmentId}:${cwd}:${enabledProviders.map((provider) => provider.instanceId).join(",")}`;
+ const scannedKeyRef = useRef(null);
+ useEffect(() => {
+ if (cwd === null || scannedKeyRef.current === scanKey) return;
+ scannedKeyRef.current = scanKey;
+ void refresh(false);
+ }, [cwd, refresh, scanKey]);
+
+ const rows = useMemo(() => collectSkillRows(providers, cwd), [cwd, providers]);
+ const groups = useMemo(() => groupSkillRows(filterSkillRows(rows, query)), [query, rows]);
+
+ const setSkillDisabled = (name: string, disabled: boolean) =>
+ persist(({ settings, projectId }) => {
+ if (projectId === null) {
+ return { disabledSkills: [...withSkillDisabled(settings.disabledSkills, name, disabled)] };
+ }
+ const switches = { ...settings.projectSettingsOverrides[projectId]?.disabledSkills };
+ const inheritedOff = isSkillDisabled(settings.disabledSkills, name);
+ delete switches[name];
+ // A switch that matches the environment is not an override.
+ if (disabled !== inheritedOff) switches[name] = disabled;
+ return projectOverridePatch(settings, projectId, "disabledSkills", switches);
+ });
+
+ return (
+ <>
+
+
+
+
+
+
+ setQuery(event.target.value)}
+ aria-label="Filter skills"
+ />
+
+
+ void refresh(true)}
+ />
+ }
+ >
+
+
+ Rescan skill folders
+
+
+
+ {rows.length === 0 ? (
+
+
+
+ ) : groups.length === 0 ? (
+
+
+
+ ) : (
+ groups.map(({ group, rows: groupRows }) => (
+
+ {groupRows.map((row) => (
+
+ candidate.projectId !== null &&
+ Object.hasOwn(
+ target?.settings.projectSettingsOverrides[candidate.projectId]
+ ?.disabledSkills ?? {},
+ row.name,
+ ),
+ )
+ }
+ showProviders={skillReachesSomeProviders(row, enabledProviders.length)}
+ canWrite={canWrite}
+ onChange={(enabled) => setSkillDisabled(row.name, !enabled)}
+ />
+ ))}
+
+ ))
+ )}
+
+ Turning a skill off hides it from Claude, Codex and OpenCode, and from the composer's skill
+ menu. Other agents may still load it on their own. Changes apply to new sessions.
+
+ >
+ );
+}
+
+function SkillSettingsRow({
+ row,
+ disabled,
+ overridden,
+ showProviders,
+ canWrite,
+ onChange,
+}: {
+ readonly row: SkillRow;
+ readonly disabled: boolean;
+ readonly overridden: boolean;
+ readonly showProviders: boolean;
+ readonly canWrite: boolean;
+ readonly onChange: (enabled: boolean) => void;
+}) {
+ const lockedOff = row.disabledByProvider;
+ return (
+
+ {row.name}
+ {overridden ? (
+
+ This project
+
+ ) : null}
+
+ }
+ description={
+ lockedOff
+ ? "Turned off in the agent's own settings."
+ : (row.description ?? row.paths[0] ?? undefined)
+ }
+ className={disabled || lockedOff ? "[&_h3]:text-muted-foreground" : undefined}
+ control={
+ <>
+ {showProviders ? (
+
+ {row.providers.map((provider) => (
+
+ }>
+
+
+ {provider.displayName}
+
+ ))}
+
+ ) : null}
+
+ >
+ }
+ />
+ );
+}
+
+// ── MCP servers ──────────────────────────────────────────────────────
+
+type ServerEditor =
+ | { readonly mode: "add" }
+ | { readonly mode: "edit"; readonly row: McpServerRow };
+
+function McpServersPanel() {
+ const { scope, target, connectedEnvironments } = useSettingsScope();
+ const targets = useToolsTargets();
+ const persist = usePersistToolsPatch();
+ const canWriteSettings = useScopedSettingsWriteAllowed();
+ const managers = useEnvironmentsWithScope(connectedEnvironments, AuthProvidersManageScope);
+ const canManageServers =
+ connectedEnvironments.length > 0 &&
+ connectedEnvironments.every((environment) => managers.has(environment.environmentId));
+ const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
+ const projectId = isProjectScope ? (target?.projectId ?? null) : null;
+ const environmentSettings = target
+ ? connectedEnvironments.find(
+ (environment) => environment.environmentId === target.environmentId,
+ )?.serverConfig?.settings
+ : undefined;
+ const rows = useMemo(
+ () =>
+ listMcpServerRows({
+ environment: environmentSettings?.mcpServers ?? {},
+ project:
+ projectId === null
+ ? null
+ : (environmentSettings?.projectSettingsOverrides[projectId]?.mcpServers ?? {}),
+ }),
+ [environmentSettings, projectId],
+ );
+ const [editor, setEditor] = useState(null);
+ const [removing, setRemoving] = useState(null);
+ const scopeLabel = isProjectScope
+ ? scope.kind === "project" || scope.kind === "checkout"
+ ? scope.group.displayName
+ : ""
+ : scope.kind === "environment"
+ ? scope.label
+ : "every environment";
+
+ const writeServer = (
+ name: string,
+ transport: McpServerTransport,
+ enabled: boolean,
+ previousName?: string,
+ ) =>
+ persist(({ settings, projectId: targetProject }) => {
+ if (targetProject === null) {
+ return {
+ mcpServers: {
+ ...(previousName !== undefined && previousName !== name
+ ? { [previousName]: null }
+ : {}),
+ [name]: { enabled, transport },
+ },
+ };
+ }
+ const entries: Record = {
+ ...settings.projectSettingsOverrides[targetProject]?.mcpServers,
+ };
+ if (previousName !== undefined && previousName !== name) delete entries[previousName];
+ entries[name] = { enabled, transport };
+ return projectOverridePatch(settings, targetProject, "mcpServers", entries);
+ });
+
+ const setEnabled = (row: McpServerRow, enabled: boolean) =>
+ persist(({ settings, projectId: targetProject }) => {
+ if (targetProject === null) {
+ const current = settings.mcpServers[row.name];
+ return current ? { mcpServers: { [row.name]: { ...current, enabled } } } : null;
+ }
+ const entries: Record = {
+ ...settings.projectSettingsOverrides[targetProject]?.mcpServers,
+ };
+ const own = entries[row.name];
+ const inherited = settings.mcpServers[row.name];
+ if (own?.transport !== undefined) {
+ entries[row.name] = { ...own, enabled };
+ } else if (inherited !== undefined && inherited.enabled === enabled) {
+ // Back to the environment's value: no override needed.
+ delete entries[row.name];
+ } else {
+ entries[row.name] = { enabled };
+ }
+ return projectOverridePatch(settings, targetProject, "mcpServers", entries);
+ });
+
+ const remove = (row: McpServerRow) =>
+ persist(({ settings, projectId: targetProject }) => {
+ if (targetProject === null) return { mcpServers: { [row.name]: null } };
+ const entries: Record = {
+ ...settings.projectSettingsOverrides[targetProject]?.mcpServers,
+ };
+ delete entries[row.name];
+ return projectOverridePatch(settings, targetProject, "mcpServers", entries);
+ });
+
+ const resetSwitch = (row: McpServerRow) =>
+ persist(({ settings, projectId: targetProject }) => {
+ if (targetProject === null) return null;
+ const entries: Record = {
+ ...settings.projectSettingsOverrides[targetProject]?.mcpServers,
+ };
+ delete entries[row.name];
+ return projectOverridePatch(settings, targetProject, "mcpServers", entries);
+ });
+
+ const ownRows = isProjectScope ? rows.filter((row) => row.origin === "project") : rows;
+ const inheritedRows = isProjectScope ? rows.filter((row) => row.origin !== "project") : [];
+ const canEditServers = canWriteSettings && canManageServers && targets.length > 0;
+
+ return (
+ <>
+ setEditor({ mode: "add" })}>
+
+ Add server
+
+ ) : null
+ }
+ >
+ {ownRows.length === 0 ? (
+
+ ) : (
+ ownRows.map((row) => (
+ setEnabled(row, enabled)}
+ onEdit={() => setEditor({ mode: "edit", row })}
+ onRemove={() => setRemoving(row)}
+ />
+ ))
+ )}
+
+ {isProjectScope && inheritedRows.length > 0 ? (
+
+ {inheritedRows.map((row) => (
+ setEnabled(row, enabled)}
+ {...(row.origin === "project-switch" ? { onReset: () => resetSwitch(row) } : {})}
+ />
+ ))}
+
+ ) : null}
+ {!canManageServers && connectedEnvironments.length > 0 ? (
+
+ Adding or editing servers needs permission to manage providers on this environment.
+
+ ) : (
+
+ Servers you add here are given to Claude, Codex, Cursor, OpenCode, Grok and other ACP
+ agents. Pi isn't supported yet. Changes apply to new sessions; use Restart agent session
+ to pick them up in an open thread.
+
+ )}
+ {editor ? (
+ {
+ if (!open) setEditor(null);
+ }}
+ scopeLabel={scopeLabel}
+ initial={
+ editor.mode === "edit" ? { name: editor.row.name, config: editor.row.config } : null
+ }
+ takenNames={
+ new Set(
+ rows
+ .filter((row) => editor.mode === "add" || row.name !== editor.row.name)
+ .filter((row) => !isProjectScope || row.origin === "project")
+ .map((row) => row.name),
+ )
+ }
+ onSave={({ name, transport }) => {
+ writeServer(
+ name,
+ transport,
+ editor.mode === "edit" ? editor.row.config.enabled : true,
+ editor.mode === "edit" ? editor.row.name : undefined,
+ );
+ setEditor(null);
+ }}
+ />
+ ) : null}
+ !open && setRemoving(null)}>
+
+
+ Remove {removing?.name}?
+
+ New agent sessions stop getting this server, and its stored secrets are deleted.
+
+
+
+ }>Cancel
+ {
+ if (removing) remove(removing);
+ setRemoving(null);
+ }}
+ >
+ Remove
+
+
+
+
+ >
+ );
+}
+
+function McpServerSettingsRow({
+ row,
+ canSwitch,
+ canEdit,
+ onEnabledChange,
+ onEdit,
+ onRemove,
+ onReset,
+}: {
+ readonly row: McpServerRow;
+ readonly canSwitch: boolean;
+ readonly canEdit: boolean;
+ readonly onEnabledChange: (enabled: boolean) => void;
+ readonly onEdit?: () => void;
+ readonly onRemove?: () => void;
+ readonly onReset?: () => void;
+}) {
+ const transport = row.config.transport;
+ return (
+
+ {row.name}
+
+ {transport.type === "stdio" ? "Command" : "URL"}
+
+ {row.replacesEnvironment ? (
+
+ Replaces environment's
+
+ ) : null}
+ {row.origin === "project-switch" ? (
+
+ {row.config.enabled ? "On" : "Off"} for this project
+
+ ) : null}
+
+ }
+ description={
+ {mcpServerTransportSummary(transport)}
+ }
+ className={row.config.enabled ? undefined : "[&_h3]:text-muted-foreground"}
+ control={
+ <>
+ {onReset ? (
+
+ Reset
+
+ ) : null}
+ {canEdit && onEdit && onRemove ? (
+
+
+ }
+ >
+
+
+
+ Edit
+
+ Remove
+
+
+
+ ) : null}
+
+ >
+ }
+ />
+ );
+}
+
+export type { McpServerConfig };
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 853886d81fcd9..21253e922b512 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -18,6 +18,7 @@ export type SettingsPath =
| "/settings/keybindings"
| "/settings/snap-shot"
| "/settings/providers"
+ | "/settings/tools"
| "/settings/integrations"
| "/settings/scheduled-tasks"
| "/settings/source-control"
@@ -93,6 +94,7 @@ export const SETTINGS_SECTION_LABELS: Readonly> = {
"/settings/keybindings": "Keybindings",
"/settings/snap-shot": "SnapShots",
"/settings/providers": "Providers",
+ "/settings/tools": "Tools",
"/settings/integrations": "Integrations",
"/settings/scheduled-tasks": "Scheduled Tasks",
"/settings/source-control": "Source Control",
@@ -623,6 +625,24 @@ export const SETTINGS_SEARCH_ITEMS = [
searchTerms: ["refresh availability versions auth state models background probes seconds off"],
providerSettingsOnly: true,
},
+ {
+ id: "tools-skills",
+ title: "Skills",
+ to: "/settings/tools",
+ scope: "project-defaults",
+ searchTerms: [
+ "agent skills SKILL.md disable enable hide turn off slash commands .agents claude codex cursor",
+ ],
+ },
+ {
+ id: "tools-mcp-servers",
+ title: "MCP servers",
+ to: "/settings/tools",
+ scope: "project-defaults",
+ searchTerms: [
+ "model context protocol mcp add server command url stdio http headers env tools agents",
+ ],
+ },
{
id: "agent-browser-access",
title: "Agent browser access",
@@ -936,6 +956,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly = {},
+): ServerProvider =>
+ ({
+ instanceId: ProviderInstanceId.make(instanceId),
+ driver: ProviderDriverKind.make(instanceId),
+ enabled: true,
+ skills,
+ ...extra,
+ }) as ServerProvider;
+
+describe("collectSkillRows", () => {
+ it("merges one skill across providers and folders, grouped by its most specific location", () => {
+ const rows = collectSkillRows(
+ [
+ provider("claudeAgent", [
+ {
+ name: "frontend-design",
+ path: "/home/me/.claude/skills/frontend-design/SKILL.md",
+ scope: "user",
+ enabled: true,
+ },
+ ]),
+ provider("codex", [
+ {
+ name: "frontend-design",
+ path: "/home/me/.agents/skills/frontend-design/SKILL.md",
+ scope: "user",
+ enabled: true,
+ },
+ {
+ name: "test-t3-app",
+ path: "/work/t3/.agents/skills/test-t3-app/SKILL.md",
+ scope: "repo",
+ enabled: true,
+ },
+ ]),
+ provider("cursor", [], { enabled: false }),
+ ],
+ null,
+ );
+ expect(
+ rows.map((row) => [row.name, row.group, row.paths.length, row.providers.length]),
+ ).toEqual([
+ ["test-t3-app", "project", 1, 1],
+ ["frontend-design", "personal", 2, 2],
+ ]);
+ });
+
+ it("shows a skill as switched off by the provider only when every provider has it off", () => {
+ const skill = (enabled: boolean) => ({
+ name: "grill-me",
+ path: "/home/me/.agents/skills/grill-me/SKILL.md",
+ scope: "user",
+ enabled,
+ });
+ expect(
+ collectSkillRows([provider("a", [skill(false)]), provider("b", [skill(true)])], null)[0]
+ ?.disabledByProvider,
+ ).toBe(false);
+ expect(collectSkillRows([provider("a", [skill(false)])], null)[0]?.disabledByProvider).toBe(
+ true,
+ );
+ });
+});
+
+describe("listMcpServerRows", () => {
+ const linear: McpServerConfig = {
+ enabled: true,
+ transport: { type: "http", url: "https://mcp.linear.app/mcp", headers: [] },
+ };
+
+ it("marks project servers, replacements and switched inherited servers", () => {
+ const rows = listMcpServerRows({
+ environment: { linear, sentry: linear },
+ project: {
+ linear: { enabled: true, transport: linear.transport },
+ sentry: { enabled: false },
+ gone: { enabled: false },
+ },
+ });
+ expect(
+ rows.map((row) => [row.name, row.origin, row.replacesEnvironment, row.config.enabled]),
+ ).toEqual([
+ ["linear", "project", true, true],
+ ["sentry", "project-switch", false, false],
+ ]);
+ });
+});
+
+describe("MCP server drafts", () => {
+ it("reads the JSON snippets vendors publish", () => {
+ expect(
+ parseMcpServerJson(
+ JSON.stringify({
+ mcpServers: {
+ Supabase: {
+ command: "npx",
+ args: ["-y", "@supabase/mcp-server-supabase", "--project-ref=abc"],
+ env: { SUPABASE_ACCESS_TOKEN: "sbp_123" },
+ },
+ },
+ }),
+ ),
+ ).toMatchObject({
+ name: "supabase",
+ type: "stdio",
+ command: "npx",
+ args: "-y @supabase/mcp-server-supabase --project-ref=abc",
+ env: [{ name: "SUPABASE_ACCESS_TOKEN", value: "sbp_123", sensitive: true }],
+ });
+ expect(
+ parseMcpServerJson('{ "linear": { "url": "https://mcp.linear.app/mcp" } }'),
+ ).toMatchObject({ name: "linear", type: "http", url: "https://mcp.linear.app/mcp" });
+ // OpenCode's command array.
+ expect(
+ parseMcpServerJson('{ "type": "local", "command": ["bunx", "my-mcp", "--flag"] }'),
+ ).toMatchObject({ type: "stdio", command: "bunx", args: "my-mcp --flag" });
+ expect(parseMcpServerJson("not json")).toBeNull();
+ expect(parseMcpServerJson('{ "theme": "dark" }')).toBeNull();
+ });
+
+ it("round-trips quoted arguments", () => {
+ const args = ["--dir", "/Users/me/My Projects", 'say "hi"', ""];
+ expect(parseArgs(formatArgs(args))).toEqual(args);
+ });
+
+ it("keeps a stored secret when the user leaves its value empty", () => {
+ const draft = mcpServerDraftFrom("linear", {
+ enabled: true,
+ transport: {
+ type: "http",
+ url: "https://mcp.linear.app/mcp",
+ headers: [{ name: "Authorization", value: "", sensitive: true, valueRedacted: true }],
+ },
+ });
+ const result = mcpServerFromDraft(draft, new Set());
+ expect(result).toEqual({
+ ok: true,
+ name: "linear",
+ transport: {
+ type: "http",
+ url: "https://mcp.linear.app/mcp",
+ headers: [{ name: "Authorization", value: "", sensitive: true, valueRedacted: true }],
+ },
+ });
+ });
+
+ it("rejects T3's own name, duplicates and missing commands", () => {
+ const base = {
+ ...mcpServerDraftFrom("x", {
+ enabled: true,
+ transport: { type: "stdio", command: "npx", args: [], env: [] },
+ }),
+ };
+ expect(mcpServerFromDraft({ ...base, name: "t3-code" }, new Set())).toMatchObject({
+ ok: false,
+ field: "name",
+ });
+ expect(mcpServerFromDraft({ ...base, name: "linear" }, new Set(["linear"]))).toMatchObject({
+ ok: false,
+ field: "name",
+ });
+ expect(mcpServerFromDraft({ ...base, name: "ok", command: " " }, new Set())).toMatchObject({
+ ok: false,
+ field: "command",
+ });
+ });
+});
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
new file mode 100644
index 0000000000000..659472299dca2
--- /dev/null
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -0,0 +1,468 @@
+import {
+ isValidMcpServerName,
+ type McpServerConfig,
+ type McpServerProjectOverride,
+ type McpServerTransport,
+ type McpServerVariable,
+ type ProviderDriverKind,
+ type ProviderInstanceId,
+ type ServerProvider,
+ type ServerProviderSkill,
+} from "@t3tools/contracts";
+import {
+ resolveProviderSkillSourceKind,
+ resolveProviderSkillsForCwd,
+} from "@t3tools/client-runtime/providerSkills";
+
+export type ToolsTab = "skills" | "mcp";
+
+export function validateToolsSearch(raw: Record): { tab?: ToolsTab } {
+ return raw.tab === "mcp" || raw.tab === "skills" ? { tab: raw.tab } : {};
+}
+
+/** Where a skill lives, the groups the Skills tab shows in order. */
+export type SkillGroupKind = "project" | "personal" | "plugin" | "system";
+
+export const SKILL_GROUP_LABELS: Readonly> = {
+ project: "Repository",
+ personal: "Personal",
+ plugin: "Plugins",
+ system: "Built in",
+};
+
+export interface SkillProviderRef {
+ readonly instanceId: ProviderInstanceId;
+ readonly driver: ProviderDriverKind;
+ readonly displayName: string;
+}
+
+/**
+ * One row of the Skills tab: every provider instance that loads a skill of
+ * this name, merged. Skills are switched by name, so two folders holding a
+ * skill of the same name are one row; their paths are listed as copies.
+ */
+export interface SkillRow {
+ readonly name: string;
+ readonly description: string | undefined;
+ readonly group: SkillGroupKind;
+ readonly paths: ReadonlyArray;
+ readonly providers: ReadonlyArray;
+ /** Off in the provider's own settings (e.g. Claude's `skillOverrides`). */
+ readonly disabledByProvider: boolean;
+}
+
+function skillGroup(skill: ServerProviderSkill): SkillGroupKind {
+ const path = skill.path.replaceAll("\\", "/");
+ if (path.includes("/plugins/")) return "plugin";
+ switch (resolveProviderSkillSourceKind(skill)) {
+ case "project":
+ case "repo":
+ return "project";
+ case "personal":
+ return "personal";
+ case "app":
+ return "plugin";
+ case "system":
+ case "other":
+ return skill.scope?.trim().toLowerCase() === "plugin" ? "plugin" : "system";
+ }
+}
+
+const GROUP_ORDER: ReadonlyArray = ["project", "personal", "plugin", "system"];
+
+const isFilePath = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path);
+
+/**
+ * The skills every enabled provider instance on one environment discovers,
+ * for the checkout at `cwd` when one is given (falling back to each
+ * provider's own launch directory until its snapshot for `cwd` arrives).
+ * A skill reached from a project folder by any provider counts as a project
+ * skill, so the group follows the most specific location.
+ */
+export function collectSkillRows(
+ providers: ReadonlyArray,
+ cwd: string | null,
+): ReadonlyArray {
+ const rows = new Map<
+ string,
+ {
+ name: string;
+ description: string | undefined;
+ group: SkillGroupKind;
+ paths: Set;
+ providers: Map;
+ disabledByProvider: boolean;
+ }
+ >();
+ for (const provider of providers) {
+ if (!provider.enabled) continue;
+ const skills = cwd === null ? provider.skills : resolveProviderSkillsForCwd(provider, cwd);
+ for (const skill of skills) {
+ const key = skill.name.trim().toLowerCase();
+ if (key.length === 0) continue;
+ const group = skillGroup(skill);
+ const ref: SkillProviderRef = {
+ instanceId: provider.instanceId,
+ driver: provider.driver,
+ displayName: provider.displayName ?? provider.instanceId,
+ };
+ // Pi reports a synthetic `pi:skill:` id instead of a file.
+ const path = isFilePath(skill.path) ? skill.path : null;
+ const existing = rows.get(key);
+ if (existing === undefined) {
+ rows.set(key, {
+ name: skill.name.trim(),
+ description: skill.description ?? skill.shortDescription,
+ group,
+ paths: new Set(path === null ? [] : [path]),
+ providers: new Map([[provider.instanceId, ref]]),
+ disabledByProvider: !skill.enabled,
+ });
+ continue;
+ }
+ if (GROUP_ORDER.indexOf(group) < GROUP_ORDER.indexOf(existing.group)) existing.group = group;
+ existing.description ??= skill.description ?? skill.shortDescription;
+ if (path !== null) existing.paths.add(path);
+ existing.providers.set(provider.instanceId, ref);
+ // Off only when every provider that has it turned it off itself.
+ existing.disabledByProvider &&= !skill.enabled;
+ }
+ }
+ return [...rows.values()]
+ .map((row) => ({
+ name: row.name,
+ description: row.description,
+ group: row.group,
+ paths: [...row.paths].toSorted(),
+ providers: [...row.providers.values()].toSorted((left, right) =>
+ left.displayName.localeCompare(right.displayName),
+ ),
+ disabledByProvider: row.disabledByProvider,
+ }))
+ .toSorted(
+ (left, right) =>
+ GROUP_ORDER.indexOf(left.group) - GROUP_ORDER.indexOf(right.group) ||
+ left.name.localeCompare(right.name),
+ );
+}
+
+export function groupSkillRows(
+ rows: ReadonlyArray,
+): ReadonlyArray<{ readonly group: SkillGroupKind; readonly rows: ReadonlyArray }> {
+ return GROUP_ORDER.flatMap((group) => {
+ const groupRows = rows.filter((row) => row.group === group);
+ return groupRows.length === 0 ? [] : [{ group, rows: groupRows }];
+ });
+}
+
+export function filterSkillRows(rows: ReadonlyArray, query: string) {
+ const needle = query.trim().toLowerCase();
+ if (needle.length === 0) return rows;
+ return rows.filter(
+ (row) =>
+ row.name.toLowerCase().includes(needle) ||
+ (row.description?.toLowerCase().includes(needle) ?? false),
+ );
+}
+
+/** Whether `providers` covers only some of the enabled instances, so the row should name them. */
+export function skillReachesSomeProviders(row: SkillRow, enabledProviderCount: number): boolean {
+ return row.providers.length < enabledProviderCount;
+}
+
+/** The environment's list with one skill switched. Sorted so equal lists compare equal. */
+export function withSkillDisabled(
+ disabledSkills: ReadonlyArray,
+ name: string,
+ disabled: boolean,
+): ReadonlyArray {
+ const next = new Set(
+ disabledSkills.filter((entry) => entry.toLowerCase() !== name.toLowerCase()),
+ );
+ if (disabled) next.add(name);
+ return [...next].toSorted();
+}
+
+export function isSkillDisabled(disabledSkills: ReadonlyArray, name: string): boolean {
+ const lowered = name.toLowerCase();
+ return disabledSkills.some((entry) => entry.toLowerCase() === lowered);
+}
+
+// ── MCP servers ────────────────────────────────────────────────────
+
+/** Where a server in the effective list comes from at the current scope. */
+export type McpServerOrigin =
+ /** Defined on the environment; at project scope, inherited unchanged. */
+ | "environment"
+ /** Added by the project, or replacing the environment's server of that name. */
+ | "project"
+ /** The environment's server, switched on or off for the project. */
+ | "project-switch";
+
+export interface McpServerRow {
+ readonly name: string;
+ readonly config: McpServerConfig;
+ readonly origin: McpServerOrigin;
+ /** The project replaces an environment server of the same name. */
+ readonly replacesEnvironment: boolean;
+}
+
+export function listMcpServerRows(input: {
+ readonly environment: Readonly>;
+ readonly project: Readonly> | null;
+}): ReadonlyArray {
+ const rows = new Map();
+ for (const [name, config] of Object.entries(input.environment)) {
+ rows.set(name, { name, config, origin: "environment", replacesEnvironment: false });
+ }
+ for (const [name, entry] of Object.entries(input.project ?? {})) {
+ const inherited = input.environment[name];
+ if (entry.transport !== undefined) {
+ rows.set(name, {
+ name,
+ config: { enabled: entry.enabled, transport: entry.transport },
+ origin: "project",
+ replacesEnvironment: inherited !== undefined,
+ });
+ } else if (inherited !== undefined) {
+ rows.set(name, {
+ name,
+ config: { ...inherited, enabled: entry.enabled },
+ origin: "project-switch",
+ replacesEnvironment: false,
+ });
+ }
+ }
+ return [...rows.values()].toSorted((left, right) => left.name.localeCompare(right.name));
+}
+
+// ── Server editor draft ────────────────────────────────────────────
+
+export interface McpVariableDraft {
+ readonly id: string;
+ readonly name: string;
+ readonly value: string;
+ readonly sensitive: boolean;
+ /** A stored secret the user has not replaced. */
+ readonly stored: boolean;
+}
+
+export interface McpServerDraft {
+ readonly name: string;
+ readonly type: McpServerTransport["type"];
+ readonly command: string;
+ readonly args: string;
+ readonly url: string;
+ readonly env: ReadonlyArray;
+ readonly headers: ReadonlyArray;
+}
+
+let variableDraftId = 0;
+export const nextMcpVariableDraftId = () => `mcp-var-${variableDraftId++}`;
+
+const variableDrafts = (variables: ReadonlyArray) =>
+ variables.map((variable) => ({
+ id: nextMcpVariableDraftId(),
+ name: variable.name,
+ value: variable.valueRedacted ? "" : variable.value,
+ sensitive: variable.sensitive,
+ stored: variable.valueRedacted === true,
+ }));
+
+export const EMPTY_MCP_SERVER_DRAFT: McpServerDraft = {
+ name: "",
+ type: "stdio",
+ command: "",
+ args: "",
+ url: "",
+ env: [],
+ headers: [],
+};
+
+export function mcpServerDraftFrom(name: string, config: McpServerConfig): McpServerDraft {
+ const transport = config.transport;
+ return transport.type === "stdio"
+ ? {
+ ...EMPTY_MCP_SERVER_DRAFT,
+ name,
+ type: "stdio",
+ command: transport.command,
+ args: formatArgs(transport.args),
+ env: variableDrafts(transport.env),
+ }
+ : {
+ ...EMPTY_MCP_SERVER_DRAFT,
+ name,
+ type: "http",
+ url: transport.url,
+ headers: variableDrafts(transport.headers),
+ };
+}
+
+/** Arguments on one line; an argument with whitespace or quotes is double-quoted. */
+export function formatArgs(args: ReadonlyArray): string {
+ return args
+ .map((arg) =>
+ arg.length === 0 || /[\s"'\\]/.test(arg) ? `"${arg.replaceAll(/(["\\])/g, "\\$1")}"` : arg,
+ )
+ .join(" ");
+}
+
+/** Split an argument line on whitespace, honoring single and double quotes. */
+export function parseArgs(line: string): ReadonlyArray {
+ const args: string[] = [];
+ let current = "";
+ let quote: '"' | "'" | null = null;
+ let started = false;
+ for (let index = 0; index < line.length; index++) {
+ const char = line[index]!;
+ if (quote !== null) {
+ if (char === quote) quote = null;
+ else if (char === "\\" && quote === '"' && index + 1 < line.length) current += line[++index];
+ else current += char;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ started = true;
+ } else if (/\s/.test(char)) {
+ if (started) args.push(current);
+ current = "";
+ started = false;
+ } else {
+ current += char;
+ started = true;
+ }
+ }
+ if (started) args.push(current);
+ return args;
+}
+
+function variablesFromDrafts(drafts: ReadonlyArray): McpServerVariable[] {
+ return drafts.flatMap((draft) => {
+ const name = draft.name.trim();
+ if (name.length === 0) return [];
+ if (draft.sensitive && draft.stored && draft.value.length === 0) {
+ return [{ name, value: "", sensitive: true, valueRedacted: true }];
+ }
+ return [{ name, value: draft.value, sensitive: draft.sensitive }];
+ });
+}
+
+export type McpServerDraftResult =
+ | { readonly ok: true; readonly name: string; readonly transport: McpServerTransport }
+ | { readonly ok: false; readonly field: "name" | "command" | "url"; readonly message: string };
+
+export function mcpServerFromDraft(
+ draft: McpServerDraft,
+ takenNames: ReadonlySet,
+): McpServerDraftResult {
+ const name = draft.name.trim();
+ if (!isValidMcpServerName(name)) {
+ return {
+ ok: false,
+ field: "name",
+ message:
+ name === "t3-code"
+ ? "t3-code is reserved for T3 Code's own server."
+ : "Use lowercase letters, digits, - or _, starting with a letter.",
+ };
+ }
+ if (takenNames.has(name)) {
+ return { ok: false, field: "name", message: "A server with this name already exists." };
+ }
+ if (draft.type === "stdio") {
+ const command = draft.command.trim();
+ if (command.length === 0) {
+ return { ok: false, field: "command", message: "Enter the command that starts the server." };
+ }
+ return {
+ ok: true,
+ name,
+ transport: {
+ type: "stdio",
+ command,
+ args: [...parseArgs(draft.args)],
+ env: variablesFromDrafts(draft.env),
+ },
+ };
+ }
+ const url = draft.url.trim();
+ if (!/^https?:\/\/\S+$/i.test(url)) {
+ return { ok: false, field: "url", message: "Enter an http:// or https:// URL." };
+ }
+ return {
+ ok: true,
+ name,
+ transport: { type: "http", url, headers: variablesFromDrafts(draft.headers) },
+ };
+}
+
+/**
+ * Read the JSON snippet MCP vendors publish (`{"mcpServers": {...}}`, a bare
+ * `{"name": {...}}` map, or one server object) into a draft. Values in `env`
+ * and `headers` are marked sensitive, since that is where keys go.
+ */
+export function parseMcpServerJson(text: string): McpServerDraft | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
+ let record = parsed as Record;
+ for (const key of ["mcpServers", "servers", "mcp"]) {
+ const nested = record[key];
+ if (typeof nested === "object" && nested !== null && !Array.isArray(nested)) {
+ record = nested as Record;
+ break;
+ }
+ }
+ const isServer = (value: unknown): value is Record =>
+ typeof value === "object" &&
+ value !== null &&
+ ("command" in value || "url" in value || "serverUrl" in value || "httpUrl" in value);
+ const [name, server] = isServer(record)
+ ? ["", record]
+ : (Object.entries(record).find(([, value]) => isServer(value)) ?? ["", undefined]);
+ if (server === undefined || !isServer(server)) return null;
+ const toVariables = (value: unknown) =>
+ typeof value === "object" && value !== null && !Array.isArray(value)
+ ? Object.entries(value as Record).map(([key, entry]) => ({
+ id: nextMcpVariableDraftId(),
+ name: key,
+ value: typeof entry === "string" ? entry : String(entry),
+ sensitive: true,
+ stored: false,
+ }))
+ : [];
+ const url = server.url ?? server.serverUrl ?? server.httpUrl;
+ if (typeof url === "string") {
+ return {
+ ...EMPTY_MCP_SERVER_DRAFT,
+ name: name.toLowerCase(),
+ type: "http",
+ url,
+ headers: toVariables(server.headers),
+ };
+ }
+ const commandValue = server.command;
+ const commandParts = Array.isArray(commandValue)
+ ? commandValue.filter((part): part is string => typeof part === "string")
+ : typeof commandValue === "string"
+ ? [commandValue]
+ : [];
+ const [command = "", ...commandArgs] = commandParts;
+ const args = Array.isArray(server.args)
+ ? server.args.filter((arg): arg is string => typeof arg === "string")
+ : [];
+ return {
+ ...EMPTY_MCP_SERVER_DRAFT,
+ name: name.toLowerCase(),
+ type: "stdio",
+ command,
+ args: formatArgs([...commandArgs, ...args]),
+ env: toVariables(server.env ?? server.environment),
+ };
+}
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index 2c0b2285d77df..1bffede184e14 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -17,6 +17,7 @@ import { Route as ConnectAgentRouteImport } from './routes/connect-agent'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
+import { Route as SettingsToolsRouteImport } from './routes/settings.tools'
import { Route as SettingsStorageRouteImport } from './routes/settings.storage'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsSnapShotRouteImport } from './routes/settings.snap-shot'
@@ -75,6 +76,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
+const SettingsToolsRoute = SettingsToolsRouteImport.update({
+ id: '/tools',
+ path: '/tools',
+ getParentRoute: () => SettingsRoute,
+} as any)
const SettingsStorageRoute = SettingsStorageRouteImport.update({
id: '/storage',
path: '/storage',
@@ -192,6 +198,7 @@ export interface FileRoutesByFullPath {
'/settings/snap-shot': typeof SettingsSnapShotRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/storage': typeof SettingsStorageRoute
+ '/settings/tools': typeof SettingsToolsRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
@@ -218,6 +225,7 @@ export interface FileRoutesByTo {
'/settings/snap-shot': typeof SettingsSnapShotRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/storage': typeof SettingsStorageRoute
+ '/settings/tools': typeof SettingsToolsRoute
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -247,6 +255,7 @@ export interface FileRoutesById {
'/settings/snap-shot': typeof SettingsSnapShotRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/storage': typeof SettingsStorageRoute
+ '/settings/tools': typeof SettingsToolsRoute
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -277,6 +286,7 @@ export interface FileRouteTypes {
| '/settings/snap-shot'
| '/settings/source-control'
| '/settings/storage'
+ | '/settings/tools'
| '/$environmentId/$threadId'
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
@@ -303,6 +313,7 @@ export interface FileRouteTypes {
| '/settings/snap-shot'
| '/settings/source-control'
| '/settings/storage'
+ | '/settings/tools'
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
@@ -331,6 +342,7 @@ export interface FileRouteTypes {
| '/settings/snap-shot'
| '/settings/source-control'
| '/settings/storage'
+ | '/settings/tools'
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
@@ -405,6 +417,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
+ '/settings/tools': {
+ id: '/settings/tools'
+ path: '/tools'
+ fullPath: '/settings/tools'
+ preLoaderRoute: typeof SettingsToolsRouteImport
+ parentRoute: typeof SettingsRoute
+ }
'/settings/storage': {
id: '/settings/storage'
path: '/storage'
@@ -565,6 +584,7 @@ interface SettingsRouteChildren {
SettingsSnapShotRoute: typeof SettingsSnapShotRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
SettingsStorageRoute: typeof SettingsStorageRoute
+ SettingsToolsRoute: typeof SettingsToolsRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
@@ -582,6 +602,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsSnapShotRoute: SettingsSnapShotRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
SettingsStorageRoute: SettingsStorageRoute,
+ SettingsToolsRoute: SettingsToolsRoute,
}
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
diff --git a/apps/web/src/routes/settings.tools.tsx b/apps/web/src/routes/settings.tools.tsx
new file mode 100644
index 0000000000000..daabf3c6c6740
--- /dev/null
+++ b/apps/web/src/routes/settings.tools.tsx
@@ -0,0 +1,27 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { ToolsSettings } from "../components/settings/ToolsSettings";
+import { validateToolsSearch } from "../components/settings/toolsSettings.logic";
+
+function SettingsToolsRoute() {
+ const { tab } = Route.useSearch();
+ const navigate = Route.useNavigate();
+ return (
+
+ void navigate({
+ // The settings route keeps the scope; Skills is the default tab.
+ search: next === "skills" ? {} : { tab: next },
+ replace: true,
+ resetScroll: false,
+ })
+ }
+ />
+ );
+}
+
+export const Route = createFileRoute("/settings/tools")({
+ validateSearch: validateToolsSearch,
+ component: SettingsToolsRoute,
+});
diff --git a/docs/README.md b/docs/README.md
index ead465ccce039..d3b0bd3ad7ec2 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -9,6 +9,7 @@
- [Terminal history](./user/terminal.md)
- [Source control](./user/source-control.md)
- [Project settings](./user/project-settings.md)
+- [Skills and MCP servers](./user/tools.md)
- [Appearance and themes](./user/appearance.md)
- [Keyboard shortcuts](./user/keybindings.md)
- [SnapShots](./user/snap-shot.md)
diff --git a/docs/user/composer.md b/docs/user/composer.md
index ba8d26fd81c29..6bbfd8b22b4c8 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -198,7 +198,8 @@ provider. On mobile, both are also available before starting a thread on
**New task**.
The slash menu also includes skills unless you turn off **Settings → General →
-Show skills in slash menu**. Only skills enabled for the provider are listed.
+Show skills in slash menu**. Only skills enabled for the provider are listed;
+**Settings → Tools** turns individual skills off (see [Skills and MCP servers](./tools.md)).
After you add or change skills, plugins, or MCP servers, use **Restart agent
session** in the command palette on web and desktop. The conversation continues,
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index 598ef5cb5e2e1..bc9dc6751dc1c 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -101,8 +101,8 @@ than** on the task.
## Defaults and inheritance
-General contains the model and workspace for new threads. Integrations controls agent browser
-access. Source Control contains automatic pull, the default pull request merge method and text
+General contains the model and workspace for new threads. Tools holds skill switches and MCP
+servers. Integrations controls agent browser access. Source Control contains automatic pull, the default pull request merge method and text
generation. The same rows edit environment defaults or project overrides depending on the
project crumb.
diff --git a/docs/user/tools.md b/docs/user/tools.md
new file mode 100644
index 0000000000000..96d04496a6457
--- /dev/null
+++ b/docs/user/tools.md
@@ -0,0 +1,39 @@
+# Skills and MCP servers
+
+**Settings → Tools** controls what agents can use on an environment: the skills they load and the
+MCP servers T3 Code gives them. Pick a project in the settings crumb to change them for that
+project only. Changes apply when an agent session next starts; use **Restart agent session** in the
+command palette to pick them up in an open thread.
+
+## Skills
+
+The **Skills** tab lists every skill the environment's agents find, grouped by where it lives: the
+selected project, your personal folders (such as `~/.agents/skills` and `~/.claude/skills`), and
+plugins. A skill is listed once even when several folders or agents have it.
+
+Turning a skill off removes it from the composer's skill menu and hides it from Claude, Codex and
+OpenCode 1.x sessions. Cursor, Grok, Antigravity, Pi and OpenCode 2 have no way to hide one skill,
+so they may still use it on their own. A skill switched off in the agent's own settings shows as
+off and can't be turned on here.
+
+With a project selected, a switch overrides the environment for that project only: you can turn a
+skill off for one project, or back on where the environment has it off.
+
+## MCP servers
+
+The **MCP servers** tab lists servers T3 Code adds to every agent session, next to its own
+`t3-code` server and the servers each agent already loads from its own config, which keep working
+unchanged. T3 Code never edits those config files.
+
+**Add server** takes a command (such as `npx -y @playwright/mcp`) or a URL. Pasting the JSON
+snippet from a server's documentation fills in the form. Environment variables and headers are
+marked secret by default: secret values are stored on the environment and never shown again, so
+leave the field empty to keep one or type a new value to replace it. Adding or editing a server
+needs permission to manage providers, because a server runs on the environment for every agent.
+
+With a project selected, servers you add belong to that project. Giving one the same name as an
+environment server replaces it for the project, which is how to point a project at a different
+account. Inherited servers can be switched off for the project without removing them elsewhere.
+
+Claude, Codex, Cursor, OpenCode, Grok and other ACP agents get these servers. ACP agents that don't
+support URL servers only get command servers. Pi isn't supported yet.
diff --git a/packages/contracts/src/agentTools.ts b/packages/contracts/src/agentTools.ts
new file mode 100644
index 0000000000000..ede7b7569ef25
--- /dev/null
+++ b/packages/contracts/src/agentTools.ts
@@ -0,0 +1,130 @@
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import { ForwardCompatibleArray, TrimmedNonEmptyString } from "./baseSchemas.ts";
+
+/**
+ * MCP servers and skill switches that T3 applies to every provider session.
+ *
+ * A server here is injected into each session next to the built-in `t3-code`
+ * server; T3 never writes a provider's own config files. Servers a provider
+ * already loads from its own config keep working untouched.
+ */
+
+/**
+ * Lowercase letters, digits, `-` and `_`, starting with a letter: the subset
+ * every provider accepts as a server key and tool prefix (Claude names tools
+ * `mcp____`, OpenCode `_`).
+ */
+const MCP_SERVER_NAME_PATTERN = /^[a-z][a-z0-9_-]*$/;
+export const MCP_SERVER_NAME_MAX_CHARS = 48;
+/** Reserved for T3's own server, which every session already gets. */
+export const RESERVED_MCP_SERVER_NAMES: ReadonlySet = new Set(["t3-code"]);
+
+export const McpServerName = TrimmedNonEmptyString.check(
+ Schema.isMaxLength(MCP_SERVER_NAME_MAX_CHARS),
+ Schema.isPattern(MCP_SERVER_NAME_PATTERN),
+ Schema.makeFilter((name: string) =>
+ RESERVED_MCP_SERVER_NAMES.has(name) ? `"${name}" is reserved for T3 Code.` : true,
+ ),
+);
+export type McpServerName = typeof McpServerName.Type;
+
+export const isValidMcpServerName: (name: unknown) => name is McpServerName =
+ Schema.is(McpServerName);
+
+/**
+ * An environment variable or HTTP header. A `sensitive` value is moved into
+ * the environment's secret store on save; settings and clients then see an
+ * empty value with `valueRedacted` set, and sending that back keeps it.
+ */
+export const McpServerVariable = Schema.Struct({
+ name: TrimmedNonEmptyString,
+ value: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
+ sensitive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
+ valueRedacted: Schema.optionalKey(Schema.Boolean),
+});
+export type McpServerVariable = typeof McpServerVariable.Type;
+
+export const McpStdioTransport = Schema.Struct({
+ type: Schema.Literal("stdio"),
+ command: TrimmedNonEmptyString,
+ args: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
+ env: Schema.Array(McpServerVariable).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
+});
+export type McpStdioTransport = typeof McpStdioTransport.Type;
+
+export const McpHttpTransport = Schema.Struct({
+ type: Schema.Literal("http"),
+ url: TrimmedNonEmptyString,
+ headers: Schema.Array(McpServerVariable).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
+});
+export type McpHttpTransport = typeof McpHttpTransport.Type;
+
+export const McpServerTransport = Schema.Union([McpStdioTransport, McpHttpTransport]);
+export type McpServerTransport = typeof McpServerTransport.Type;
+
+export const McpServerConfig = Schema.Struct({
+ enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ transport: McpServerTransport,
+});
+export type McpServerConfig = typeof McpServerConfig.Type;
+
+/**
+ * One server in a project's overrides. With a transport it adds a server to
+ * the project, or replaces the environment's server of the same name. Without
+ * one it only switches the inherited server on or off for the project.
+ */
+export const McpServerProjectOverride = Schema.Struct({
+ enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ transport: Schema.optionalKey(McpServerTransport),
+});
+export type McpServerProjectOverride = typeof McpServerProjectOverride.Type;
+
+export const McpServers = Schema.Record(McpServerName, McpServerConfig);
+export type McpServers = typeof McpServers.Type;
+
+export const McpServerProjectOverrides = Schema.Record(McpServerName, McpServerProjectOverride);
+export type McpServerProjectOverrides = typeof McpServerProjectOverrides.Type;
+
+/**
+ * Skills switched off on the environment, by the name agents invoke them
+ * with. A name rather than a path: the same skill is reached through several
+ * folders (symlinked into each provider's directory, or a worktree's copy of
+ * the repo), and a provider only ever sees one of them.
+ */
+export const DisabledSkills = ForwardCompatibleArray(TrimmedNonEmptyString);
+export type DisabledSkills = typeof DisabledSkills.Type;
+
+/**
+ * A project's per-skill switches, keyed by skill name. `true` turns a skill
+ * off for the project; `false` turns one the environment disabled back on.
+ * An absent name inherits.
+ */
+export const DisabledSkillsProjectOverride = Schema.Record(TrimmedNonEmptyString, Schema.Boolean);
+export type DisabledSkillsProjectOverride = typeof DisabledSkillsProjectOverride.Type;
+
+/** An MCP server as a provider session receives it: secrets materialized, enabled only. */
+export interface ResolvedMcpServer {
+ readonly name: McpServerName;
+ readonly transport: McpServerTransport;
+}
+
+/** Variables as a provider needs them; a redacted value that never materialized is dropped. */
+export function mcpServerVariableRecord(
+ variables: ReadonlyArray,
+): Record {
+ const record: Record = {};
+ for (const variable of variables) {
+ if (variable.valueRedacted === true && variable.value.length === 0) continue;
+ record[variable.name] = variable.value;
+ }
+ return record;
+}
+
+/** What a row shows for a server: its command line or URL, never a secret. */
+export function mcpServerTransportSummary(transport: McpServerTransport): string {
+ return transport.type === "stdio"
+ ? [transport.command, ...transport.args].join(" ")
+ : transport.url;
+}
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index d738ef79909e2..4cf7eb6d93187 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -28,6 +28,7 @@ export * from "./model.ts";
export * from "./keybindings.ts";
export * from "./server.ts";
export * from "./settings.ts";
+export * from "./agentTools.ts";
export * from "./git.ts";
export * from "./vcs.ts";
export * from "./sourceControl.ts";
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 942fbb915ffe3..1acaac8a94906 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -43,6 +43,14 @@ import {
type ProviderDriverKind,
} from "./providerInstance.ts";
import { PullRequestMergeMethod } from "./pullRequest.ts";
+import {
+ DisabledSkills,
+ DisabledSkillsProjectOverride,
+ McpServerConfig,
+ McpServerName,
+ McpServerProjectOverrides,
+ McpServers,
+} from "./agentTools.ts";
// ── Client Settings (local-only) ───────────────────────────────
@@ -1182,6 +1190,8 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [
"sidebarAutoSettleAfterDays",
"continueThreadsAfterServerUpdate",
"responseStreamingMode",
+ "mcpServers",
+ "disabledSkills",
] as const;
export type ProjectScopedServerSettingKey = (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number];
@@ -1213,6 +1223,9 @@ export const ProjectSettingsOverrides = Schema.Struct({
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
+ // Sparse: merged per name over the environment's value, not a replacement.
+ mcpServers: ForwardCompatibleOptional(McpServerProjectOverrides),
+ disabledSkills: ForwardCompatibleOptional(DisabledSkillsProjectOverride),
} satisfies Record);
export type ProjectSettingsOverrides = typeof ProjectSettingsOverrides.Type;
@@ -1480,6 +1493,10 @@ export const ServerSettings = Schema.Struct({
usageModelAliases: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString).pipe(
Schema.withDecodingDefault(Effect.succeed({})),
),
+ /** MCP servers T3 adds to every provider session, keyed by server name. */
+ mcpServers: McpServers.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
+ /** Skill names hidden from every agent on this environment. */
+ disabledSkills: DisabledSkills.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export type ServerSettings = typeof ServerSettings.Type;
@@ -1792,6 +1809,12 @@ export const ServerSettingsPatch = Schema.Struct({
usageModelAliases: Schema.optionalKey(
Schema.Record(TrimmedNonEmptyString, Schema.NullOr(TrimmedNonEmptyString)),
),
+ /**
+ * Each entry replaces one server; `null` removes it. A sensitive variable
+ * sent back with `valueRedacted` and no value keeps its stored secret.
+ */
+ mcpServers: Schema.optionalKey(Schema.Record(McpServerName, Schema.NullOr(McpServerConfig))),
+ disabledSkills: Schema.optionalKey(DisabledSkills),
});
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
@@ -1803,12 +1826,27 @@ export function requiredScopesForServerSettingsPatch(
let changesSettings = false;
for (const [key, value] of Object.entries(patch)) {
if (value === undefined) continue;
- if (key === "providers" || key === "providerInstances" || key === "usageLimitSources") {
+ if (
+ key === "providers" ||
+ key === "providerInstances" ||
+ key === "usageLimitSources" ||
+ // A server is a command T3 runs for every agent, like a provider binary.
+ key === "mcpServers"
+ ) {
changesProviders = true;
} else {
changesSettings = true;
}
}
+ // So does a project entry that carries its own server. Switching an
+ // inherited server off or on for a project is an ordinary setting.
+ if (
+ Object.values(patch.projectSettingsOverrides ?? {}).some((entry) =>
+ Object.values(entry?.mcpServers ?? {}).some((server) => server.transport !== undefined),
+ )
+ ) {
+ changesProviders = true;
+ }
return [
...(changesSettings || !changesProviders ? [AuthSettingsWriteScope] : []),
...(changesProviders ? [AuthProvidersManageScope] : []),
diff --git a/packages/shared/src/agentTools.test.ts b/packages/shared/src/agentTools.test.ts
new file mode 100644
index 0000000000000..d8b97677d251d
--- /dev/null
+++ b/packages/shared/src/agentTools.test.ts
@@ -0,0 +1,133 @@
+import {
+ AuthProvidersManageScope,
+ AuthSettingsWriteScope,
+ DEFAULT_SERVER_SETTINGS,
+ ProjectId,
+ requiredScopesForServerSettingsPatch,
+ ServerSettings,
+ type McpServerConfig,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { describe, expect, it } from "vite-plus/test";
+
+import { resolveProjectSettings } from "./projectSettings.ts";
+import { applyServerSettingsPatch } from "./serverSettings.ts";
+
+const projectId = ProjectId.make("project-a");
+
+const linear: McpServerConfig = {
+ enabled: true,
+ transport: { type: "http", url: "https://mcp.linear.app/mcp", headers: [] },
+};
+const supabase: McpServerConfig = {
+ enabled: true,
+ transport: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "@supabase/mcp-server-supabase"],
+ env: [{ name: "SUPABASE_ACCESS_TOKEN", value: "env-token", sensitive: true }],
+ },
+};
+
+describe("project tools overrides", () => {
+ it("merges servers per name so environment servers still reach the project", () => {
+ const projectSupabase: McpServerConfig = {
+ enabled: true,
+ transport: { ...supabase.transport, args: ["--project-ref", "project-db"] } as never,
+ };
+ const settings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ mcpServers: { linear, supabase, sentry: linear },
+ projectSettingsOverrides: {
+ [projectId]: {
+ mcpServers: {
+ // Replaces the environment's server of the same name.
+ supabase: projectSupabase,
+ // Switches an inherited server off without restating it.
+ sentry: { enabled: false },
+ // A switch for a server the environment no longer has is ignored.
+ removed: { enabled: true },
+ playwright: {
+ enabled: true,
+ transport: { type: "stdio", command: "npx", args: ["@playwright/mcp"], env: [] },
+ },
+ },
+ },
+ },
+ } satisfies ServerSettings;
+
+ const resolved = resolveProjectSettings(settings, projectId);
+
+ expect(resolved.sources.mcpServers).toBe("project");
+ expect(resolved.settings.mcpServers).toEqual({
+ linear,
+ supabase: projectSupabase,
+ sentry: { ...linear, enabled: false },
+ playwright: {
+ enabled: true,
+ transport: { type: "stdio", command: "npx", args: ["@playwright/mcp"], env: [] },
+ },
+ });
+ });
+
+ it("turns skills off and back on per project over the environment list", () => {
+ const settings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ disabledSkills: ["grill-me", "prepare-pr"],
+ projectSettingsOverrides: {
+ [projectId]: { disabledSkills: { "prepare-pr": false, "expo-deployment": true } },
+ },
+ } satisfies ServerSettings;
+
+ expect(resolveProjectSettings(settings, projectId).settings.disabledSkills).toEqual([
+ "expo-deployment",
+ "grill-me",
+ ]);
+ expect(resolveProjectSettings(settings, null).settings.disabledSkills).toEqual([
+ "grill-me",
+ "prepare-pr",
+ ]);
+ });
+});
+
+describe("mcpServers patches", () => {
+ it("replaces one server at a time and removes it with null", () => {
+ const current = { ...DEFAULT_SERVER_SETTINGS, mcpServers: { linear, supabase } };
+ const switched: McpServerConfig = {
+ enabled: true,
+ transport: { type: "http", url: "https://example.com/mcp", headers: [] },
+ };
+
+ const next = applyServerSettingsPatch(current, {
+ mcpServers: { supabase: switched, linear: null },
+ });
+
+ // A stdio server edited into an http one keeps no stdio fields.
+ expect(next.mcpServers).toEqual({ supabase: switched });
+ });
+
+ it("needs provider management to add a server, not to switch one for a project", () => {
+ expect(requiredScopesForServerSettingsPatch({ mcpServers: { linear } })).toEqual([
+ AuthProvidersManageScope,
+ ]);
+ expect(
+ requiredScopesForServerSettingsPatch({
+ projectSettingsOverrides: { [projectId]: { mcpServers: { linear } } },
+ }),
+ ).toEqual([AuthSettingsWriteScope, AuthProvidersManageScope]);
+ expect(
+ requiredScopesForServerSettingsPatch({
+ projectSettingsOverrides: { [projectId]: { mcpServers: { linear: { enabled: false } } } },
+ }),
+ ).toEqual([AuthSettingsWriteScope]);
+ expect(requiredScopesForServerSettingsPatch({ disabledSkills: ["grill-me"] })).toEqual([
+ AuthSettingsWriteScope,
+ ]);
+ });
+
+ it("rejects T3's own server name", () => {
+ const decode = Schema.decodeUnknownExit(ServerSettings);
+ expect(decode({ mcpServers: { "t3-code": linear } })._tag).toBe("Failure");
+ expect(decode({ mcpServers: { linear } })._tag).toBe("Success");
+ });
+});
diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts
index f99dacbbb69df..8587959ae462e 100644
--- a/packages/shared/src/projectSettings.ts
+++ b/packages/shared/src/projectSettings.ts
@@ -1,4 +1,9 @@
import {
+ type DisabledSkills,
+ type DisabledSkillsProjectOverride,
+ type McpServerConfig,
+ type McpServerProjectOverrides,
+ type McpServers,
type ModelSelection,
PROJECT_FILE_BACKED_SETTINGS,
PROJECT_SCOPED_SERVER_SETTING_KEYS,
@@ -172,6 +177,22 @@ function resolveProjectOverrides(
// A forward-compatible decode leaves an unknown value as a present
// undefined; that is not an override.
if (value === undefined) continue;
+ // Sparse per-name overrides: the project adds to and switches the
+ // environment's entries instead of replacing the whole value, so a server
+ // or skill added to the environment later still reaches the project.
+ if (key === "mcpServers") {
+ effective[key] = mergeProjectMcpServers(settings.mcpServers, overrides.mcpServers);
+ sources[key] = "project";
+ continue;
+ }
+ if (key === "disabledSkills") {
+ effective[key] = mergeProjectDisabledSkills(
+ settings.disabledSkills,
+ overrides.disabledSkills,
+ );
+ sources[key] = "project";
+ continue;
+ }
// A model on a disabled provider falls back to the environment, like the
// environment-level guards do for these keys.
if (
@@ -188,6 +209,43 @@ function resolveProjectOverrides(
return { settings: effective as ServerSettings, sources, overrides };
}
+/**
+ * The environment's servers with a project's entries applied by name: an
+ * entry with a transport adds or replaces a server, one without only switches
+ * the inherited server. A switch for a server the environment no longer has
+ * is dropped.
+ */
+export function mergeProjectMcpServers(
+ environment: McpServers,
+ project: McpServerProjectOverrides | undefined,
+): McpServers {
+ if (project === undefined) return environment;
+ const merged: Record = { ...environment };
+ for (const [name, entry] of Object.entries(project)) {
+ if (entry.transport !== undefined) {
+ merged[name] = { enabled: entry.enabled, transport: entry.transport };
+ continue;
+ }
+ const inherited = environment[name];
+ if (inherited !== undefined) merged[name] = { ...inherited, enabled: entry.enabled };
+ }
+ return merged as McpServers;
+}
+
+/** The environment's disabled skills with a project's per-name switches applied. */
+export function mergeProjectDisabledSkills(
+ environment: DisabledSkills,
+ project: DisabledSkillsProjectOverride | undefined,
+): DisabledSkills {
+ if (project === undefined) return environment;
+ const disabled = new Set(environment);
+ for (const [name, off] of Object.entries(project)) {
+ if (off) disabled.add(name);
+ else disabled.delete(name);
+ }
+ return [...disabled].sort();
+}
+
/** Replace the project's entry, dropping it entirely when nothing is overridden. */
export function withProjectSettingsOverrides(
settings: Pick,
diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts
index 5e66b0ebe3325..f7f00cba41b0e 100644
--- a/packages/shared/src/serverSettings.ts
+++ b/packages/shared/src/serverSettings.ts
@@ -281,6 +281,7 @@ export function applyServerSettingsPatch(
usageLimitSources: usageLimitSourcesPatch,
usagePriceOverrides: usagePriceOverridesPatch,
usageModelAliases: usageModelAliasesPatch,
+ mcpServers: mcpServersPatch,
// Entry replacement: deepMerge would keep keys the client meant to clear.
projectSettingsOverrides: projectSettingsOverridesPatch,
// Already translated into `projectSettingsOverrides` above; the legacy
@@ -421,6 +422,12 @@ export function applyServerSettingsPatch(
),
}
: {}),
+ // Each server is replaced whole: deepMerge would mix a stdio and an http
+ // transport, or keep a variable the client removed.
+ ...(mcpServersPatch !== undefined
+ ? { mcpServers: mergeSettingsEntries(current.mcpServers, mcpServersPatch) }
+ : {}),
+ ...(patch.disabledSkills !== undefined ? { disabledSkills: patch.disabledSkills } : {}),
...(patch.sourceControlWriterModelSelection !== undefined
? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
: {}),
From 54f5ab7fca01410610e750465b34b9344bbc4f89 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 10:26:09 -0700
Subject: [PATCH 02/35] chore: drop unused exports flagged by knip
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/mcpServerSecrets.ts | 2 +-
.../src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts | 2 +-
packages/contracts/src/agentTools.ts | 4 ++--
packages/shared/src/projectSettings.ts | 2 +-
4 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/apps/server/src/mcpServerSecrets.ts b/apps/server/src/mcpServerSecrets.ts
index ad58df7c577c6..cac7a31bc215c 100644
--- a/apps/server/src/mcpServerSecrets.ts
+++ b/apps/server/src/mcpServerSecrets.ts
@@ -25,7 +25,7 @@ type ServerEntry = McpServerConfig | McpServerProjectOverride;
const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url");
/** Deterministic per (owner, server, variable kind, variable name). */
-export function mcpServerSecretName(input: {
+function mcpServerSecretName(input: {
readonly owner: McpServerOwner;
readonly server: string;
readonly variableKind: "env" | "header";
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts
index 9827c37c0de4d..3644f28072682 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.ts
@@ -479,7 +479,7 @@ export const t3McpServerName = Effect.fn("t3McpServerName")(function* (threadId:
* thread registers its own copies under `t3u--` (at most
* 61 characters, under OpenCode's 64) and its rules allow only those.
*/
-export const userMcpServerPrefix = Effect.fn("userMcpServerPrefix")(function* (threadId: string) {
+const userMcpServerPrefix = Effect.fn("userMcpServerPrefix")(function* (threadId: string) {
const crypto = yield* Crypto.Crypto;
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(threadId))
diff --git a/packages/contracts/src/agentTools.ts b/packages/contracts/src/agentTools.ts
index ede7b7569ef25..71e07b5a74623 100644
--- a/packages/contracts/src/agentTools.ts
+++ b/packages/contracts/src/agentTools.ts
@@ -17,9 +17,9 @@ import { ForwardCompatibleArray, TrimmedNonEmptyString } from "./baseSchemas.ts"
* `mcp____`, OpenCode `_`).
*/
const MCP_SERVER_NAME_PATTERN = /^[a-z][a-z0-9_-]*$/;
-export const MCP_SERVER_NAME_MAX_CHARS = 48;
+const MCP_SERVER_NAME_MAX_CHARS = 48;
/** Reserved for T3's own server, which every session already gets. */
-export const RESERVED_MCP_SERVER_NAMES: ReadonlySet = new Set(["t3-code"]);
+const RESERVED_MCP_SERVER_NAMES: ReadonlySet = new Set(["t3-code"]);
export const McpServerName = TrimmedNonEmptyString.check(
Schema.isMaxLength(MCP_SERVER_NAME_MAX_CHARS),
diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts
index 8587959ae462e..84dd4cea15616 100644
--- a/packages/shared/src/projectSettings.ts
+++ b/packages/shared/src/projectSettings.ts
@@ -215,7 +215,7 @@ function resolveProjectOverrides(
* the inherited server. A switch for a server the environment no longer has
* is dropped.
*/
-export function mergeProjectMcpServers(
+function mergeProjectMcpServers(
environment: McpServers,
project: McpServerProjectOverrides | undefined,
): McpServers {
From 22c016bfa064fe64aad9aa41f1b5d0f21f751159 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 10:44:24 -0700
Subject: [PATCH 03/35] fix(server): pass skill switches to Claude's query
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
claudeMcpQueryOverrides built the skillOverrides settings, but the turn
never handed them to makeClaudeQueryOptions, so a skill switched off in
Settings → Tools still loaded in Claude sessions. Found by running a real
Claude turn; the new test opens a turn and checks the query options.
Co-Authored-By: Claude Opus 5.5
---
.../Adapters/ClaudeAdapterV2.test.ts | 98 +++++++++++++++++++
.../Adapters/ClaudeAdapterV2.ts | 3 +
2 files changed, 101 insertions(+)
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index bce88439008aa..73b74734331e0 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -1107,6 +1107,104 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => {
);
});
+describe("ClaudeAdapterV2 user tools", () => {
+ it.effect("opens the turn's query with the user's servers and skill switches", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-claude-user-tools-",
+ });
+ let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
+ settings: DEFAULT_CLAUDE_SETTINGS,
+ environment: {},
+ attachmentsDir,
+ fileSystem,
+ path: yield* Path.Path,
+ crypto: yield* Crypto.Crypto,
+ idAllocator,
+ queryRunner: {
+ allocateSessionId: Effect.succeed("native-thread-claude-user-tools"),
+ open: (input) =>
+ Effect.sync(() => {
+ openedOptions = input.options;
+ return {
+ messages: Stream.never,
+ offer: () => Effect.void,
+ setModel: () => Effect.void,
+ setPermissionMode: () => Effect.void,
+ interrupt: Effect.void,
+ close: Effect.void,
+ };
+ }),
+ forkSession: () => Effect.die("unused"),
+ subagentLaunchToolUseId: () => Effect.succeed(null),
+ assertComplete: Effect.void,
+ },
+ });
+ const threadId = ThreadId.make("thread-claude-user-tools-turn");
+ yield* mcpSessions.set({
+ environmentId: EnvironmentId.make("environment-claude-user-tools"),
+ threadId,
+ providerSessionId: "mcp-session-claude-user-tools",
+ providerInstanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
+ endpoint: "http://127.0.0.1:43123/mcp",
+ authorizationHeader: "Bearer secret-claude-token",
+ browserToolsAvailable: true,
+ tools: {
+ servers: [
+ {
+ name: "context7",
+ transport: { type: "stdio", command: "npx", args: ["context7"], env: [] },
+ },
+ ],
+ disabledSkills: ["grill-me"],
+ fingerprint: "a",
+ },
+ });
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-claude-user-tools"),
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
+ });
+ yield* runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId,
+ providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-claude-user-tools"),
+ text: "Hello.",
+ attachments: [],
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
+ }),
+ );
+
+ assert.deepInclude(openedOptions?.mcpServers ?? {}, {
+ context7: { type: "stdio", command: "npx", args: ["context7"], env: {} },
+ });
+ const settings = openedOptions?.settings;
+ assert.deepEqual(typeof settings === "object" ? settings.skillOverrides : undefined, {
+ "grill-me": "off",
+ });
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ ),
+ );
+});
+
describe("ClaudeAdapterV2 approval cancellation", () => {
it.effect("observes an approval signal that was already aborted", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 11492ba63322b..cd44af7c1220f 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -7405,6 +7405,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
...(mcpOverrides.mcpServers === undefined
? {}
: { mcpServers: mcpOverrides.mcpServers }),
+ ...(mcpOverrides.sdkSettings === undefined
+ ? {}
+ : { sdkSettings: mcpOverrides.sdkSettings }),
permissionMode: queryPolicy.permissionMode,
...(queryPolicy.allowDangerouslySkipPermissions === undefined
? {}
From a9239e68b55a3192a904a42f7c895bd70a942670 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 11:46:03 -0700
Subject: [PATCH 04/35] =?UTF-8?q?fix:=20address=20review=20findings=20on?=
=?UTF-8?q?=20Settings=20=E2=86=92=20Tools?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- Renaming an MCP server or variable keeps its stored secret: the client
sends where it was saved and the server moves it. A sensitive value
hand-edited into settings.json moves into the store on the next save.
- Turning a secret off and on again with nothing typed keeps it.
- Editing a server at All environments no longer copies it, without its
secrets, onto environments that never had it; adding one checks names
across every environment.
- A settings-only client can change a project's skills or switches when
the project has its own servers: resending a server unchanged is not a
provider change.
- Environment server switches need provider management, like the server.
- OpenCode 2 always denies other threads' user servers and retries ones
that failed to register. OpenCode 1 and 2 give an external server the
user's servers, and OpenCode 1 reapplies skill rules on resume and
rollback.
- ACP agents get an absolute command for bare names like npx.
- The composer hides disabled skills from slash commands too, a project
switch for a server named like an object property is ignored, and a
search for MCP servers opens that tab.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/auth/RpcAuthorization.test.ts | 56 +++++++++++
apps/server/src/auth/RpcAuthorization.ts | 42 +++++++--
apps/server/src/mcpServerSecrets.ts | 44 ++++++---
.../Adapters/OpenCode2AdapterV2.test.ts | 8 +-
...penCode2OrchestratorV2.integration.test.ts | 4 +-
.../opencode2_fork/opencode_transcript.ndjson | 2 +-
.../opencode_transcript.ndjson | 2 +-
apps/server/src/serverSettings.test.ts | 94 +++++++++++++++++++
apps/server/src/serverSettings.ts | 52 ++++++----
apps/server/src/ws.ts | 9 +-
apps/web/src/components/chat/ChatComposer.tsx | 16 ++--
.../components/settings/McpServerDialog.tsx | 23 ++++-
.../src/components/settings/ToolsSettings.tsx | 74 ++++++++++++---
.../settings/toolsSettings.logic.test.ts | 26 +++++
.../settings/toolsSettings.logic.ts | 39 +++++++-
.../components/settings/useScopedSettings.ts | 13 ++-
apps/web/src/hooks/useSettings.ts | 15 +--
apps/web/src/routes/settings.tools.tsx | 7 +-
packages/contracts/src/agentTools.ts | 5 +
packages/contracts/src/settings.ts | 17 +++-
packages/provider-acp/src/server/adapter.ts | 20 +++-
.../provider-opencode/src/server/adapter.ts | 81 ++++++++++------
.../src/server/v2/adapter.ts | 30 +++---
packages/shared/src/agentTools.test.ts | 4 +-
packages/shared/src/projectSettings.ts | 2 +-
25 files changed, 548 insertions(+), 137 deletions(-)
diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts
index 0359b07b39415..524ce496a1b1b 100644
--- a/apps/server/src/auth/RpcAuthorization.test.ts
+++ b/apps/server/src/auth/RpcAuthorization.test.ts
@@ -5,6 +5,7 @@ import {
AuthProvidersManageScope,
AuthSettingsWriteScope,
DEFAULT_SERVER_SETTINGS,
+ ProjectId,
ProviderInstanceId,
ThreadId,
AuthOrchestrationOperateScope,
@@ -297,6 +298,61 @@ describe("settings mutation authorization", () => {
}).pipe(Effect.scoped),
);
+ it.effect("lets a settings grant resend a project's stored MCP server, not change it", () =>
+ Effect.gen(function* () {
+ const projectId = ProjectId.make("project-tools");
+ const linear = {
+ enabled: true,
+ transport: { type: "http" as const, url: "https://mcp.linear.app/mcp", headers: [] },
+ };
+ let handled = 0;
+ const client = yield* RpcTest.makeClient(group).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ group.toLayerHandler(WS_METHODS.serverUpdateSettings, () =>
+ Effect.sync(() => {
+ handled++;
+ return DEFAULT_SERVER_SETTINGS;
+ }),
+ ),
+ RpcAuthorization.layer(
+ [AuthSettingsWriteScope],
+ Effect.succeed({
+ projectSettingsOverrides: { [projectId]: { mcpServers: { linear } } },
+ }),
+ ),
+ ),
+ ),
+ );
+ // Turning a skill off resends the project's server exactly as stored.
+ yield* client[WS_METHODS.serverUpdateSettings]({
+ patch: {
+ projectSettingsOverrides: {
+ [projectId]: { mcpServers: { linear }, disabledSkills: { "grill-me": true } },
+ },
+ },
+ });
+ expect(handled).toBe(1);
+ expect(
+ yield* client[WS_METHODS.serverUpdateSettings]({
+ patch: {
+ projectSettingsOverrides: {
+ [projectId]: {
+ mcpServers: {
+ linear: {
+ ...linear,
+ transport: { ...linear.transport, url: "https://example.com/mcp" },
+ },
+ },
+ },
+ },
+ },
+ }).pipe(Effect.flip),
+ ).toMatchObject({ requiredPermission: AuthProvidersManageScope });
+ expect(handled).toBe(1);
+ }).pipe(Effect.scoped),
+ );
+
it.effect("does not let a settings grant create or remove providers", () =>
Effect.gen(function* () {
let handled = false;
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index a33d2f3317aaf..0f752c94f3601 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -6,6 +6,7 @@ import {
AssetCreateUrlInput,
AuthAccessReadScope,
ServerSettingsPatch,
+ type ServerSettings,
ProviderInstanceMutation,
requiredScopesForServerSettingsPatch,
AuthSettingsWriteScope,
@@ -230,9 +231,12 @@ const SettingsUpdate = Schema.Struct({
providerInstanceMutation: Schema.optionalKey(ProviderInstanceMutation),
});
-const requiredScopesForSettingsUpdate = (payload: unknown) => {
+const requiredScopesForSettingsUpdate = (
+ payload: unknown,
+ current: Pick | undefined,
+) => {
const input = Schema.decodeUnknownSync(SettingsUpdate)(payload);
- const scopes = requiredScopesForServerSettingsPatch(input.patch);
+ const scopes = requiredScopesForServerSettingsPatch(input.patch, current);
if (input.providerInstanceMutation === undefined) return scopes;
// An atomic provider mutation carries an empty patch unless it also changes settings.
return Object.values(input.patch).every((value) => value === undefined)
@@ -243,6 +247,7 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => {
const requiredScopesForRpcCall = (
method: string,
payload: unknown,
+ currentSettings?: Pick,
): ReadonlyArray => {
if (method === WS_METHODS.serverRetryResourceTelemetry) {
return [AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope];
@@ -257,19 +262,36 @@ const requiredScopesForRpcCall = (
: AuthOrchestrationReadScope,
];
}
- if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
+ if (method === WS_METHODS.serverUpdateSettings) {
+ return requiredScopesForSettingsUpdate(payload, currentSettings);
+ }
const guarded = clientRpcRequiredScopes(method, payload);
if (guarded.length > 0) return guarded;
return [requiredScopeForRpcMethod(method)];
};
-/** Authorizes every RPC on one connection against that connection's session scopes. */
-export const layer = (scopes: ReadonlyArray) =>
- Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => {
- const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload);
- const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope));
- return requiredScope === undefined ? effect : Effect.fail(rpcAuthorizationError(requiredScope));
- });
+/**
+ * Authorizes every RPC on one connection against that connection's session scopes.
+ * `currentSettings` lets a settings update that only resends a project's stored
+ * MCP servers pass with `settings:write`.
+ */
+export const layer = (
+ scopes: ReadonlyArray,
+ currentSettings: Effect.Effect<
+ Pick | undefined
+ > = Effect.succeed(undefined),
+) =>
+ Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) =>
+ Effect.gen(function* () {
+ const settings =
+ rpc._tag === WS_METHODS.serverUpdateSettings ? yield* currentSettings : undefined;
+ const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload, settings);
+ const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope));
+ return requiredScope === undefined
+ ? yield* effect
+ : yield* Effect.fail(rpcAuthorizationError(requiredScope));
+ }),
+ );
/** Retrying can install or restart tools even though ordinary listing is readable. */
export const requiredScopeForDeviceList = (input: DeviceListInput): AuthEnvironmentScope =>
diff --git a/apps/server/src/mcpServerSecrets.ts b/apps/server/src/mcpServerSecrets.ts
index cac7a31bc215c..2bf030836597e 100644
--- a/apps/server/src/mcpServerSecrets.ts
+++ b/apps/server/src/mcpServerSecrets.ts
@@ -160,40 +160,58 @@ export function redactMcpServerSecrets(settings: ServerSettings): ServerSettings
export type McpSecretChange =
| { readonly kind: "write"; readonly secretName: string; readonly value: string }
+ | { readonly kind: "copy"; readonly secretName: string; readonly from: string }
| { readonly kind: "remove"; readonly secretName: string };
/**
* Plan the secret-store writes for moving from `current` to `next`, and the
* settings to persist (sensitive values replaced by the redaction flag).
- * A sensitive variable sent back redacted with no value keeps its secret;
- * a value the user typed replaces it; an empty value or a variable that is
+ * A sensitive variable sent back redacted with no value keeps its secret,
+ * moved to its new name when `storedAs` says it was renamed, and a value still
+ * inline in `current` (hand-edited into settings.json) moves into the store.
+ * A value the user typed replaces it; an empty value or a variable that is
* no longer sensitive (or no longer exists) removes it.
*/
export function planMcpServerSecrets(
current: ServerSettings,
next: ServerSettings,
): { readonly settings: ServerSettings; readonly changes: ReadonlyArray } {
- const stored = new Set();
+ const stored = new Map();
for (const site of variableSites(current)) {
- if (site.variable.sensitive) stored.add(siteSecretName(site));
+ if (site.variable.sensitive) stored.set(siteSecretName(site), site.variable);
}
const changes: McpSecretChange[] = [];
const kept = new Set();
const settings = mapVariables(next, (site) => {
const secretName = siteSecretName(site);
- const { variable } = site;
- const { valueRedacted: _omit, ...plain } = variable;
- if (!variable.sensitive) return plain;
- if (variable.value.length === 0) {
- if (!variable.valueRedacted) return plain;
+ const { valueRedacted: _omit, storedAs, ...plain } = site.variable;
+ if (!plain.sensitive) return plain;
+ const redacted = { ...plain, value: "", valueRedacted: true };
+ if (plain.value.length > 0) {
kept.add(secretName);
- return { ...variable, value: "", valueRedacted: true };
+ changes.push({ kind: "write", secretName, value: plain.value });
+ return redacted;
}
+ if (!site.variable.valueRedacted) return plain;
+ const from =
+ storedAs === undefined
+ ? secretName
+ : siteSecretName({
+ ...site,
+ server: storedAs.server,
+ variable: { ...plain, name: storedAs.variable },
+ });
+ const previous = stored.get(from);
+ if (previous === undefined) return plain;
kept.add(secretName);
- changes.push({ kind: "write", secretName, value: variable.value });
- return { ...variable, value: "", valueRedacted: true };
+ if (!previous.valueRedacted && previous.value.length > 0) {
+ changes.push({ kind: "write", secretName, value: previous.value });
+ } else if (from !== secretName) {
+ changes.push({ kind: "copy", secretName, from });
+ }
+ return redacted;
});
- for (const secretName of stored) {
+ for (const secretName of stored.keys()) {
if (!kept.has(secretName)) changes.push({ kind: "remove", secretName });
}
return { settings, changes };
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index 205f54da70442..db646a85e900e 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -73,10 +73,14 @@ const event = (type: string, data: Record): ProviderReplayEntry
});
const durable = { durable: { aggregateID: SESSION, seq: 1, version: 1 } };
-/** The rules T3 gives every session it runs, with only this thread's own T3 MCP server allowed. */
+/**
+ * The rules T3 gives every session it runs: only this thread's own T3 MCP
+ * server is allowed, and no thread's Settings → Tools servers.
+ */
const mcpRules = [
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" },
+ { action: "t3u-*", resource: "*", effect: "deny" },
];
const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules];
const sessionInfo = (overrides: Record = {}) => ({
@@ -2742,6 +2746,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
{ action: "*", resource: "*", effect: "allow" },
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: `${server}_*`, resource: "*", effect: "allow" },
+ { action: "t3u-*", resource: "*", effect: "deny" },
],
}),
),
@@ -3691,6 +3696,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
{ action: "*", resource: "*", effect: "allow" },
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" },
+ { action: "t3u-*", resource: "*", effect: "deny" },
],
}),
reply("session.update", null),
diff --git a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
index 3b9fa218d0521..ed47a93db0aac 100644
--- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
+++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
@@ -73,11 +73,13 @@ const labelled = (entry: ProviderReplayEntry, label: string): ProviderReplayEntr
entry.type === "runtime_exit" ? entry : { ...entry, label };
/**
* T3's own rules after a mode's: every thread's T3 MCP server is denied, and
- * then this thread's own is allowed again (last match wins).
+ * then this thread's own is allowed again (last match wins). No thread's
+ * Settings → Tools servers are allowed, since these threads have none.
*/
const mcpRules = (name: string) => [
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: `t3-code-thread_${name}_*`, resource: "*", effect: "allow" },
+ { action: "t3u-*", resource: "*", effect: "deny" },
];
const FULL_ACCESS = [{ action: "*", resource: "*", effect: "allow" }];
/** Full access for the thread named `name`. */
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson
index a327f5ffc9ed9..4d178ccb9687f 100644
--- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson
+++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson
@@ -47,7 +47,7 @@
{"type": "emit_inbound", "label": "message.list.response.2", "frame": {"type": "sdk.response", "operation": "message.list", "data": {"data": [], "cursor": {}}}}
{"type": "expect_outbound", "label": "session.fork", "frame": {"type": "session.fork", "input": {"sessionID": "ses_f1484ea8affe5aTo8CcgbGIszj", "before": "msg_0eb7b1f9f001g95Bduh3bi8syS"}}}
{"type": "emit_inbound", "label": "session.fork.response", "frame": {"type": "sdk.response", "operation": "session.fork", "data": {"data": {"id": "ses_f1484db83ffeLGtrRCFimo1H0e", "fork": {"sessionID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}}, "projectID": "global", "model": {"id": "big-pickle", "providerID": "opencode", "variant": "default"}, "cost": 0, "tokens": {"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}, "time": {"created": 1790657111165, "updated": 1790657111165}, "title": "spike fork (fork #1)", "location": {"directory": ""}, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "subagent", "resource": "*", "effect": "deny"}]}}}}
-{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}]}}}
+{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}, {"action": "t3u-*", "resource": "*", "effect": "deny"}]}}}
{"type": "emit_inbound", "label": "session.update.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}}
{"type": "emit_inbound", "label": "session.forked", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7b247d001fXzFroPg5P0bps", "created": 1790657111165, "type": "session.forked", "location": {"directory": ""}, "data": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "parentID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}, "instructions": {"core/environment": "db4a793a05fec32fdfa985a3432125a86d6cb42debc8b9ee8f6a99fbfcf2f93b", "core/date": "bf08b8486572ab3eef677a3c9ee12468e411ae41a8f4d2fb6cf02a6ca73f1986", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}, "instructionEntries": []}, "durable": {"aggregateID": "ses_f1484db83ffeLGtrRCFimo1H0e", "seq": 0, "version": 2}}}}
{"type": "expect_outbound", "label": "session.instructions.entry.put.2", "frame": {"type": "session.instructions.entry.put", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "key": "t3-code", "value": ""}}}
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_switch/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_switch/opencode_transcript.ndjson
index 11b79b6d31f1d..1429a0640b224 100644
--- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_switch/opencode_transcript.ndjson
+++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_switch/opencode_transcript.ndjson
@@ -53,7 +53,7 @@
{"type": "emit_inbound", "label": "session.execution.succeeded", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7eef75001z9Sy13uGDVqV3F", "created": 1790657359733, "type": "session.execution.succeeded", "data": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP"}, "durable": {"aggregateID": "ses_f14812197ffeCbw641wM2r3ZmP", "seq": 15, "version": 1}}}}
{"type": "expect_outbound", "label": "session.get", "frame": {"type": "session.get", "input": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP"}}}
{"type": "emit_inbound", "label": "session.get.response", "frame": {"type": "sdk.response", "operation": "session.get", "data": {"data": {"id": "ses_f14812197ffeCbw641wM2r3ZmP", "projectID": "global", "agent": "plan", "model": {"id": "big-pickle", "providerID": "opencode", "variant": "default"}, "cost": 0, "tokens": {"input": 8910, "output": 271, "reasoning": 0, "cache": {"read": 384, "write": 0}}, "outcome": "succeeded", "time": {"created": 1790657355410, "updated": 1790657355463}, "title": "spike switch", "location": {"directory": ""}, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "subagent", "resource": "*", "effect": "deny"}]}}}}
-{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2_switch_*", "resource": "*", "effect": "allow"}]}}}
+{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2_switch_*", "resource": "*", "effect": "allow"}, {"action": "t3u-*", "resource": "*", "effect": "deny"}]}}}
{"type": "emit_inbound", "label": "session.update.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}}
{"type": "expect_outbound", "label": "session.switchAgent.2", "frame": {"type": "session.switchAgent", "input": {"sessionID": "ses_f14812197ffeCbw641wM2r3ZmP", "agent": "build"}}}
{"type": "emit_inbound", "label": "session.switchAgent.response.2", "frame": {"type": "sdk.response", "operation": "session.switchAgent", "data": null}}
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index 68f06f13e8485..c4dc8ed29db79 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1583,6 +1583,100 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(layerServerSettingsWithSecrets())),
);
+ it.effect("moves an MCP secret when its server or variable is renamed", () =>
+ Effect.gen(function* () {
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const secrets = yield* ServerSecretStore.ServerSecretStore;
+ yield* serverSettings.updateSettings({
+ mcpServers: {
+ supabase: {
+ enabled: true,
+ transport: {
+ type: "stdio",
+ command: "npx",
+ args: [],
+ env: [{ name: "SUPABASE_TOKEN", value: "token", sensitive: true }],
+ },
+ },
+ },
+ });
+
+ // The client renames both and sends the secret back redacted.
+ const renamed = yield* serverSettings.updateSettings({
+ mcpServers: {
+ supabase: null,
+ db: {
+ enabled: true,
+ transport: {
+ type: "stdio",
+ command: "npx",
+ args: [],
+ env: [
+ {
+ name: "SUPABASE_ACCESS_TOKEN",
+ value: "",
+ sensitive: true,
+ valueRedacted: true,
+ storedAs: { server: "supabase", variable: "SUPABASE_TOKEN" },
+ },
+ ],
+ },
+ },
+ },
+ });
+
+ const db = renamed.mcpServers.db?.transport;
+ assert.equal(db?.type === "stdio" ? db.env[0]?.value : undefined, "token");
+ // Only the new name holds it, and storedAs is not saved.
+ const secretName = (server: string, variable: string) =>
+ `mcp-env-${Buffer.from(server).toString("base64url")}-env-${Buffer.from(variable).toString("base64url")}`;
+ assert.isTrue(Option.isNone(yield* secrets.get(secretName("supabase", "SUPABASE_TOKEN"))));
+ assert.isTrue(Option.isSome(yield* secrets.get(secretName("db", "SUPABASE_ACCESS_TOKEN"))));
+ const forClient = ServerSettingsModule.redactServerSettingsForClient(renamed);
+ const echoed = forClient.mcpServers.db?.transport;
+ assert.notProperty(echoed?.type === "stdio" ? echoed.env[0] : {}, "storedAs");
+ }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
+ );
+
+ it.effect("moves a sensitive MCP value written into settings.json into the secret store", () =>
+ Effect.gen(function* () {
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const linear = (value: string, valueRedacted?: boolean) => ({
+ enabled: true,
+ transport: {
+ type: "http" as const,
+ url: "https://mcp.linear.app/mcp",
+ headers: [
+ {
+ name: "Authorization",
+ value,
+ sensitive: true,
+ ...(valueRedacted === undefined ? {} : { valueRedacted }),
+ },
+ ],
+ },
+ });
+ yield* fileSystem.writeFileString(
+ serverConfig.settingsPath,
+ JSON.stringify({ mcpServers: { linear: linear("Bearer hand-edited") } }),
+ );
+
+ // A client edit sends the header back redacted, as it always sees it.
+ const saved = yield* serverSettings.updateSettings({
+ mcpServers: { linear: linear("", true) },
+ });
+
+ const headers = saved.mcpServers.linear?.transport;
+ assert.equal(
+ headers?.type === "http" ? headers.headers[0]?.value : undefined,
+ "Bearer hand-edited",
+ );
+ assert.notInclude(yield* fileSystem.readFileString(serverConfig.settingsPath), "hand-edited");
+ }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
+ );
+
it.effect("removes a Bitbucket secret once its token is cleared by hand in settings.json", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index eda724adc4c1e..83c17862df08f 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -1018,6 +1018,8 @@ const make = Effect.gen(function* () {
readonly environmentVariable?: string;
} & (
| { readonly kind: "write"; readonly value: Uint8Array }
+ // A renamed MCP server or variable: the value moves to the new name.
+ | { readonly kind: "copy"; readonly from: string }
| { readonly kind: "remove"; readonly operation: "remove-secret" | "remove-stale-secret" }
);
@@ -1194,7 +1196,9 @@ const make = Effect.gen(function* () {
secretName: change.secretName,
value: textEncoder.encode(change.value),
}
- : { kind: "remove", secretName: change.secretName, operation: "remove-secret" },
+ : change.kind === "copy"
+ ? { kind: "copy", secretName: change.secretName, from: change.from }
+ : { kind: "remove", secretName: change.secretName, operation: "remove-secret" },
);
}
@@ -1244,34 +1248,48 @@ const make = Effect.gen(function* () {
readonly environmentVariable?: string;
}> = [];
const rollback = Effect.suspend(() => rollbackProviderEnvironmentSecretWrites(applied));
+ const readSecret = (change: SecretChange, secretName: string) =>
+ secretStore.get(secretName).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: "read-secret",
+ providerInstanceId: change.providerInstanceId,
+ environmentVariable: change.environmentVariable,
+ cause,
+ }),
+ ),
+ );
+ // Copies read their source before any removal in the same save drops it.
+ const ordered = [
+ ...changes.filter((change) => change.kind === "copy"),
+ ...changes.filter((change) => change.kind !== "copy"),
+ ];
return Effect.forEach(
- changes,
+ ordered,
(change) =>
Effect.gen(function* () {
- const previousValue = yield* secretStore.get(change.secretName).pipe(
- Effect.mapError(
- (cause) =>
- new ServerSettingsError({
- settingsPath,
- operation: "read-secret",
- providerInstanceId: change.providerInstanceId,
- environmentVariable: change.environmentVariable,
- cause,
- }),
- ),
- );
+ let value: Uint8Array | undefined;
+ if (change.kind === "write") value = change.value;
+ if (change.kind === "copy") {
+ const source = yield* readSecret(change, change.from);
+ if (Option.isNone(source)) return;
+ value = source.value;
+ }
+ const previousValue = yield* readSecret(change, change.secretName);
// A store operation may mutate before reporting an error (for example chmod after rename).
applied.push({ ...change, previousValue });
yield* (
- change.kind === "write"
- ? secretStore.set(change.secretName, change.value)
+ value !== undefined
+ ? secretStore.set(change.secretName, value)
: secretStore.remove(change.secretName)
).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
- operation: change.kind === "write" ? "write-secret" : change.operation,
+ operation: change.kind === "remove" ? change.operation : "write-secret",
providerInstanceId: change.providerInstanceId,
environmentVariable: change.environmentVariable,
cause,
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index a035d6971d454..5aa1681ea586b 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -3133,6 +3133,7 @@ export const layer = Layer.unwrap(
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const pullRequests = yield* PullRequestService.PullRequestService;
const sql = yield* SqlClient.SqlClient;
+ const serverSettingsService = yield* ServerSettings.ServerSettingsService;
return HttpRouter.add(
"GET",
"/ws",
@@ -3172,7 +3173,13 @@ export const layer = Layer.unwrap(
yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe(
Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
Effect.provide(
- Layer.merge(RpcAuthorization.layer(session.scopes), rpcInstrumentationLayer),
+ Layer.merge(
+ RpcAuthorization.layer(
+ session.scopes,
+ serverSettingsService.getSettings.pipe(Effect.orElseSucceed(() => undefined)),
+ ),
+ rpcInstrumentationLayer,
+ ),
),
Effect.forkScoped,
);
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 4c5d23898706a..4366c164a79cf 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -2222,13 +2222,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? skills
: skills.filter((skill) => !disabledSkillNames.has(skill.name.toLowerCase()));
}, [disabledSkillNames, gitCwd, selectedProviderStatus]);
- const selectedProviderSlashCommands = useMemo(
- () =>
- selectedProviderStatus
- ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd)
- : [],
- [gitCwd, selectedProviderStatus],
- );
+ // Claude also lists each skill as a slash command; a disabled one leaves both.
+ const selectedProviderSlashCommands = useMemo(() => {
+ const commands = selectedProviderStatus
+ ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd)
+ : [];
+ return disabledSkillNames.size === 0
+ ? commands
+ : commands.filter((command) => !disabledSkillNames.has(command.name.toLowerCase()));
+ }, [disabledSkillNames, gitCwd, selectedProviderStatus]);
const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
reportFailure: false,
});
diff --git a/apps/web/src/components/settings/McpServerDialog.tsx b/apps/web/src/components/settings/McpServerDialog.tsx
index 115cf09485eeb..be1740f1af6ab 100644
--- a/apps/web/src/components/settings/McpServerDialog.tsx
+++ b/apps/web/src/components/settings/McpServerDialog.tsx
@@ -55,7 +55,7 @@ export function McpServerDialog({
const [paste, setPaste] = useState("");
const [pasteError, setPasteError] = useState(false);
const [attempted, setAttempted] = useState(false);
- const result = mcpServerFromDraft(draft, takenNames);
+ const result = mcpServerFromDraft(draft, takenNames, initial?.name ?? null);
const error = attempted && !result.ok ? result : null;
const update = (patch: Partial) =>
@@ -233,8 +233,16 @@ function VariablesEditor({
? {
...variable,
...patch,
- // Typing a value replaces a stored secret.
- ...(patch.value !== undefined ? { stored: false } : {}),
+ // Typing a value replaces a stored secret; clearing it again
+ // while still secret brings the stored one back.
+ ...(patch.value !== undefined
+ ? {
+ stored:
+ patch.value.length === 0 &&
+ (patch.sensitive ?? variable.sensitive) &&
+ variable.storedName !== undefined,
+ }
+ : {}),
}
: variable,
),
@@ -296,8 +304,13 @@ function VariablesEditor({
onClick={() =>
update(variable.id, {
sensitive: !variable.sensitive,
- // A stored secret cannot become plain text without a new value.
- ...(variable.stored ? { stored: false, value: "" } : {}),
+ // Plain text needs a real value, so a stored secret is
+ // set aside while the variable is plain and comes back
+ // when it is marked secret again with nothing typed.
+ stored:
+ !variable.sensitive &&
+ variable.storedName !== undefined &&
+ variable.value.length === 0,
})
}
/>
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index e79e2546d2ac5..f54b0a5b342bd 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -10,6 +10,7 @@ import {
type ServerSettingsPatch,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
+import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -96,10 +97,18 @@ function useToolsTargets(): ReadonlyArray {
}, [connectedEnvironments, scope]);
}
+type ToolsSettingsSnapshot = NonNullable<
+ ReturnType["connectedEnvironments"][number]["serverConfig"]
+>["settings"];
+
/**
* Write a Tools change to every target. `apply` receives the target's raw
* environment settings and returns its patch: the environment's own key at
* environment scope, or the project's override entry at project scope.
+ *
+ * Each patch replaces a whole list or project entry, so it is built on the
+ * settings this page last wrote rather than the last ones the server pushed:
+ * a second click before the first save comes back must not undo it.
*/
function usePersistToolsPatch() {
const targets = useToolsTargets();
@@ -107,22 +116,33 @@ function usePersistToolsPatch() {
const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
label: "update tools",
});
+ const written = useRef(
+ new Map<
+ string,
+ { readonly base: ToolsSettingsSnapshot; readonly next: ToolsSettingsSnapshot }
+ >(),
+ );
return useCallback(
(
apply: (input: {
- readonly settings: NonNullable<
- (typeof connectedEnvironments)[number]["serverConfig"]
- >["settings"];
+ readonly settings: ToolsSettingsSnapshot;
readonly projectId: ProjectId | null;
}) => ServerSettingsPatch | null,
) => {
for (const target of targets) {
- const settings = connectedEnvironments.find(
+ const pushed = connectedEnvironments.find(
(environment) => environment.environmentId === target.environmentId,
)?.serverConfig?.settings;
- if (!settings) continue;
+ if (!pushed) continue;
+ const pending = written.current.get(target.environmentId);
+ // Once the server pushes newer settings, they are the base again.
+ const settings = pending !== undefined && pending.base === pushed ? pending.next : pushed;
const patch = apply({ settings, projectId: target.projectId });
if (patch === null) continue;
+ written.current.set(target.environmentId, {
+ base: pushed,
+ next: applyServerSettingsPatch(settings, patch),
+ });
void updateSettings({ environmentId: target.environmentId, input: { patch } });
}
},
@@ -130,7 +150,10 @@ function usePersistToolsPatch() {
);
}
-/** Replace one key of a project's override entry, dropping the key (or the entry) when empty. */
+/**
+ * Replace one key of a project's override entry, dropping the key (or the entry) when empty.
+ * The rest of the entry is resent as stored, since the patch replaces the whole entry.
+ */
function projectOverridePatch(
settings: {
readonly projectSettingsOverrides: Readonly>>;
@@ -455,6 +478,15 @@ function McpServersPanel() {
previousName?: string,
) =>
persist(({ settings, projectId: targetProject }) => {
+ const existing =
+ targetProject === null
+ ? settings.mcpServers
+ : (settings.projectSettingsOverrides[targetProject]?.mcpServers ?? {});
+ // An edit changes the server where it exists; it does not create a copy,
+ // without the stored secrets, on a target that never had it.
+ if (previousName !== undefined && existing[previousName]?.transport === undefined) {
+ return null;
+ }
if (targetProject === null) {
return {
mcpServers: {
@@ -465,9 +497,7 @@ function McpServersPanel() {
},
};
}
- const entries: Record = {
- ...settings.projectSettingsOverrides[targetProject]?.mcpServers,
- };
+ const entries: Record = { ...existing };
if (previousName !== undefined && previousName !== name) delete entries[previousName];
entries[name] = { enabled, transport };
return projectOverridePatch(settings, targetProject, "mcpServers", entries);
@@ -547,7 +577,8 @@ function McpServersPanel() {
setEnabled(row, enabled)}
onEdit={() => setEditor({ mode: "edit", row })}
@@ -592,11 +623,26 @@ function McpServersPanel() {
editor.mode === "edit" ? { name: editor.row.name, config: editor.row.config } : null
}
takenNames={
+ // Every target, not only the one shown: a name another environment
+ // already uses would otherwise overwrite its server and secrets.
new Set(
- rows
- .filter((row) => editor.mode === "add" || row.name !== editor.row.name)
- .filter((row) => !isProjectScope || row.origin === "project")
- .map((row) => row.name),
+ targets
+ .flatMap((writeTarget) => {
+ const settings = connectedEnvironments.find(
+ (environment) => environment.environmentId === writeTarget.environmentId,
+ )?.serverConfig?.settings;
+ const servers =
+ writeTarget.projectId === null
+ ? settings?.mcpServers
+ : Object.fromEntries(
+ Object.entries(
+ settings?.projectSettingsOverrides[writeTarget.projectId]?.mcpServers ??
+ {},
+ ).filter(([, entry]) => entry.transport !== undefined),
+ );
+ return Object.keys(servers ?? {});
+ })
+ .filter((name) => editor.mode === "add" || name !== editor.row.name),
)
}
onSave={({ name, transport }) => {
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index 7a6c161caf43e..9a724d3e04cbc 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -166,6 +166,32 @@ describe("MCP server drafts", () => {
});
});
+ it("tells the server where a renamed server's stored secret lives", () => {
+ const draft = mcpServerDraftFrom("linear", {
+ enabled: true,
+ transport: {
+ type: "http",
+ url: "https://mcp.linear.app/mcp",
+ headers: [{ name: "Authorization", value: "", sensitive: true, valueRedacted: true }],
+ },
+ });
+ const renamed = {
+ ...draft,
+ name: "linear-work",
+ headers: draft.headers.map((header) => ({ ...header, name: "X-Api-Key" })),
+ };
+ const result = mcpServerFromDraft(renamed, new Set(), "linear");
+ expect(result.ok && result.transport.type === "http" && result.transport.headers).toEqual([
+ {
+ name: "X-Api-Key",
+ value: "",
+ sensitive: true,
+ valueRedacted: true,
+ storedAs: { server: "linear", variable: "Authorization" },
+ },
+ ]);
+ });
+
it("rejects T3's own name, duplicates and missing commands", () => {
const base = {
...mcpServerDraftFrom("x", {
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 659472299dca2..853c0ce2f9291 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -216,7 +216,7 @@ export function listMcpServerRows(input: {
rows.set(name, { name, config, origin: "environment", replacesEnvironment: false });
}
for (const [name, entry] of Object.entries(input.project ?? {})) {
- const inherited = input.environment[name];
+ const inherited = Object.hasOwn(input.environment, name) ? input.environment[name] : undefined;
if (entry.transport !== undefined) {
rows.set(name, {
name,
@@ -245,6 +245,8 @@ export interface McpVariableDraft {
readonly sensitive: boolean;
/** A stored secret the user has not replaced. */
readonly stored: boolean;
+ /** The variable name its stored secret was saved under, kept through renames and toggles. */
+ readonly storedName?: string;
}
export interface McpServerDraft {
@@ -267,6 +269,7 @@ const variableDrafts = (variables: ReadonlyArray) =>
value: variable.valueRedacted ? "" : variable.value,
sensitive: variable.sensitive,
stored: variable.valueRedacted === true,
+ ...(variable.valueRedacted ? { storedName: variable.name } : {}),
}));
export const EMPTY_MCP_SERVER_DRAFT: McpServerDraft = {
@@ -338,12 +341,32 @@ export function parseArgs(line: string): ReadonlyArray {
return args;
}
-function variablesFromDrafts(drafts: ReadonlyArray): McpServerVariable[] {
+/**
+ * A stored secret the user did not replace goes back redacted. When the server
+ * or the variable was renamed, `storedAs` tells the server where the secret was
+ * saved so it moves with the rename.
+ */
+function variablesFromDrafts(
+ drafts: ReadonlyArray,
+ server: { readonly name: string; readonly storedName: string | null },
+): McpServerVariable[] {
return drafts.flatMap((draft) => {
const name = draft.name.trim();
if (name.length === 0) return [];
if (draft.sensitive && draft.stored && draft.value.length === 0) {
- return [{ name, value: "", sensitive: true, valueRedacted: true }];
+ const storedName = draft.storedName ?? name;
+ const renamed = server.storedName !== null && server.storedName !== server.name;
+ return [
+ {
+ name,
+ value: "",
+ sensitive: true,
+ valueRedacted: true,
+ ...(renamed || storedName !== name
+ ? { storedAs: { server: server.storedName ?? server.name, variable: storedName } }
+ : {}),
+ },
+ ];
}
return [{ name, value: draft.value, sensitive: draft.sensitive }];
});
@@ -353,9 +376,11 @@ export type McpServerDraftResult =
| { readonly ok: true; readonly name: string; readonly transport: McpServerTransport }
| { readonly ok: false; readonly field: "name" | "command" | "url"; readonly message: string };
+/** `storedName` is the server's saved name when editing, so renames keep its secrets. */
export function mcpServerFromDraft(
draft: McpServerDraft,
takenNames: ReadonlySet,
+ storedName: string | null = null,
): McpServerDraftResult {
const name = draft.name.trim();
if (!isValidMcpServerName(name)) {
@@ -383,7 +408,7 @@ export function mcpServerFromDraft(
type: "stdio",
command,
args: [...parseArgs(draft.args)],
- env: variablesFromDrafts(draft.env),
+ env: variablesFromDrafts(draft.env, { name, storedName }),
},
};
}
@@ -394,7 +419,11 @@ export function mcpServerFromDraft(
return {
ok: true,
name,
- transport: { type: "http", url, headers: variablesFromDrafts(draft.headers) },
+ transport: {
+ type: "http",
+ url,
+ headers: variablesFromDrafts(draft.headers, { name, storedName }),
+ },
};
}
diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.ts
index 4bed07267b133..47223d8957565 100644
--- a/apps/web/src/components/settings/useScopedSettings.ts
+++ b/apps/web/src/components/settings/useScopedSettings.ts
@@ -62,6 +62,8 @@ export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[])
function useRunScopedPlan() {
const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
+ // Optional: the plan also runs from controls rendered outside a settings page.
+ const connectedEnvironments = useOptionalSettingsScope()?.connectedEnvironments;
return useCallback(
(plan: ReturnType) => {
if (plan.unavailableReason) {
@@ -75,9 +77,12 @@ function useRunScopedPlan() {
void persistScopedSettingsPatch(
plan,
async (request) => {
- const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
- (scope) => !readEnvironmentScope(request.environmentId, scope),
- );
+ const missing = requiredScopesForServerSettingsPatch(
+ request.input.patch,
+ connectedEnvironments?.find(
+ (environment) => environment.environmentId === request.environmentId,
+ )?.serverConfig?.settings,
+ ).find((scope) => !readEnvironmentScope(request.environmentId, scope));
if (missing)
return AsyncResult.failure(
Cause.fail(
@@ -107,7 +112,7 @@ function useRunScopedPlan() {
});
});
},
- [persistServer],
+ [connectedEnvironments, persistServer],
);
}
diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts
index d61abb34f5535..04f409d08a2de 100644
--- a/apps/web/src/hooks/useSettings.ts
+++ b/apps/web/src/hooks/useSettings.ts
@@ -503,9 +503,11 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
const canWriteServerPatch =
environmentId === null ||
- requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
- readEnvironmentScope(environmentId, scope),
- );
+ requiredScopesForServerSettingsPatch(
+ serverPatch,
+ environments.find((target) => target.environmentId === environmentId)?.serverConfig
+ ?.settings,
+ ).every((scope) => readEnvironmentScope(environmentId, scope));
if (Object.keys(serverPatch).length > 0 && !canWriteServerPatch) {
toastManager.add({
type: "warning",
@@ -555,9 +557,10 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
const session = appAtomRegistry.get(environmentSession.sessionStateAtom(targetId));
if (
session._tag !== "Initial" &&
- !requiredScopesForServerSettingsPatch(sharedPatch).every((scope) =>
- readEnvironmentScope(targetId, scope),
- )
+ !requiredScopesForServerSettingsPatch(
+ sharedPatch,
+ target?.serverConfig?.settings,
+ ).every((scope) => readEnvironmentScope(targetId, scope))
) {
deniedLabels.push(target?.label ?? targetId);
continue;
diff --git a/apps/web/src/routes/settings.tools.tsx b/apps/web/src/routes/settings.tools.tsx
index daabf3c6c6740..ddcf66562afd4 100644
--- a/apps/web/src/routes/settings.tools.tsx
+++ b/apps/web/src/routes/settings.tools.tsx
@@ -1,4 +1,4 @@
-import { createFileRoute } from "@tanstack/react-router";
+import { createFileRoute, useLocation } from "@tanstack/react-router";
import { ToolsSettings } from "../components/settings/ToolsSettings";
import { validateToolsSearch } from "../components/settings/toolsSettings.logic";
@@ -6,9 +6,12 @@ import { validateToolsSearch } from "../components/settings/toolsSettings.logic"
function SettingsToolsRoute() {
const { tab } = Route.useSearch();
const navigate = Route.useNavigate();
+ // A settings search result links by hash, so it opens the tab it points at.
+ const hash = useLocation({ select: (location) => location.hash });
+ const resolvedTab = tab ?? (hash === "tools-mcp-servers" ? "mcp" : undefined);
return (
void navigate({
// The settings route keeps the scope; Skills is the default tab.
diff --git a/packages/contracts/src/agentTools.ts b/packages/contracts/src/agentTools.ts
index 71e07b5a74623..aa478cbf05e5a 100644
--- a/packages/contracts/src/agentTools.ts
+++ b/packages/contracts/src/agentTools.ts
@@ -37,12 +37,17 @@ export const isValidMcpServerName: (name: unknown) => name is McpServerName =
* An environment variable or HTTP header. A `sensitive` value is moved into
* the environment's secret store on save; settings and clients then see an
* empty value with `valueRedacted` set, and sending that back keeps it.
+ * A client that renamed the server or the variable sends `storedAs`, the
+ * names the secret was saved under, so the save moves it instead of losing it.
*/
export const McpServerVariable = Schema.Struct({
name: TrimmedNonEmptyString,
value: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
sensitive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
valueRedacted: Schema.optionalKey(Schema.Boolean),
+ storedAs: Schema.optionalKey(
+ Schema.Struct({ server: TrimmedNonEmptyString, variable: TrimmedNonEmptyString }),
+ ),
});
export type McpServerVariable = typeof McpServerVariable.Type;
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 84bbbf682471d..8b8d10380a2d8 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1548,9 +1548,15 @@ export const ServerSettingsPatch = Schema.Struct({
});
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
-/** A mixed settings patch must be authorized for every configuration domain it changes. */
+/**
+ * A mixed settings patch must be authorized for every configuration domain it changes.
+ * A patch replaces a project's whole override entry, so it resends that
+ * project's servers with any change; with `current`, a server sent back
+ * exactly as stored is not counted as a provider change.
+ */
export function requiredScopesForServerSettingsPatch(
patch: ServerSettingsPatch,
+ current?: Pick,
): ReadonlyArray {
let changesProviders = false;
let changesSettings = false;
@@ -1571,8 +1577,13 @@ export function requiredScopesForServerSettingsPatch(
// So does a project entry that carries its own server. Switching an
// inherited server off or on for a project is an ordinary setting.
if (
- Object.values(patch.projectSettingsOverrides ?? {}).some((entry) =>
- Object.values(entry?.mcpServers ?? {}).some((server) => server.transport !== undefined),
+ Object.entries(patch.projectSettingsOverrides ?? {}).some(([projectId, entry]) =>
+ Object.entries(entry?.mcpServers ?? {}).some(([name, server]) => {
+ if (server.transport === undefined) return false;
+ const stored =
+ current?.projectSettingsOverrides[projectId as ProjectId]?.mcpServers?.[name]?.transport;
+ return stored === undefined || JSON.stringify(stored) !== JSON.stringify(server.transport);
+ }),
)
) {
changesProviders = true;
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index ec44a6237e010..0b78eca94b51c 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -35,6 +35,7 @@ import {
} from "@t3tools/contracts";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
+import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
@@ -681,18 +682,21 @@ interface AcpMcpContext {
/**
* The user's servers from Settings → Tools, passed through as plain ACP
- * entries. A bare command name is left to the agent's PATH lookup. Http
- * entries are dropped later for agents that do not advertise http support.
+ * entries. ACP wants an absolute command, so a bare name such as `npx` is
+ * looked up on the PATH the agent inherits; one that cannot be found is sent
+ * as typed. Http entries are dropped later for agents that do not advertise
+ * http support.
*/
function acpUserMcpServers(
servers: ReadonlyArray,
+ resolveCommand: (command: string) => string,
): ReadonlyArray {
return servers.map((server) =>
server.transport.type === "stdio"
? {
// Untyped like T3's own entry: the shape every ACP version accepts.
name: server.name,
- command: server.transport.command,
+ command: resolveCommand(server.transport.command),
args: [...server.transport.args],
env: Object.entries(mcpServerVariableRecord(server.transport.env)).map(
([name, value]) => ({ name, value }),
@@ -712,13 +716,14 @@ function acpUserMcpServers(
function acpMcpContext(
session: McpProviderSession.McpProviderSessionConfig | undefined,
self: SelfInvocation,
+ resolveCommand: (command: string) => string = (command) => command,
): AcpMcpContext {
if (session === undefined) {
return { servers: [], acpServers: [] };
}
// Both lists carry them: an agent that takes T3's server over ACP gets
// only `acpServers`, so the user's servers would otherwise be lost.
- const userServers = acpUserMcpServers(session.tools?.servers ?? []);
+ const userServers = acpUserMcpServers(session.tools?.servers ?? [], resolveCommand);
// Stdio is ACP's required baseline MCP transport. Agents that advertise
// optional http support still routinely fail to wire injected http servers
// through to their backend (codex-acp 1.2.0 and pi-acp both drop them), so
@@ -1526,10 +1531,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const { flavor, selfInvocation: self } = options;
+ const resolveExecutable = yield* SpawnExecutableResolution;
+ const resolveCommand = (command: string) =>
+ resolveExecutable(command, process.platform, process.env) ?? command;
const readMcpContext = (threadId: ThreadId | null) =>
threadId === null
? Effect.succeed(acpMcpContext(undefined, self))
- : mcpSessions.read(threadId).pipe(Effect.map((session) => acpMcpContext(session, self)));
+ : mcpSessions
+ .read(threadId)
+ .pipe(Effect.map((session) => acpMcpContext(session, self, resolveCommand)));
const driver = flavor.driver;
const continuationRequests = options.continuationRequests;
const postSettleContinuationEnabled =
diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts
index 7ddaff6b24e97..16af010642679 100644
--- a/packages/provider-opencode/src/server/adapter.ts
+++ b/packages/provider-opencode/src/server/adapter.ts
@@ -999,34 +999,35 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
},
}),
);
- // The user's servers are additions: one that fails to register must
- // not stop the session, so each logs and moves on.
- for (const server of mcpSession.tools?.servers ?? []) {
- yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
- client.mcp.add({
- name: server.name,
- config:
- server.transport.type === "stdio"
- ? {
- type: "local",
- command: [server.transport.command, ...server.transport.args],
- environment: mcpServerVariableRecord(server.transport.env),
- }
- : {
- type: "remote",
- url: server.transport.url,
- headers: mcpServerVariableRecord(server.transport.headers),
- },
+ }
+ // The user's servers are additions that do not need to reach T3, so
+ // an external server gets them too. One that fails to register must
+ // not stop the session, so each logs and moves on.
+ for (const server of mcpSession?.tools?.servers ?? []) {
+ yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
+ client.mcp.add({
+ name: server.name,
+ config:
+ server.transport.type === "stdio"
+ ? {
+ type: "local",
+ command: [server.transport.command, ...server.transport.args],
+ environment: mcpServerVariableRecord(server.transport.env),
+ }
+ : {
+ type: "remote",
+ url: server.transport.url,
+ headers: mcpServerVariableRecord(server.transport.headers),
+ },
+ }),
+ ).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Could not add an MCP server to OpenCode.", {
+ server: server.name,
+ cause,
}),
- ).pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("Could not add an MCP server to OpenCode.", {
- server: server.name,
- cause,
- }),
- ),
- );
- }
+ ),
+ );
}
const now = yield* DateTime.now;
@@ -3143,6 +3144,24 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
client.session.get({ sessionID: sessionId }),
);
const nativeSession = unwrapData("session.get", response);
+ // The saved rules may predate a skill switched off since; a
+ // resume that knows its policy brings them up to date.
+ const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId;
+ if (threadInput.runtimePolicy !== undefined && appThreadId !== null) {
+ const permission = openCodePermissionRules(
+ threadInput.runtimePolicy,
+ (yield* mcpSessions.read(appThreadId))?.tools?.disabledSkills ?? [],
+ );
+ const saved = nativeSession.permission ?? [];
+ const unchanged =
+ saved.length === permission.length &&
+ saved.every((rule, index) => permissionRuleEquals(rule, permission[index]!));
+ if (!unchanged) {
+ yield* sdkCall("session.update", { sessionID: sessionId, permission }, () =>
+ client.session.update({ sessionID: sessionId, permission }),
+ );
+ }
+ }
const resumedAt = yield* DateTime.now;
const providerThread = {
...threadInput.providerThread,
@@ -3654,10 +3673,16 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
return yield* protocolError(
"OpenCode did not preserve the requested rewind boundary.",
);
+ // The fork replaces the session, so it needs the skill rules too.
+ const appThreadId = rollbackInput.providerThread.appThreadId;
+ const disabledSkills =
+ appThreadId === null
+ ? []
+ : ((yield* mcpSessions.read(appThreadId))?.tools?.disabledSkills ?? []);
yield* sdkCall("session.update", { sessionID: fork.id }, () =>
client.session.update({
sessionID: fork.id,
- permission: openCodePermissionRules(input.runtimePolicy),
+ permission: openCodePermissionRules(input.runtimePolicy, disabledSkills),
}),
);
retainedThread = {
diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts
index 82084243eded6..775e9aa07bb4c 100644
--- a/packages/provider-opencode/src/server/v2/adapter.ts
+++ b/packages/provider-opencode/src/server/v2/adapter.ts
@@ -412,6 +412,8 @@ interface UserMcpRegistration {
readonly names: ReadonlyArray;
readonly directory: string;
readonly fingerprint: string;
+ /** False when a server failed to register, so the next turn tries again. */
+ readonly complete: boolean;
}
type TurnTerminal =
@@ -504,12 +506,14 @@ const mcpRules = (
{ action: "t3-code-*", resource: "*", effect: "deny" as const },
{ action: `${mcpServerName}_*`, resource: "*", effect: "allow" as const },
]),
+ // Registrations are shared per directory, so another thread's user servers
+ // are denied even when this thread has none of its own.
+ ...(mcpServerName === null && userMcpPrefix === null
+ ? []
+ : [{ action: "t3u-*", resource: "*", effect: "deny" as const }]),
...(userMcpPrefix === null
? []
- : [
- { action: "t3u-*", resource: "*", effect: "deny" as const },
- { action: `${userMcpPrefix}-*`, resource: "*", effect: "allow" as const },
- ]),
+ : [{ action: `${userMcpPrefix}-*`, resource: "*", effect: "allow" as const }]),
];
const sessionRules = (
@@ -3031,8 +3035,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
policy.runtimeMode === "full-access" && !plan
? []
: yield* pathsFor(thread.directory, plan ? [thread.agent, "plan"] : [thread.agent]);
- // Rules for the user's servers only exist once a thread has some, so a
- // session without them keeps exactly the rules it always had.
+ // Only a thread with servers of its own gets the allow rule for them.
const hasUserMcp =
appThreadId !== null &&
((yield* mcpSessions.read(ThreadId.make(appThreadId)))?.tools?.servers.length ?? 0) > 0;
@@ -3312,13 +3315,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
directory: string,
mcpSession: McpProviderSession.McpProviderSessionConfig | undefined,
) {
- const tools =
- mcpSession === undefined || connection.external
- ? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS
- : (mcpSession.tools ?? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS);
+ // Unlike T3's own endpoint, the user's servers do not depend on reaching
+ // T3, so an external OpenCode server gets them too.
+ const tools = mcpSession?.tools ?? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS;
const current = state.userMcp;
if (
current !== undefined &&
+ current.complete &&
current.directory === directory &&
current.fingerprint === tools.fingerprint
) {
@@ -3362,7 +3365,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
);
if (added) names.push(name);
}
- state.userMcp = { names, directory, fingerprint: tools.fingerprint };
+ state.userMcp = {
+ names,
+ directory,
+ fingerprint: tools.fingerprint,
+ complete: names.length === tools.servers.length,
+ };
});
/**
diff --git a/packages/shared/src/agentTools.test.ts b/packages/shared/src/agentTools.test.ts
index d8b97677d251d..1641e5e151041 100644
--- a/packages/shared/src/agentTools.test.ts
+++ b/packages/shared/src/agentTools.test.ts
@@ -45,8 +45,10 @@ describe("project tools overrides", () => {
supabase: projectSupabase,
// Switches an inherited server off without restating it.
sentry: { enabled: false },
- // A switch for a server the environment no longer has is ignored.
+ // A switch for a server the environment no longer has is ignored,
+ // including names an object inherits.
removed: { enabled: true },
+ constructor: { enabled: true },
playwright: {
enabled: true,
transport: { type: "stdio", command: "npx", args: ["@playwright/mcp"], env: [] },
diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts
index 84dd4cea15616..5895f2226b370 100644
--- a/packages/shared/src/projectSettings.ts
+++ b/packages/shared/src/projectSettings.ts
@@ -226,7 +226,7 @@ function mergeProjectMcpServers(
merged[name] = { enabled: entry.enabled, transport: entry.transport };
continue;
}
- const inherited = environment[name];
+ const inherited = Object.hasOwn(environment, name) ? environment[name] : undefined;
if (inherited !== undefined) merged[name] = { ...inherited, enabled: entry.enabled };
}
return merged as McpServers;
From 8e7f0820aebd37a62e9518a3d69a80e53bcbf918 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 11:49:26 -0700
Subject: [PATCH 05/35] fix(server): read the host platform through its
injected reference
Co-Authored-By: Claude Opus 5.5
---
packages/provider-acp/src/server/adapter.ts | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 0b78eca94b51c..e2feba5925970 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -35,6 +35,7 @@ import {
} from "@t3tools/contracts";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
+import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
import * as Cause from "effect/Cause";
@@ -1532,8 +1533,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const { flavor, selfInvocation: self } = options;
const resolveExecutable = yield* SpawnExecutableResolution;
+ const hostPlatform = yield* HostProcessPlatform;
+ const hostEnvironment = yield* HostProcessEnvironment;
const resolveCommand = (command: string) =>
- resolveExecutable(command, process.platform, process.env) ?? command;
+ resolveExecutable(command, hostPlatform, hostEnvironment) ?? command;
const readMcpContext = (threadId: ThreadId | null) =>
threadId === null
? Effect.succeed(acpMcpContext(undefined, self))
From 79912b208f29d7e1a596c6c2a4b270210d85292f Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 11:52:25 -0700
Subject: [PATCH 06/35] fix(server): keep MCP server secrets out of Claude's
process arguments
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The SDK passes mcpServers to the CLI as an inline --mcp-config argument,
which any local user can read. A sensitive env value or header from
Settings → Tools now goes into the child's environment and --mcp-config
carries a ${VAR} reference, the same as T3's own token since #17408.
Checked against claude 2.1.292: a stdio server received the expanded value.
Co-Authored-By: Claude Opus 5.5
---
.../Adapters/ClaudeAdapterV2.test.ts | 5 ++-
.../Adapters/ClaudeAdapterV2.ts | 40 +++++++++++++++----
2 files changed, 35 insertions(+), 10 deletions(-)
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 73b74734331e0..64dd8448636d0 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -667,6 +667,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
mcpSession,
readOnlySandbox: false,
});
+ // The secret reaches the child's environment, never `--mcp-config`.
assert.deepEqual(overrides, {
allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD, "mcp__supabase__*"],
mcpServers: {
@@ -674,12 +675,12 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
type: "stdio",
command: "npx",
args: ["-y", "@supabase/mcp-server-supabase"],
- env: { SUPABASE_ACCESS_TOKEN: "token" },
+ env: { SUPABASE_ACCESS_TOKEN: "${T3_MCP_SECRET_0}" },
},
...T3_MCP_SERVERS,
},
sdkSettings: { skillOverrides: { "grill-me": "off" } },
- mcpEnvironment: T3_MCP_ENVIRONMENT,
+ mcpEnvironment: { T3_MCP_SECRET_0: "token", ...T3_MCP_ENVIRONMENT },
});
// Read-only sandboxes keep the user's servers behind the permission prompt.
assert.deepEqual(
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index cd44af7c1220f..5e8522424aae9 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -66,6 +66,7 @@ import {
type ProviderRequestKind,
type ProviderUserInputAnswers,
type ProviderThreadId,
+ type McpServerVariable,
type ResolvedMcpServer,
type ThreadId,
} from "@t3tools/contracts";
@@ -999,12 +1000,13 @@ export function claudeMcpQueryOverrides(input: {
const userAllowedTools = input.readOnlySandbox
? []
: tools.servers.map((server) => `mcp__${server.name}__*`);
+ const userServers = claudeUserMcpServers(tools.servers);
return {
allowedTools: Array.from(
new Set([...(input.allowedTools ?? []), ...mcpAllowedTools, ...userAllowedTools]),
),
mcpServers: {
- ...claudeUserMcpServers(tools.servers),
+ ...userServers.mcpServers,
"t3-code": {
type: "http",
url: session.endpoint,
@@ -1026,14 +1028,35 @@ export function claudeMcpQueryOverrides(input: {
),
},
}),
- mcpEnvironment: { [CLAUDE_T3_MCP_AUTHORIZATION_ENV]: session.authorizationHeader },
+ mcpEnvironment: {
+ ...userServers.environment,
+ [CLAUDE_T3_MCP_AUTHORIZATION_ENV]: session.authorizationHeader,
+ },
};
}
-function claudeUserMcpServers(
- servers: ReadonlyArray,
-): NonNullable {
- return Object.fromEntries(
+/**
+ * The user's servers for `--mcp-config`. Like T3's own token, a sensitive
+ * env value or header becomes a `${VAR}` reference there, and its value goes
+ * into the child's environment.
+ */
+function claudeUserMcpServers(servers: ReadonlyArray): {
+ readonly mcpServers: NonNullable;
+ readonly environment: Readonly>;
+} {
+ const environment: Record = {};
+ const values = (server: string, variables: ReadonlyArray) => {
+ const record = mcpServerVariableRecord(variables);
+ for (const variable of variables) {
+ if (!variable.sensitive || !Object.hasOwn(record, variable.name)) continue;
+ // Indexed, so two names that read the same once uppercased stay apart.
+ const reference = `T3_MCP_SECRET_${Object.keys(environment).length}`;
+ environment[reference] = record[variable.name]!;
+ record[variable.name] = `\${${reference}}`;
+ }
+ return record;
+ };
+ const mcpServers = Object.fromEntries(
servers.map((server) => [
server.name,
server.transport.type === "stdio"
@@ -1041,15 +1064,16 @@ function claudeUserMcpServers(
type: "stdio" as const,
command: server.transport.command,
args: [...server.transport.args],
- env: mcpServerVariableRecord(server.transport.env),
+ env: values(server.name, server.transport.env),
}
: {
type: "http" as const,
url: server.transport.url,
- headers: mcpServerVariableRecord(server.transport.headers),
+ headers: values(server.name, server.transport.headers),
},
]),
);
+ return { mcpServers, environment };
}
function providerSession(input: {
From f1f98fbfc1d9136ad4166e89eca1895ef4986ce2 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 11:57:00 -0700
Subject: [PATCH 07/35] fix: keep both secrets when a rename swaps two names,
and group repo skills by scope
- Secret copies read every source before anything is written, so swapping
two variable names no longer leaves both with one value.
- A repository skill under a folder named plugins stays in Repository; the
plugins path only classifies skills a provider reports without a scope.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/serverSettings.test.ts | 56 ++++++++++++++
apps/server/src/serverSettings.ts | 76 ++++++++++---------
.../settings/toolsSettings.logic.test.ts | 15 ++++
.../settings/toolsSettings.logic.ts | 9 ++-
4 files changed, 118 insertions(+), 38 deletions(-)
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index c4dc8ed29db79..8b9c7db35de23 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1638,6 +1638,62 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(layerServerSettingsWithSecrets())),
);
+ it.effect("keeps both MCP secrets when two variables swap names", () =>
+ Effect.gen(function* () {
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const server = (
+ env: ReadonlyArray<{
+ name: string;
+ value: string;
+ sensitive: boolean;
+ valueRedacted?: boolean;
+ storedAs?: { server: string; variable: string };
+ }>,
+ ) => ({
+ enabled: true,
+ transport: { type: "stdio" as const, command: "npx", args: [], env },
+ });
+ yield* serverSettings.updateSettings({
+ mcpServers: {
+ db: server([
+ { name: "A", value: "value-a", sensitive: true },
+ { name: "B", value: "value-b", sensitive: true },
+ ]),
+ },
+ });
+
+ const swapped = yield* serverSettings.updateSettings({
+ mcpServers: {
+ db: server([
+ {
+ name: "A",
+ value: "",
+ sensitive: true,
+ valueRedacted: true,
+ storedAs: { server: "db", variable: "B" },
+ },
+ {
+ name: "B",
+ value: "",
+ sensitive: true,
+ valueRedacted: true,
+ storedAs: { server: "db", variable: "A" },
+ },
+ ]),
+ },
+ });
+
+ const env = swapped.mcpServers.db?.transport;
+ assert.deepEqual(
+ env?.type === "stdio" ? env.env.map((variable) => [variable.name, variable.value]) : [],
+ [
+ ["A", "value-b"],
+ ["B", "value-a"],
+ ],
+ );
+ }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
+ );
+
it.effect("moves a sensitive MCP value written into settings.json into the secret store", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 83c17862df08f..660b7310eedd7 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -1261,44 +1261,50 @@ const make = Effect.gen(function* () {
}),
),
);
- // Copies read their source before any removal in the same save drops it.
- const ordered = [
- ...changes.filter((change) => change.kind === "copy"),
- ...changes.filter((change) => change.kind !== "copy"),
- ];
+ const apply = (copied: ReadonlyMap>) =>
+ Effect.forEach(
+ changes,
+ (change) =>
+ Effect.gen(function* () {
+ let value: Uint8Array | undefined;
+ if (change.kind === "write") value = change.value;
+ if (change.kind === "copy") {
+ const source = copied.get(change.secretName) ?? Option.none();
+ if (Option.isNone(source)) return;
+ value = source.value;
+ }
+ const previousValue = yield* readSecret(change, change.secretName);
+ // A store operation may mutate before reporting an error (for example chmod after rename).
+ applied.push({ ...change, previousValue });
+ yield* (
+ value !== undefined
+ ? secretStore.set(change.secretName, value)
+ : secretStore.remove(change.secretName)
+ ).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ServerSettingsError({
+ settingsPath,
+ operation: change.kind === "remove" ? change.operation : "write-secret",
+ providerInstanceId: change.providerInstanceId,
+ environmentVariable: change.environmentVariable,
+ cause,
+ }),
+ ),
+ );
+ }),
+ { discard: true },
+ );
+ // Every copy reads its source before anything is written or removed, so a
+ // rename that swaps two names, or drops the old one, still moves both values.
return Effect.forEach(
- ordered,
+ changes.filter((change) => change.kind === "copy"),
(change) =>
- Effect.gen(function* () {
- let value: Uint8Array | undefined;
- if (change.kind === "write") value = change.value;
- if (change.kind === "copy") {
- const source = yield* readSecret(change, change.from);
- if (Option.isNone(source)) return;
- value = source.value;
- }
- const previousValue = yield* readSecret(change, change.secretName);
- // A store operation may mutate before reporting an error (for example chmod after rename).
- applied.push({ ...change, previousValue });
- yield* (
- value !== undefined
- ? secretStore.set(change.secretName, value)
- : secretStore.remove(change.secretName)
- ).pipe(
- Effect.mapError(
- (cause) =>
- new ServerSettingsError({
- settingsPath,
- operation: change.kind === "remove" ? change.operation : "write-secret",
- providerInstanceId: change.providerInstanceId,
- environmentVariable: change.environmentVariable,
- cause,
- }),
- ),
- );
- }),
- { discard: true },
+ readSecret(change, change.from).pipe(
+ Effect.map((source) => [change.secretName, source] as const),
+ ),
).pipe(
+ Effect.flatMap((sources) => apply(new Map(sources))),
Effect.tapError(() => rollback),
Effect.as(rollback),
);
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index 9a724d3e04cbc..8b3c6bb37a1a6 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -54,6 +54,19 @@ describe("collectSkillRows", () => {
scope: "repo",
enabled: true,
},
+ // A repository folder that happens to be called `plugins`.
+ {
+ name: "release",
+ path: "/work/t3/packages/plugins/.agents/skills/release/SKILL.md",
+ scope: "repo",
+ enabled: true,
+ },
+ // A plugin skill the provider reports with no scope.
+ {
+ name: "docs",
+ path: "/home/me/.claude/plugins/cache/acme/docs/skills/docs/SKILL.md",
+ enabled: true,
+ },
]),
provider("cursor", [], { enabled: false }),
],
@@ -62,8 +75,10 @@ describe("collectSkillRows", () => {
expect(
rows.map((row) => [row.name, row.group, row.paths.length, row.providers.length]),
).toEqual([
+ ["release", "project", 1, 1],
["test-t3-app", "project", 1, 1],
["frontend-design", "personal", 2, 2],
+ ["docs", "plugin", 1, 1],
]);
});
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 853c0ce2f9291..0562ebfad81a4 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -52,8 +52,6 @@ export interface SkillRow {
}
function skillGroup(skill: ServerProviderSkill): SkillGroupKind {
- const path = skill.path.replaceAll("\\", "/");
- if (path.includes("/plugins/")) return "plugin";
switch (resolveProviderSkillSourceKind(skill)) {
case "project":
case "repo":
@@ -64,7 +62,12 @@ function skillGroup(skill: ServerProviderSkill): SkillGroupKind {
return "plugin";
case "system":
case "other":
- return skill.scope?.trim().toLowerCase() === "plugin" ? "plugin" : "system";
+ // Some providers report plugin skills with no scope; their folder is the
+ // only sign. A repository folder named `plugins` already has a scope.
+ return skill.scope?.trim().toLowerCase() === "plugin" ||
+ skill.path.replaceAll("\\", "/").includes("/plugins/")
+ ? "plugin"
+ : "system";
}
}
From 35a5d4f86eb10b2ad382d245385bc597b10dab89 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 11:58:23 -0700
Subject: [PATCH 08/35] fix(server): map a repeated MCP variable name to one
Claude secret
Two sensitive entries with the same name made the second reference point
at the first one's placeholder. Each name now gets one reference holding
its last value, matching how the variable record resolves duplicates.
Co-Authored-By: Claude Opus 5.5
---
.../Adapters/ClaudeAdapterV2.test.ts | 33 +++++++++++++++++++
.../Adapters/ClaudeAdapterV2.ts | 16 +++++----
2 files changed, 42 insertions(+), 7 deletions(-)
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 64dd8448636d0..358af0e1d1b7c 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -687,6 +687,39 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: true }).allowedTools,
ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS,
);
+ // A repeated name maps to one reference holding its last value.
+ const repeated = ClaudeAdapterV2.claudeMcpQueryOverrides({
+ mcpSession: {
+ ...mcpSession,
+ tools: {
+ servers: [
+ {
+ name: "linear",
+ transport: {
+ type: "http",
+ url: "https://mcp.linear.app/mcp",
+ headers: [
+ { name: "Authorization", value: "first", sensitive: true },
+ { name: "Authorization", value: "second", sensitive: true },
+ ],
+ },
+ },
+ ],
+ disabledSkills: [],
+ fingerprint: "b",
+ },
+ },
+ readOnlySandbox: false,
+ });
+ assert.deepEqual(repeated.mcpServers?.linear, {
+ type: "http",
+ url: "https://mcp.linear.app/mcp",
+ headers: { Authorization: "${T3_MCP_SECRET_0}" },
+ });
+ assert.deepEqual(repeated.mcpEnvironment, {
+ T3_MCP_SECRET_0: "second",
+ ...T3_MCP_ENVIRONMENT,
+ });
const initialKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy, overrides);
const clearedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 5e8522424aae9..37d147fb20963 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -1045,14 +1045,16 @@ function claudeUserMcpServers(servers: ReadonlyArray): {
readonly environment: Readonly>;
} {
const environment: Record = {};
- const values = (server: string, variables: ReadonlyArray) => {
+ const values = (variables: ReadonlyArray) => {
const record = mcpServerVariableRecord(variables);
- for (const variable of variables) {
- if (!variable.sensitive || !Object.hasOwn(record, variable.name)) continue;
+ // A repeated name keeps its last entry, as the record does.
+ const sensitive = new Map(variables.map((variable) => [variable.name, variable.sensitive]));
+ for (const name of Object.keys(record)) {
+ if (sensitive.get(name) !== true) continue;
// Indexed, so two names that read the same once uppercased stay apart.
const reference = `T3_MCP_SECRET_${Object.keys(environment).length}`;
- environment[reference] = record[variable.name]!;
- record[variable.name] = `\${${reference}}`;
+ environment[reference] = record[name]!;
+ record[name] = `\${${reference}}`;
}
return record;
};
@@ -1064,12 +1066,12 @@ function claudeUserMcpServers(servers: ReadonlyArray): {
type: "stdio" as const,
command: server.transport.command,
args: [...server.transport.args],
- env: values(server.name, server.transport.env),
+ env: values(server.transport.env),
}
: {
type: "http" as const,
url: server.transport.url,
- headers: values(server.name, server.transport.headers),
+ headers: values(server.transport.headers),
},
]),
);
From 9f0fa2333a4003dae4a7036af3db8db657292b59 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 12:03:36 -0700
Subject: [PATCH 09/35] =?UTF-8?q?fix(server):=20ask=20before=20Claude=20us?=
=?UTF-8?q?es=20a=20Settings=20=E2=86=92=20Tools=20server=20in=20modes=20t?=
=?UTF-8?q?hat=20ask?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The user's servers were added to Claude's allowedTools, which skips the
permission prompt in approval-required and auto-accept sessions. Full
access already runs them without asking, so the allow rule only bypassed
the modes that ask. Their tools now go through the session's approval.
Co-Authored-By: Claude Opus 5.5
---
.../Adapters/ClaudeAdapterV2.test.ts | 8 ++------
.../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts | 12 +++---------
2 files changed, 5 insertions(+), 15 deletions(-)
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 358af0e1d1b7c..e2afd8f80231a 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -669,7 +669,8 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
});
// The secret reaches the child's environment, never `--mcp-config`.
assert.deepEqual(overrides, {
- allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD, "mcp__supabase__*"],
+ // Its tools go through the session's approval like any other tool.
+ allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD],
mcpServers: {
supabase: {
type: "stdio",
@@ -682,11 +683,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
sdkSettings: { skillOverrides: { "grill-me": "off" } },
mcpEnvironment: { T3_MCP_SECRET_0: "token", ...T3_MCP_ENVIRONMENT },
});
- // Read-only sandboxes keep the user's servers behind the permission prompt.
- assert.deepEqual(
- ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: true }).allowedTools,
- ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS,
- );
// A repeated name maps to one reference holding its last value.
const repeated = ClaudeAdapterV2.claudeMcpQueryOverrides({
mcpSession: {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 37d147fb20963..8cdfc006fb4f7 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -994,17 +994,11 @@ export function claudeMcpQueryOverrides(input: {
const mcpAllowedTools = input.readOnlySandbox
? CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS
: [CLAUDE_T3_MCP_TOOL_WILDCARD];
- // Servers the user added in T3 are trusted like T3's own: their tools are
- // pre-approved outside read-only sandboxes, where the permission prompt
- // still decides.
- const userAllowedTools = input.readOnlySandbox
- ? []
- : tools.servers.map((server) => `mcp__${server.name}__*`);
+ // The user's servers are not pre-approved: full access already skips the
+ // prompt, so an allow rule would only bypass the modes that ask to approve.
const userServers = claudeUserMcpServers(tools.servers);
return {
- allowedTools: Array.from(
- new Set([...(input.allowedTools ?? []), ...mcpAllowedTools, ...userAllowedTools]),
- ),
+ allowedTools: Array.from(new Set([...(input.allowedTools ?? []), ...mcpAllowedTools])),
mcpServers: {
...userServers.mcpServers,
"t3-code": {
From 6396c81c4e132ba6f8be6eb1557e5e00fb533a3d Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 18:55:11 -0700
Subject: [PATCH 10/35] feat(server): install skills from a source with the
bundled skills CLI
Adds a hidden `t3 skills-cli` subcommand that runs the pinned skills CLI
(vercel-labs/skills 1.7.1, telemetry off) and a SkillLibrary service with
preview, install, update, remove and inspect, exposed as skills.* RPCs.
Installs land where `npx skills` puts them, with links for agents that
read only their own folder, chosen from a per-agent folder table.
Co-Authored-By: Claude Opus 5.5
---
apps/server/package.json | 1 +
apps/server/src/auth/RpcAuthorization.ts | 4 +
apps/server/src/bin.ts | 4 +
apps/server/src/binCli.ts | 2 +
apps/server/src/cli/skillsCli.ts | 24 +
.../src/observability/RpcInstrumentation.ts | 5 +
apps/server/src/server.ts | 2 +
apps/server/src/skills/SkillLibrary.test.ts | 229 +++++++++
apps/server/src/skills/SkillLibrary.ts | 444 ++++++++++++++++++
apps/server/src/skills/SkillsCli.ts | 139 ++++++
apps/server/src/ws.ts | 7 +
.../contracts/src/clientRpcPermissions.ts | 7 +
packages/contracts/src/index.ts | 1 +
packages/contracts/src/rpc.ts | 50 ++
packages/contracts/src/skills.ts | 133 ++++++
packages/provider-core/package.json | 4 +
.../src/server/AgentSkillFolders.ts | 93 ++++
pnpm-lock.yaml | 13 +
18 files changed, 1162 insertions(+)
create mode 100644 apps/server/src/cli/skillsCli.ts
create mode 100644 apps/server/src/skills/SkillLibrary.test.ts
create mode 100644 apps/server/src/skills/SkillLibrary.ts
create mode 100644 apps/server/src/skills/SkillsCli.ts
create mode 100644 packages/contracts/src/skills.ts
create mode 100644 packages/provider-core/src/server/AgentSkillFolders.ts
diff --git a/apps/server/package.json b/apps/server/package.json
index bb166039abd95..b3dbc1f9a157b 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -51,6 +51,7 @@
"node-pty": "^1.2.0-beta.15",
"playwright-core": "1.60.0",
"proper-lockfile": "4.1.2",
+ "skills": "1.7.1",
"stream-chain": "^4.2.5",
"stream-json": "3.6.0",
"yaml": "catalog:",
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 0f752c94f3601..9d32a456c8d4a 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -142,6 +142,10 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
+ // The server lists skill folders itself; a client never names a path.
+ [WS_METHODS.skillsInspect]: AuthFilesystemReadScope,
+ // A preview unpacks a source into a temp folder and deletes it.
+ [WS_METHODS.skillsPreview]: AuthFilesystemReadScope,
[WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
[WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts
index 063093874503d..cf53340ad863b 100644
--- a/apps/server/src/bin.ts
+++ b/apps/server/src/bin.ts
@@ -20,6 +20,10 @@ if (
if (command === "acp-mcp-bridge" || command === "acp-mcp-call") {
const { runAcpMcpCliFastPath } = await import("./mcp/AcpMcpStdioBridge.ts");
await runAcpMcpCliFastPath(command, process.argv.slice(3));
+ } else if (command === "skills-cli") {
+ // Option parsing belongs to the skills CLI, so it skips the T3 CLI entirely.
+ const { runSkillsCli } = await import("./cli/skillsCli.ts");
+ await runSkillsCli(process.argv.slice(3));
} else {
const { runCli } = await import("./binCli.ts");
runCli();
diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
index 76035ded632b6..3cacc7861b3d6 100644
--- a/apps/server/src/binCli.ts
+++ b/apps/server/src/binCli.ts
@@ -8,6 +8,7 @@ import * as CliError from "effect/cli/CliError";
import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { acpMcpBridgeCommand, acpMcpCallCommand } from "./cli/acpMcpBridge.ts";
+import { skillsCliCommand } from "./cli/skillsCli.ts";
import { authCommand } from "./cli/auth.ts";
import { appCommand } from "./cli/app.ts";
import { browserCommand } from "./cli/browser.ts";
@@ -67,6 +68,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
),
acpMcpBridgeCommand,
acpMcpCallCommand,
+ skillsCliCommand,
startCommand,
serveCommand,
appCommand,
diff --git a/apps/server/src/cli/skillsCli.ts b/apps/server/src/cli/skillsCli.ts
new file mode 100644
index 0000000000000..42f0f44922ae2
--- /dev/null
+++ b/apps/server/src/cli/skillsCli.ts
@@ -0,0 +1,24 @@
+import * as Effect from "effect/Effect";
+import { Argument, Command } from "effect/cli";
+
+/**
+ * `t3 skills-cli ` runs the bundled `skills` CLI (vercel-labs/skills),
+ * the installer `npx skills` runs. The server spawns it through this hidden
+ * subcommand so installs need no Node or npm of their own: the CLI is part of
+ * this build, and runs as a child so its `process.exit` and prompts stay out
+ * of the server.
+ */
+export async function runSkillsCli(args: ReadonlyArray): Promise {
+ // The CLI reads its command from argv[2] onward.
+ process.argv = [process.argv[0] ?? "node", "skills", ...args];
+ await import("skills/dist/cli.mjs");
+}
+
+/** Real invocations dispatch through the bin.ts fast path before the CLI graph loads. */
+export const skillsCliCommand = Command.make("skills-cli", {
+ args: Argument.String("args").pipe(Argument.variadic()),
+}).pipe(
+ Command.withDescription("Run the bundled skills installer."),
+ Command.unlisted,
+ Command.withHandler(({ args }) => Effect.promise(() => runSkillsCli(args))),
+);
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index b1abaf8d465c4..0447400994fa9 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -33,6 +33,11 @@ const RPC_AGGREGATES = {
[WS_METHODS.serverProbe]: "server",
[WS_METHODS.serverGetConfig]: "server",
[WS_METHODS.serverRefreshProviders]: "server",
+ [WS_METHODS.skillsInspect]: "skills",
+ [WS_METHODS.skillsPreview]: "skills",
+ [WS_METHODS.skillsInstall]: "skills",
+ [WS_METHODS.skillsUpdate]: "skills",
+ [WS_METHODS.skillsRemove]: "skills",
[WS_METHODS.serverUpdateProvider]: "server",
[WS_METHODS.providerAuthStart]: "provider",
[WS_METHODS.providerConsumeResetCredit]: "provider",
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 1bbe647dcd0cf..f032fa74ff85a 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -86,6 +86,7 @@ import * as CodexInstallation from "./provider/CodexInstallation.ts";
import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts";
import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegistry.ts";
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
+import * as SkillLibrary from "./skills/SkillLibrary.ts";
import * as ProviderUsageLimitsIngestion from "./provider/ProviderUsageLimitsIngestion.ts";
import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
@@ -589,6 +590,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
ProviderUsageLimitsIngestion.layer,
layerProviderInstallationRefresh,
ReplayMarkers.layer,
+ SkillLibrary.layer.pipe(Layer.provide(ProcessRunner.layer)),
).pipe(
// Core Services
Layer.provideMerge(layerOrchestrationApplication),
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
new file mode 100644
index 0000000000000..da5962e86d454
--- /dev/null
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -0,0 +1,229 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import {
+ ProjectId,
+ ProviderDriverKind,
+ ProviderInstanceId,
+ type ServerProvider,
+} from "@t3tools/contracts";
+import {
+ HostProcessArguments,
+ HostProcessEnvironment,
+ HostProcessIsExecutable,
+} from "@t3tools/shared/hostProcess";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+import * as Ref from "effect/Ref";
+
+import * as ProcessRunner from "../processRunner.ts";
+import * as ProjectService from "../project/ProjectService.ts";
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
+import * as SkillLibrary from "./SkillLibrary.ts";
+
+const SKILL = (name: string, description: string) =>
+ `---\nname: ${name}\ndescription: ${description}\n---\n\nUse ${name}.\n`;
+
+const claude: ServerProvider = {
+ driver: ProviderDriverKind.make("claudeAgent"),
+ instanceId: ProviderInstanceId.make("claude"),
+ enabled: true,
+ installed: true,
+ version: "2.1.0",
+ status: "ready",
+ checkedAt: "2026-10-09T00:00:00Z",
+ auth: { status: "authenticated" },
+ models: [],
+ skills: [],
+ slashCommands: [],
+};
+
+/**
+ * A temp HOME, a registered project and a local source with two skills (one
+ * with a script), plus the service built against them. The real `skills` CLI
+ * runs through the `t3 skills-cli` subcommand of this checkout's bin.ts.
+ */
+const withLibrary = (
+ body: (input: {
+ readonly library: SkillLibrary.SkillLibrary["Service"];
+ readonly home: string;
+ readonly project: string;
+ readonly source: string;
+ readonly providers: Ref.Ref>;
+ readonly refreshed: Ref.Ref>;
+ }) => Effect.Effect,
+) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const base = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-skill-library-" });
+ const home = path.join(base, "home");
+ const project = path.join(base, "project");
+ const source = path.join(base, "source");
+ yield* fileSystem.makeDirectory(home, { recursive: true });
+ yield* fileSystem.makeDirectory(project, { recursive: true });
+ yield* fileSystem.makeDirectory(path.join(source, "review", "bin"), { recursive: true });
+ yield* fileSystem.makeDirectory(path.join(source, "notes"), { recursive: true });
+ yield* fileSystem.writeFileString(
+ path.join(source, "review", "SKILL.md"),
+ SKILL("review", "Review a change."),
+ );
+ yield* fileSystem.writeFileString(path.join(source, "review", "bin", "run"), "#!/bin/sh\n");
+ yield* fileSystem.chmod(path.join(source, "review", "bin", "run"), 0o755);
+ yield* fileSystem.writeFileString(
+ path.join(source, "notes", "SKILL.md"),
+ SKILL("notes", "Take notes."),
+ );
+
+ const providers = yield* Ref.make>([claude]);
+ const refreshed = yield* Ref.make>([]);
+ const record = (entry: string) =>
+ Ref.update(refreshed, (entries) => [...entries, entry]).pipe(
+ Effect.andThen(Ref.get(providers)),
+ );
+ const registry = ProviderRegistry.ProviderRegistry.of({
+ getProviders: Ref.get(providers),
+ refreshInstance: (instanceId) => record(`instance:${instanceId}`),
+ refreshWorkspaceSnapshot: ({ instanceId, cwd }) => record(`workspace:${instanceId}:${cwd}`),
+ } as unknown as ProviderRegistry.ProviderRegistry["Service"]);
+ const realProject = yield* fileSystem.realPath(project);
+ const projects = ProjectService.ProjectService.of({
+ getByWorkspaceRoot: (root: string) =>
+ Effect.succeed(
+ path.resolve(root) === project || path.resolve(root) === realProject
+ ? Option.some({
+ id: ProjectId.make("project"),
+ title: "Project",
+ workspaceRoot: project,
+ })
+ : Option.none(),
+ ),
+ } as unknown as ProjectService.ProjectService["Service"]);
+
+ const entry = path.resolve(import.meta.dirname, "../bin.ts");
+ const library = yield* SkillLibrary.SkillLibrary.pipe(
+ Effect.provide(
+ SkillLibrary.layer.pipe(
+ Layer.provide(ProcessRunner.layer),
+ Layer.provide(Layer.succeed(ProviderRegistry.ProviderRegistry, registry)),
+ Layer.provide(Layer.succeed(ProjectService.ProjectService, projects)),
+ ),
+ ),
+ Effect.provideService(HostProcessEnvironment, {
+ ...process.env,
+ HOME: home,
+ XDG_STATE_HOME: "",
+ }),
+ Effect.provideService(HostProcessArguments, [process.execPath, entry]),
+ Effect.provideService(HostProcessIsExecutable, false),
+ );
+ return yield* body({ library, home, project, source, providers, refreshed });
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
+
+it.effect(
+ "previews a source without installing it",
+ () =>
+ withLibrary(({ library, home, source }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const preview = yield* library.preview({ source });
+ assert.deepEqual(
+ preview.skills.map((skill) => [skill.name, skill.description, skill.scripts]),
+ [
+ ["notes", "Take notes.", false],
+ ["review", "Review a change.", true],
+ ],
+ );
+ assert.deepEqual(
+ preview.skills[1]?.files.map((file) => [file.path, file.executable]),
+ [
+ ["SKILL.md", false],
+ ["bin/run", true],
+ ],
+ );
+ assert.isFalse(yield* fileSystem.exists(`${home}/.agents`));
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 120_000,
+);
+
+it.effect(
+ "installs into a project, reports the source, and removes it again",
+ () =>
+ withLibrary(({ library, project, source, providers, refreshed }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const result = yield* library.install({
+ source,
+ skills: ["review"],
+ target: { kind: "project", cwd: project },
+ });
+ assert.deepEqual(result.outcomes, [{ name: "review", status: "installed" }]);
+ // Claude reads only `.claude/skills`, so it gets a link there.
+ const claudeLink = path.join(project, ".claude", "skills", "review", "SKILL.md");
+ assert.isTrue(yield* fileSystem.exists(claudeLink));
+ assert.isFalse(yield* fileSystem.exists(path.join(project, ".agents/skills/notes")));
+ assert.deepEqual(yield* Ref.get(refreshed), [`workspace:claude:${project}`]);
+
+ yield* Ref.set(providers, [
+ {
+ ...claude,
+ workspaceSnapshots: [
+ {
+ cwd: project,
+ checkedAt: "2026-10-09T00:00:00Z",
+ slashCommands: [],
+ skills: [{ name: "review", path: claudeLink, scope: "project", enabled: true }],
+ },
+ ],
+ },
+ ]);
+ const inspected = yield* library.inspect({ cwd: project });
+ assert.equal(inspected.folders.length, 1);
+ const folder = inspected.folders[0];
+ assert.equal(folder?.path, claudeLink);
+ assert.equal(
+ folder?.folder,
+ yield* fileSystem.realPath(path.join(project, ".agents/skills/review")),
+ );
+ assert.isTrue(folder?.scripts);
+ // A project lock keeps a local source relative to the project, so it travels with it.
+ assert.deepEqual(folder?.installed, {
+ target: { kind: "project", cwd: project },
+ source: path.relative(yield* fileSystem.realPath(project), source),
+ });
+
+ const updated = yield* library.update({
+ name: "review",
+ target: { kind: "project", cwd: project },
+ });
+ assert.deepEqual(updated.outcomes, [{ name: "review", status: "installed" }]);
+
+ yield* library.remove({ name: "review", target: { kind: "project", cwd: project } });
+ assert.isFalse(yield* fileSystem.exists(path.join(project, ".agents/skills/review")));
+ assert.isFalse(yield* fileSystem.exists(path.join(project, ".claude/skills/review")));
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 180_000,
+);
+
+it.effect(
+ "refuses folders that aren't projects and skills the CLI didn't install",
+ () =>
+ withLibrary(({ library, home, source }) =>
+ Effect.gen(function* () {
+ const notProject = yield* library
+ .install({ source, skills: ["review"], target: { kind: "project", cwd: home } })
+ .pipe(Effect.flip);
+ assert.equal(notProject.reason, "projectNotRegistered");
+ const notInstalled = yield* library
+ .remove({ name: "review", target: { kind: "environment" } })
+ .pipe(Effect.flip);
+ assert.equal(notInstalled.reason, "notInstalled");
+ }),
+ ),
+ 60_000,
+);
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
new file mode 100644
index 0000000000000..d3d35a33a269e
--- /dev/null
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -0,0 +1,444 @@
+/**
+ * SkillLibrary - installs skills from a source and describes the skill
+ * folders the environment's agents report.
+ *
+ * Installs go through the `skills` CLI (see SkillsCli.ts), into
+ * `.agents/skills` at home or in a project, with links for agents that read
+ * their own folder. The CLI's lock files (`~/.agents/.skill-lock.json`, or
+ * `$XDG_STATE_HOME/skills/.skill-lock.json`, and a project's
+ * `skills-lock.json`) record where each install came from; this module reads
+ * them to group skills by source and to update or remove only what the CLI
+ * installed. Turning skills on or off stays in settings.
+ *
+ * @module SkillLibrary
+ */
+import {
+ type InstalledSkillInput,
+ type ProviderDriverKind,
+ type ServerProvider,
+ type SkillFileEntry,
+ type SkillFolderInfo,
+ type SkillInspectInput,
+ type SkillInspectResult,
+ type SkillInstallInput,
+ type SkillInstallResult,
+ type SkillInstallTarget,
+ SkillLibraryError,
+ type SkillPreviewInput,
+ type SkillPreviewResult,
+} from "@t3tools/contracts";
+import {
+ STANDARD_SKILL_FOLDER,
+ skillsCliInstallAgents,
+} from "@t3tools/provider-core/server/AgentSkillFolders";
+import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
+import { fromLenientJson } from "@t3tools/shared/schemaJson";
+import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
+import * as Effect from "effect/Effect";
+import * as Hex from "effect/encoding/Hex";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+import { parse as parseYamlDocument } from "yaml";
+
+import * as ProjectService from "../project/ProjectService.ts";
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
+import * as SkillsCli from "./SkillsCli.ts";
+
+export class SkillLibrary extends Context.Service<
+ SkillLibrary,
+ {
+ /** Facts about each SKILL.md the enabled agents report, for `cwd` and the environment. */
+ readonly inspect: (input: SkillInspectInput) => Effect.Effect;
+ /** The skills in a source, read from a throwaway install. */
+ readonly preview: (
+ input: SkillPreviewInput,
+ ) => Effect.Effect;
+ readonly install: (
+ input: SkillInstallInput,
+ ) => Effect.Effect;
+ /** Reinstall a skill the CLI installed, from the source its lock records. */
+ readonly update: (
+ input: InstalledSkillInput,
+ ) => Effect.Effect;
+ /** Remove a skill the CLI installed, with every agent's link to it. */
+ readonly remove: (input: InstalledSkillInput) => Effect.Effect;
+ }
+>()("t3/skills/SkillLibrary") {}
+
+/** A lock entry, as both lock versions write it. */
+const LockEntry = Schema.Struct({
+ source: Schema.String,
+ sourceType: Schema.optional(Schema.String),
+ sourceUrl: Schema.optional(Schema.String),
+ ref: Schema.optional(Schema.String),
+ skillPath: Schema.optional(Schema.String),
+});
+type LockEntry = typeof LockEntry.Type;
+const decodeLock = Schema.decodeUnknownOption(
+ fromLenientJson(Schema.Struct({ skills: Schema.Record(Schema.String, LockEntry) })),
+);
+
+const SCRIPT_EXTENSION = /\.(?:sh|bash|zsh|fish|ps1|bat|cmd|py|rb|pl|js|mjs|cjs|ts|mts|php)$/i;
+/** Bounds on the walk of one skill folder, so a huge tree costs a fixed amount. */
+const MAX_FILES = 500;
+const MAX_DIRECTORIES = 200;
+/** Folders an installer or VCS leaves behind, never part of the skill. */
+const SKIPPED_DIRECTORIES = new Set([".git", "node_modules"]);
+
+/**
+ * The CLI's install source for one locked skill: the skill's own folder in
+ * the source, at the recorded ref, as `buildUpdateInstallSource` builds it.
+ */
+export function lockedInstallSource(entry: LockEntry): string {
+ const base = entry.sourceUrl ?? entry.source;
+ const ref = entry.ref === undefined ? "" : `#${entry.ref}`;
+ const folder = entry.skillPath?.replace(/\/?SKILL\.md$/i, "") ?? "";
+ // Only GitHub-style shorthands and GitHub or GitLab URLs take a subpath.
+ const takesSubpath =
+ folder !== "" &&
+ !entry.source.endsWith(".git") &&
+ !/^(?:git@|ssh:\/\/)/.test(entry.source) &&
+ (!/^https?:\/\//.test(entry.source) ||
+ /^https?:\/\/(?:github|gitlab)\.com\//.test(entry.source));
+ return takesSubpath ? `${entry.source}/${folder}${ref}` : `${base}${ref}`;
+}
+
+const make = Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const crypto = yield* Crypto.Crypto;
+ const cli = yield* SkillsCli.SkillsCli;
+ const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
+ const projectService = yield* ProjectService.ProjectService;
+ const environment = yield* HostProcessEnvironment;
+
+ const home = environment.HOME?.trim() || environment.USERPROFILE?.trim() || "";
+ const globalLockPath = environment.XDG_STATE_HOME?.trim()
+ ? path.join(environment.XDG_STATE_HOME.trim(), "skills", ".skill-lock.json")
+ : path.join(home, ".agents", ".skill-lock.json");
+
+ const readLock = (file: string) =>
+ fileSystem.readFileString(file).pipe(
+ Effect.map((text) =>
+ Option.match(decodeLock(text), {
+ onNone: () => new Map(),
+ onSome: (lock) => new Map(Object.entries(lock.skills)),
+ }),
+ ),
+ Effect.orElseSucceed(() => new Map()),
+ );
+
+ const realPath = (target: string) =>
+ fileSystem.realPath(target).pipe(Effect.orElseSucceed(() => target));
+
+ /** Where a target's installs live, and its lock file. */
+ const targetPaths = (target: SkillInstallTarget) => {
+ const root = target.kind === "environment" ? home : target.cwd;
+ return {
+ root,
+ folder: path.join(root, STANDARD_SKILL_FOLDER),
+ lock: target.kind === "environment" ? globalLockPath : path.join(root, "skills-lock.json"),
+ };
+ };
+
+ /** The project's root as the registry stores it, refusing an unregistered folder. */
+ const resolveTarget = Effect.fnUntraced(function* (target: SkillInstallTarget) {
+ if (target.kind === "environment") return target;
+ const project = yield* projectService.getByWorkspaceRoot(target.cwd).pipe(
+ Effect.map(Option.getOrUndefined),
+ Effect.orElseSucceed(() => undefined),
+ );
+ if (project === undefined) {
+ return yield* new SkillLibraryError({
+ reason: "projectNotRegistered",
+ message: "That folder isn't a project on this environment.",
+ });
+ }
+ return { kind: "project", cwd: project.workspaceRoot } satisfies SkillInstallTarget;
+ });
+
+ const enabledProviders = providerRegistry.getProviders.pipe(
+ Effect.map((providers) => providers.filter((provider) => provider.enabled)),
+ );
+
+ /** Ask the agents to rescan, so lists and the composer show the change. */
+ const refreshAgents = (target: SkillInstallTarget) =>
+ Effect.gen(function* () {
+ const providers = yield* enabledProviders;
+ yield* Effect.forEach(
+ providers,
+ (provider) =>
+ target.kind === "environment"
+ ? providerRegistry.refreshInstance(provider.instanceId)
+ : providerRegistry.refreshWorkspaceSnapshot({
+ instanceId: provider.instanceId,
+ cwd: target.cwd,
+ fresh: true,
+ }),
+ { concurrency: "unbounded", discard: true },
+ );
+ });
+
+ /** A skill folder's files, breadth first and bounded; links are listed, never followed. */
+ const listFiles = Effect.fnUntraced(function* (root: string) {
+ const files: SkillFileEntry[] = [];
+ const pending = [""];
+ let directories = 0;
+ let truncated = false;
+ while (pending.length > 0) {
+ const relative = pending.shift() ?? "";
+ directories += 1;
+ const names = yield* fileSystem
+ .readDirectory(path.join(root, relative))
+ .pipe(Effect.orElseSucceed((): string[] => []));
+ for (const name of names.toSorted()) {
+ const childPath = relative === "" ? name : `${relative}/${name}`;
+ const absolute = path.join(root, childPath);
+ const link = yield* fileSystem.readLink(absolute).pipe(
+ Effect.as(true),
+ Effect.orElseSucceed(() => false),
+ );
+ const info = link
+ ? undefined
+ : yield* fileSystem.stat(absolute).pipe(Effect.orElseSucceed(() => undefined));
+ if (info?.type === "Directory") {
+ if (SKIPPED_DIRECTORIES.has(name)) continue;
+ if (directories + pending.length >= MAX_DIRECTORIES) truncated = true;
+ else pending.push(childPath);
+ continue;
+ }
+ if (!link && info?.type !== "File") continue;
+ if (files.length >= MAX_FILES) return { files, truncated: true };
+ files.push({
+ path: childPath,
+ size: info === undefined ? 0 : Number(info.size),
+ executable: info !== undefined && (info.mode & 0o111) !== 0,
+ });
+ }
+ }
+ return { files, truncated };
+ });
+
+ const hasScripts = (files: ReadonlyArray) =>
+ files.some((file) => file.executable || SCRIPT_EXTENSION.test(file.path));
+
+ const sha256 = (text: string) =>
+ crypto.digest("SHA-256", new TextEncoder().encode(text)).pipe(
+ Effect.map(Hex.encode),
+ Effect.orElseSucceed(() => ""),
+ );
+
+ const inspect: SkillLibrary["Service"]["inspect"] = Effect.fn("SkillLibrary.inspect")(
+ function* (input) {
+ const providers = yield* enabledProviders;
+ const reported = new Set();
+ for (const provider of providers) {
+ const snapshot =
+ input.cwd === undefined
+ ? undefined
+ : provider.workspaceSnapshots?.find((candidate) => candidate.cwd === input.cwd);
+ for (const skill of snapshot?.skills ?? provider.skills) {
+ if (path.isAbsolute(skill.path) && path.basename(skill.path) === "SKILL.md") {
+ reported.add(skill.path);
+ }
+ }
+ }
+
+ const targets: ReadonlyArray = [
+ { kind: "environment" },
+ ...(input.cwd === undefined ? [] : [{ kind: "project" as const, cwd: input.cwd }]),
+ ];
+ const installs = yield* Effect.forEach(targets, (target) =>
+ Effect.gen(function* () {
+ const paths = targetPaths(target);
+ return {
+ target,
+ folder: yield* realPath(paths.folder),
+ lock: yield* readLock(paths.lock),
+ };
+ }),
+ );
+
+ const folders = yield* Effect.forEach(
+ [...reported],
+ (skillPath) =>
+ Effect.gen(function* () {
+ const contents = yield* fileSystem
+ .readFileString(skillPath)
+ .pipe(Effect.orElseSucceed(() => undefined));
+ if (contents === undefined) return undefined;
+ const folder = yield* realPath(path.dirname(skillPath));
+ const name = path.basename(folder);
+ const install = installs.find(
+ (candidate) => path.dirname(folder) === candidate.folder && candidate.lock.has(name),
+ );
+ const entry = install?.lock.get(name);
+ const { files } = yield* listFiles(folder);
+ return {
+ path: skillPath,
+ folder,
+ hash: yield* sha256(contents),
+ scripts: hasScripts(files),
+ ...(install === undefined || entry === undefined
+ ? {}
+ : { installed: { target: install.target, source: entry.source } }),
+ } satisfies SkillFolderInfo;
+ }),
+ { concurrency: 8 },
+ );
+ return { folders: folders.filter((folder) => folder !== undefined) };
+ },
+ );
+
+ const describeSkill = (contents: string) => {
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(contents);
+ try {
+ const parsed: unknown = match === null ? undefined : parseYamlDocument(match[1] ?? "");
+ const description =
+ typeof parsed === "object" && parsed !== null && "description" in parsed
+ ? parsed.description
+ : undefined;
+ return typeof description === "string" ? description.trim() : "";
+ } catch {
+ return "";
+ }
+ };
+
+ const cliFailed = (message: string) => new SkillLibraryError({ reason: "cliFailed", message });
+
+ const runAdd = (input: SkillsCli.SkillsCliAddInput) =>
+ cli.add(input).pipe(
+ Effect.catchTags({
+ SkillsCliError: (error) => Effect.fail(cliFailed(error.message)),
+ }),
+ );
+
+ const preview: SkillLibrary["Service"]["preview"] = Effect.fn("SkillLibrary.preview")(
+ function* (input) {
+ return yield* Effect.scoped(
+ Effect.gen(function* () {
+ const scratch = yield* fileSystem
+ .makeTempDirectoryScoped({ prefix: "t3-skills-preview-" })
+ .pipe(Effect.mapError(() => cliFailed("Couldn't make a folder to read the source.")));
+ const results = yield* runAdd({
+ source: input.source,
+ skills: ["*"],
+ agents: ["universal"],
+ global: false,
+ cwd: scratch,
+ });
+ const installed = results.filter((result) => result.status === "installed");
+ if (installed.length === 0) {
+ const failure = results.find((result) => result.error)?.error;
+ return yield* new SkillLibraryError({
+ reason: failure === undefined || failure === null ? "noSkills" : "cliFailed",
+ message: failure ?? "No skills were found in that source.",
+ });
+ }
+ const folder = path.join(scratch, STANDARD_SKILL_FOLDER);
+ const names = yield* fileSystem
+ .readDirectory(folder)
+ .pipe(Effect.orElseSucceed((): string[] => []));
+ const skills = yield* Effect.forEach(names.toSorted(), (name) =>
+ Effect.gen(function* () {
+ const root = path.join(folder, name);
+ const contents = yield* fileSystem
+ .readFileString(path.join(root, "SKILL.md"))
+ .pipe(Effect.orElseSucceed(() => ""));
+ const { files, truncated } = yield* listFiles(root);
+ return {
+ name,
+ description: describeSkill(contents),
+ files,
+ filesTruncated: truncated,
+ scripts: hasScripts(files),
+ };
+ }),
+ );
+ return { skills };
+ }),
+ );
+ },
+ );
+
+ const outcomes = (results: ReadonlyArray) => ({
+ outcomes: results.map((result) => ({
+ name: result.name ?? "",
+ status: result.status,
+ ...(result.error === undefined || result.error === null ? {} : { error: result.error }),
+ })),
+ });
+
+ const installInto = (target: SkillInstallTarget, source: string, skills: ReadonlyArray) =>
+ Effect.gen(function* () {
+ const drivers: ReadonlyArray = (yield* enabledProviders).map(
+ (provider: ServerProvider) => provider.driver,
+ );
+ const results = yield* runAdd({
+ source,
+ skills,
+ agents: skillsCliInstallAgents(drivers, target.kind === "environment" ? "home" : "project"),
+ global: target.kind === "environment",
+ cwd: targetPaths(target).root,
+ });
+ yield* refreshAgents(target);
+ return outcomes(results);
+ });
+
+ const install: SkillLibrary["Service"]["install"] = Effect.fn("SkillLibrary.install")(
+ function* (input) {
+ const target = yield* resolveTarget(input.target);
+ return yield* installInto(target, input.source, input.skills);
+ },
+ );
+
+ const lockedEntry = (target: SkillInstallTarget, name: string) =>
+ readLock(targetPaths(target).lock).pipe(
+ Effect.flatMap((lock) => {
+ const entry = lock.get(name);
+ return entry === undefined
+ ? Effect.fail(
+ new SkillLibraryError({
+ reason: "notInstalled",
+ message: "Only skills installed from a source can be updated or removed here.",
+ }),
+ )
+ : Effect.succeed(entry);
+ }),
+ );
+
+ const update: SkillLibrary["Service"]["update"] = Effect.fn("SkillLibrary.update")(
+ function* (input) {
+ const target = yield* resolveTarget(input.target);
+ const entry = yield* lockedEntry(target, input.name);
+ return yield* installInto(target, lockedInstallSource(entry), [input.name]);
+ },
+ );
+
+ const remove: SkillLibrary["Service"]["remove"] = Effect.fn("SkillLibrary.remove")(
+ function* (input) {
+ const target = yield* resolveTarget(input.target);
+ yield* lockedEntry(target, input.name);
+ yield* cli
+ .remove({
+ skills: [input.name],
+ global: target.kind === "environment",
+ cwd: targetPaths(target).root,
+ })
+ .pipe(
+ Effect.catchTags({
+ SkillsCliError: (error) => Effect.fail(cliFailed(error.message)),
+ }),
+ );
+ yield* refreshAgents(target);
+ },
+ );
+
+ return SkillLibrary.of({ inspect, preview, install, update, remove });
+});
+
+export const layer = Layer.effect(SkillLibrary, make).pipe(Layer.provide(SkillsCli.layer));
diff --git a/apps/server/src/skills/SkillsCli.ts b/apps/server/src/skills/SkillsCli.ts
new file mode 100644
index 0000000000000..44fecad739a17
--- /dev/null
+++ b/apps/server/src/skills/SkillsCli.ts
@@ -0,0 +1,139 @@
+/**
+ * SkillsCli - runs the bundled `skills` CLI (vercel-labs/skills) through the
+ * hidden `t3 skills-cli` subcommand, so installs write exactly what
+ * `npx skills` would: the same folders, links and lock files.
+ *
+ * Arguments are built here from typed input only. Telemetry is off, git never
+ * prompts, and stdin is closed, so the CLI can't wait on anyone.
+ *
+ * @module SkillsCli
+ */
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+import { fromLenientJson } from "@t3tools/shared/schemaJson";
+import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
+
+import * as ProcessRunner from "../processRunner.ts";
+
+export class SkillsCliError extends Schema.TaggedError()("SkillsCliError", {
+ command: Schema.Literals(["add", "remove", "list"]),
+ exitCode: Schema.optional(Schema.Number),
+ cause: Schema.optional(Schema.Defect()),
+}) {
+ override get message(): string {
+ return `The skills installer failed to ${this.command}.`;
+ }
+}
+
+/** One entry of `add --json`. */
+const AddResult = Schema.Struct({
+ name: Schema.optional(Schema.String),
+ status: Schema.Literals(["installed", "skipped", "failed"]),
+ path: Schema.optional(Schema.String),
+ reason: Schema.optional(Schema.NullOr(Schema.String)),
+ error: Schema.optional(Schema.NullOr(Schema.String)),
+});
+export type SkillsCliAddResult = typeof AddResult.Type;
+const decodeAddResults = Schema.decodeUnknownEffect(fromLenientJson(Schema.Array(AddResult)));
+
+export interface SkillsCliAddInput {
+ readonly source: string;
+ /** Skill names, or `*` for every skill in the source. */
+ readonly skills: ReadonlyArray;
+ /** `skills` CLI agent ids, such as `universal` and `claude-code`. */
+ readonly agents: ReadonlyArray;
+ /** Install into the home folders instead of `cwd`. */
+ readonly global: boolean;
+ /** The project root, or the temp folder a preview unpacks into. */
+ readonly cwd: string;
+}
+
+export interface SkillsCliRemoveInput {
+ readonly skills: ReadonlyArray;
+ readonly global: boolean;
+ readonly cwd: string;
+}
+
+export class SkillsCli extends Context.Service<
+ SkillsCli,
+ {
+ /**
+ * Install skills. Resolves with each skill's result, including failures the
+ * CLI reports for the whole source (a result with no name).
+ */
+ readonly add: (
+ input: SkillsCliAddInput,
+ ) => Effect.Effect, SkillsCliError>;
+ /** Remove skills: their folders, every agent's link to them, and their lock entries. */
+ readonly remove: (input: SkillsCliRemoveInput) => Effect.Effect;
+ }
+>()("t3/skills/SkillsCli") {}
+
+/** Fetching a large repository is slow; nothing here should take longer. */
+const TIMEOUT = "3 minutes";
+const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
+
+const make = Effect.gen(function* () {
+ const processRunner = yield* ProcessRunner.ProcessRunner;
+ const self = yield* resolveSelfInvocation();
+
+ const run = (command: "add" | "remove", args: ReadonlyArray, cwd: string) =>
+ processRunner
+ .run({
+ command: self.command,
+ args: [...selfInvocationArgs(self, ["skills-cli", command, ...args])],
+ cwd,
+ env: {
+ ELECTRON_RUN_AS_NODE: "1",
+ DISABLE_TELEMETRY: "1",
+ DO_NOT_TRACK: "1",
+ GIT_TERMINAL_PROMPT: "0",
+ },
+ // An empty stdin closes it, so a prompt the flags missed ends instead of waiting.
+ stdin: "",
+ timeout: TIMEOUT,
+ maxOutputBytes: MAX_OUTPUT_BYTES,
+ })
+ .pipe(Effect.mapError((cause) => new SkillsCliError({ command, cause })));
+
+ const add: SkillsCli["Service"]["add"] = Effect.fn("SkillsCli.add")(function* (input) {
+ const result = yield* run(
+ "add",
+ [
+ input.source,
+ "--skill",
+ ...input.skills,
+ "--agent",
+ ...input.agents,
+ ...(input.global ? ["--global"] : []),
+ "--yes",
+ "--json",
+ ],
+ input.cwd,
+ );
+ // A non-zero exit still prints the per-skill results when any were reached.
+ return yield* decodeAddResults(result.stdout).pipe(
+ Effect.mapError(
+ (cause) =>
+ new SkillsCliError({ command: "add", exitCode: result.code ?? undefined, cause }),
+ ),
+ );
+ });
+
+ const remove: SkillsCli["Service"]["remove"] = Effect.fn("SkillsCli.remove")(function* (input) {
+ const result = yield* run(
+ "remove",
+ [...input.skills, ...(input.global ? ["--global"] : []), "--yes"],
+ input.cwd,
+ );
+ if (result.code !== 0) {
+ return yield* new SkillsCliError({ command: "remove", exitCode: result.code ?? undefined });
+ }
+ });
+
+ return SkillsCli.of({ add, remove });
+});
+
+export const layer = Layer.effect(SkillsCli, make);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 5aa1681ea586b..5619ed6a8c099 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -190,6 +190,7 @@ import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/Atta
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
+import * as SkillLibrary from "./skills/SkillLibrary.ts";
import { readWorkflowScript } from "./orchestration-v2/workflowScriptQuery.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
@@ -1286,6 +1287,7 @@ const layerWsRpc = (
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
+ const skillLibrary = yield* SkillLibrary.SkillLibrary;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const rpcClientIds = yield* Ref.make(new Set());
@@ -2642,6 +2644,11 @@ const layerWsRpc = (
}),
),
),
+ [WS_METHODS.skillsInspect]: (input) => skillLibrary.inspect(input),
+ [WS_METHODS.skillsPreview]: (input) => skillLibrary.preview(input),
+ [WS_METHODS.skillsInstall]: (input) => skillLibrary.install(input),
+ [WS_METHODS.skillsUpdate]: (input) => skillLibrary.update(input),
+ [WS_METHODS.skillsRemove]: (input) => skillLibrary.remove(input).pipe(Effect.as({})),
[WS_METHODS.projectsReadFile]: (input) =>
workspaceFileSystem.readFile(input).pipe(
Effect.mapError(
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 9605829e47d7c..90fb22d6b1e20 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";
import { GitPreparePullRequestThreadInput } from "./git.ts";
import {
AuthOrchestrationOperateScope,
+ AuthProvidersManageScope,
AuthSourceControlWriteScope,
type AuthEnvironmentScope,
} from "./auth.ts";
@@ -34,6 +35,12 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope,
[WS_METHODS.vcsInit]: AuthSourceControlWriteScope,
+ // Skills from a source may carry scripts every agent on the environment can
+ // run, the same reach as adding an MCP server.
+ [WS_METHODS.skillsInstall]: AuthProvidersManageScope,
+ [WS_METHODS.skillsUpdate]: AuthProvidersManageScope,
+ [WS_METHODS.skillsRemove]: AuthProvidersManageScope,
+
[WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope,
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index 4cf7eb6d93187..cdfd8cf68b7f3 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -29,6 +29,7 @@ export * from "./keybindings.ts";
export * from "./server.ts";
export * from "./settings.ts";
export * from "./agentTools.ts";
+export * from "./skills.ts";
export * from "./git.ts";
export * from "./vcs.ts";
export * from "./sourceControl.ts";
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index ed14e2e16b7c7..6002cebbdcafe 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -148,6 +148,16 @@ import {
ReviewDiffPreviewResult,
} from "./review.ts";
import { KeybindingsConfigError } from "./keybindings.ts";
+import {
+ InstalledSkillInput,
+ SkillInspectInput,
+ SkillInspectResult,
+ SkillInstallInput,
+ SkillInstallResult,
+ SkillLibraryError,
+ SkillPreviewInput,
+ SkillPreviewResult,
+} from "./skills.ts";
import {
OrchestrationSearchThreadsError,
OrchestrationSearchThreadsInput,
@@ -462,6 +472,11 @@ export const WS_METHODS = {
serverProbe: "server.probe",
serverGetConfig: "server.getConfig",
serverRefreshProviders: "server.refreshProviders",
+ skillsInspect: "skills.inspect",
+ skillsPreview: "skills.preview",
+ skillsInstall: "skills.install",
+ skillsUpdate: "skills.update",
+ skillsRemove: "skills.remove",
serverUpdateProvider: "server.updateProvider",
serverUpdateServer: "server.updateServer",
serverUpdateServerWithProgress: "server.updateServerWithProgress",
@@ -585,6 +600,36 @@ const WsServerProbeRpc = Rpc.make(WS_METHODS.serverProbe, {
error: EnvironmentAuthorizationError,
});
+const WsSkillsInspectRpc = Rpc.make(WS_METHODS.skillsInspect, {
+ payload: SkillInspectInput,
+ success: SkillInspectResult,
+ error: EnvironmentAuthorizationError,
+});
+
+const WsSkillsPreviewRpc = Rpc.make(WS_METHODS.skillsPreview, {
+ payload: SkillPreviewInput,
+ success: SkillPreviewResult,
+ error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
+});
+
+const WsSkillsInstallRpc = Rpc.make(WS_METHODS.skillsInstall, {
+ payload: SkillInstallInput,
+ success: SkillInstallResult,
+ error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
+});
+
+const WsSkillsUpdateRpc = Rpc.make(WS_METHODS.skillsUpdate, {
+ payload: InstalledSkillInput,
+ success: SkillInstallResult,
+ error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
+});
+
+const WsSkillsRemoveRpc = Rpc.make(WS_METHODS.skillsRemove, {
+ payload: InstalledSkillInput,
+ success: Schema.Struct({}),
+ error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
+});
+
const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {
payload: Schema.Struct({}),
success: ServerConfig,
@@ -1812,6 +1857,11 @@ export const WsRpcGroup = RpcGroup.make(
WsServerProbeRpc,
WsServerGetConfigRpc,
WsServerRefreshProvidersRpc,
+ WsSkillsInspectRpc,
+ WsSkillsPreviewRpc,
+ WsSkillsInstallRpc,
+ WsSkillsUpdateRpc,
+ WsSkillsRemoveRpc,
WsServerUpdateProviderRpc,
WsProviderConsumeResetCreditRpc,
WsProviderAuthStartRpc,
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
new file mode 100644
index 0000000000000..f83e7bb69a386
--- /dev/null
+++ b/packages/contracts/src/skills.ts
@@ -0,0 +1,133 @@
+import * as Schema from "effect/Schema";
+
+import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
+
+/**
+ * Installing skills from a source, as `npx skills` does: the server runs the
+ * `skills` CLI (vercel-labs/skills), so skills land in the same folders and
+ * lock files a terminal install would write. Turning skills on or off stays in
+ * `ServerSettings.disabledSkills`; this only adds and removes skill folders.
+ */
+
+/** Where an install goes: the environment's home folders, or a registered project. */
+export const SkillInstallTarget = Schema.Union([
+ Schema.Struct({ kind: Schema.Literal("environment") }),
+ Schema.Struct({ kind: Schema.Literal("project"), cwd: TrimmedNonEmptyString }),
+]);
+export type SkillInstallTarget = typeof SkillInstallTarget.Type;
+
+/**
+ * What a user pastes: `owner/repo`, a git or GitHub tree URL, or an absolute
+ * path on the environment. Never an option, which the CLI would parse as one.
+ */
+export const SkillSource = TrimmedNonEmptyString.check(
+ Schema.isMaxLength(2048),
+ Schema.makeFilter((source: string) =>
+ source.startsWith("-") ? "A source can't start with a dash." : true,
+ ),
+);
+
+/** A skill's folder name, the name agents invoke it by, as the CLI sanitizes it. */
+export const InstalledSkillName = TrimmedNonEmptyString.check(
+ Schema.isMaxLength(255),
+ Schema.isPattern(/^[a-z0-9._][a-z0-9._-]*$/),
+);
+export type InstalledSkillName = typeof InstalledSkillName.Type;
+
+export const SkillFileEntry = Schema.Struct({
+ /** Relative to the skill's folder, with `/` separators. */
+ path: Schema.String,
+ size: NonNegativeInt,
+ executable: Schema.Boolean,
+});
+export type SkillFileEntry = typeof SkillFileEntry.Type;
+
+export const SkillPreviewInput = Schema.Struct({ source: SkillSource });
+export type SkillPreviewInput = typeof SkillPreviewInput.Type;
+
+export const SkillPreviewItem = Schema.Struct({
+ name: InstalledSkillName,
+ description: Schema.String,
+ /** Up to a limit; `filesTruncated` says when some were left out. */
+ files: Schema.Array(SkillFileEntry),
+ filesTruncated: Schema.Boolean,
+ /** Some file is executable or a script, which an agent may run. */
+ scripts: Schema.Boolean,
+});
+export type SkillPreviewItem = typeof SkillPreviewItem.Type;
+
+export const SkillPreviewResult = Schema.Struct({ skills: Schema.Array(SkillPreviewItem) });
+export type SkillPreviewResult = typeof SkillPreviewResult.Type;
+
+export const SkillInstallInput = Schema.Struct({
+ source: SkillSource,
+ skills: Schema.Array(InstalledSkillName).check(Schema.isMinLength(1), Schema.isMaxLength(200)),
+ target: SkillInstallTarget,
+});
+export type SkillInstallInput = typeof SkillInstallInput.Type;
+
+/** One skill an `installed` lock entry names, to update or remove. */
+export const InstalledSkillInput = Schema.Struct({
+ name: InstalledSkillName,
+ target: SkillInstallTarget,
+});
+export type InstalledSkillInput = typeof InstalledSkillInput.Type;
+
+export const SkillInstallOutcome = Schema.Struct({
+ name: Schema.String,
+ status: Schema.Literals(["installed", "skipped", "failed"]),
+ error: Schema.optional(Schema.String),
+});
+export type SkillInstallOutcome = typeof SkillInstallOutcome.Type;
+
+export const SkillInstallResult = Schema.Struct({ outcomes: Schema.Array(SkillInstallOutcome) });
+export type SkillInstallResult = typeof SkillInstallResult.Type;
+
+export const SkillInspectInput = Schema.Struct({
+ /** A project checkout whose skills are inspected besides the environment's. */
+ cwd: Schema.optional(TrimmedNonEmptyString),
+});
+export type SkillInspectInput = typeof SkillInspectInput.Type;
+
+/**
+ * One SKILL.md an enabled agent reported, keyed by that path. The server
+ * finds the paths itself, so a client can't point it at other files.
+ */
+export const SkillFolderInfo = Schema.Struct({
+ /** The SKILL.md path the agent reported. */
+ path: Schema.String,
+ /** The skill's folder after following links, for viewing its files. */
+ folder: Schema.String,
+ /** SHA-256 of SKILL.md, so two copies of a name can be compared. */
+ hash: Schema.String,
+ scripts: Schema.Boolean,
+ /** Set when the `skills` CLI installed this folder: its lock names the source. */
+ installed: Schema.optional(
+ Schema.Struct({
+ target: SkillInstallTarget,
+ /** `owner/repo`, a URL or a path, as the lock records it. */
+ source: Schema.String,
+ }),
+ ),
+});
+export type SkillFolderInfo = typeof SkillFolderInfo.Type;
+
+export const SkillInspectResult = Schema.Struct({ folders: Schema.Array(SkillFolderInfo) });
+export type SkillInspectResult = typeof SkillInspectResult.Type;
+
+export class SkillLibraryError extends Schema.TaggedError()(
+ "SkillLibraryError",
+ {
+ reason: Schema.Literals([
+ /** The CLI failed; `message` carries what it printed. */
+ "cliFailed",
+ /** The source has no skills the CLI could find. */
+ "noSkills",
+ /** The project isn't one of this environment's projects. */
+ "projectNotRegistered",
+ /** Only skills the CLI installed (with a lock entry) can be updated or removed. */
+ "notInstalled",
+ ]),
+ message: Schema.String,
+ },
+) {}
diff --git a/packages/provider-core/package.json b/packages/provider-core/package.json
index fdf4c7fd52887..264d8a90f1d93 100644
--- a/packages/provider-core/package.json
+++ b/packages/provider-core/package.json
@@ -7,6 +7,10 @@
"types": "./src/client.ts",
"import": "./src/client.ts"
},
+ "./server/AgentSkillFolders": {
+ "types": "./src/server/AgentSkillFolders.ts",
+ "import": "./src/server/AgentSkillFolders.ts"
+ },
"./server/adapterDriver": {
"types": "./src/server/adapterDriver.ts",
"import": "./src/server/adapterDriver.ts"
diff --git a/packages/provider-core/src/server/AgentSkillFolders.ts b/packages/provider-core/src/server/AgentSkillFolders.ts
new file mode 100644
index 0000000000000..4921305ad1962
--- /dev/null
+++ b/packages/provider-core/src/server/AgentSkillFolders.ts
@@ -0,0 +1,93 @@
+/**
+ * AgentSkillFolders - where each agent reads skills from, and which `skills`
+ * CLI agent id installs into them.
+ *
+ * Paths are relative to the home folder (`home`) or the project root
+ * (`project`), in the order the agent looks. `.agents/skills` is the folder the
+ * `skills` CLI writes every install to; agents that read only their own folder
+ * get a link there, made by naming their CLI id. Sources for each agent:
+ * - Claude: `ClaudeSkills.ts` (`~/.claude/skills`, `.claude/skills`; it does
+ * not read `.agents/skills`).
+ * - Codex: https://developers.openai.com/codex/skills (`.agents/skills` at both
+ * levels; `~/.codex/skills` is the deprecated user folder).
+ * - Cursor: provider-cursor's `skills.ts`.
+ * - OpenCode: https://opencode.ai/docs/skills/ (its own folders plus the
+ * `.claude` and `.agents` ones).
+ * - Grok: https://docs.x.ai/build/features/skills-plugins-marketplaces.md.
+ * - Antigravity: `AntigravitySkills.ts` (`.agents/skills` only in a project).
+ * - Pi: its docs/skills.md (`.pi/skills`, `~/.pi/agent/skills`, `.agents`).
+ * The CLI ids and folders follow vercel-labs/skills' `src/agents.ts`.
+ *
+ * @module AgentSkillFolders
+ */
+import type { ProviderDriverKind } from "@t3tools/contracts";
+
+/** The folder the `skills` CLI installs into, at home and in a project. */
+export const STANDARD_SKILL_FOLDER = ".agents/skills";
+
+export interface AgentSkillFolders {
+ /** Folders under the home folder, in the order the agent looks. */
+ readonly home: ReadonlyArray;
+ /** Folders under a project root, in the order the agent looks. */
+ readonly project: ReadonlyArray;
+ /**
+ * The `skills` CLI agent that links an install into a folder this agent
+ * reads, when `.agents/skills` alone doesn't reach it at that level.
+ */
+ readonly installAgent?: { readonly home?: string; readonly project?: string };
+}
+
+const AGENT_SKILL_FOLDERS: Readonly> = {
+ claudeAgent: {
+ home: [".claude/skills"],
+ project: [".claude/skills"],
+ installAgent: { home: "claude-code", project: "claude-code" },
+ },
+ codex: {
+ home: [STANDARD_SKILL_FOLDER, ".codex/skills"],
+ project: [STANDARD_SKILL_FOLDER, ".codex/skills"],
+ },
+ cursor: {
+ home: [".cursor/skills", STANDARD_SKILL_FOLDER, ".codex/skills", ".claude/skills"],
+ project: [".cursor/skills", STANDARD_SKILL_FOLDER, ".codex/skills", ".claude/skills"],
+ },
+ opencode: {
+ home: [".config/opencode/skills", ".claude/skills", STANDARD_SKILL_FOLDER],
+ project: [".opencode/skills", ".claude/skills", STANDARD_SKILL_FOLDER],
+ },
+ grok: {
+ home: [".grok/skills", STANDARD_SKILL_FOLDER],
+ project: [".grok/skills"],
+ installAgent: { project: "grok" },
+ },
+ antigravity: {
+ home: [".gemini/config/skills", ".gemini/antigravity-cli/skills"],
+ project: [".gemini/skills", STANDARD_SKILL_FOLDER, ".agent/skills"],
+ installAgent: { home: "antigravity-cli" },
+ },
+ pi: {
+ home: [".pi/agent/skills", STANDARD_SKILL_FOLDER],
+ project: [".pi/skills", STANDARD_SKILL_FOLDER],
+ },
+};
+
+/** The folders a driver reads, or undefined for a driver this table doesn't know. */
+export const agentSkillFolders = (driver: ProviderDriverKind): AgentSkillFolders | undefined =>
+ AGENT_SKILL_FOLDERS[driver];
+
+/**
+ * The `skills` CLI agents an install names so every listed driver can use the
+ * skill: `universal` writes `.agents/skills`, and each driver that doesn't read
+ * it at that level adds the agent that links into its own folder.
+ */
+export function skillsCliInstallAgents(
+ drivers: ReadonlyArray,
+ level: "home" | "project",
+): ReadonlyArray {
+ const agents = new Set(["universal"]);
+ for (const driver of drivers) {
+ const agent = agentSkillFolders(driver)?.installAgent?.[level];
+ if (agent !== undefined) agents.add(agent);
+ }
+ return [...agents];
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 711ef69a8bbd8..13ae026c4e7d9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -645,6 +645,9 @@ importers:
proper-lockfile:
specifier: 4.1.2
version: 4.1.2
+ skills:
+ specifier: 1.7.1
+ version: 1.7.1
stream-chain:
specifier: ^4.2.5
version: 4.2.5
@@ -10940,6 +10943,11 @@ packages:
sisteransi@1.0.5:
resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
+ skills@1.7.1:
+ resolution: {integrity: sha512-LUHR/+3D3evhwejiMfBStH7ndqJkV9UlwkjH1LpQ8j1g1cJO1yrXs+R+xS0AuV6E7iX0uZt44xEMAPZC+o40nA==}
+ engines: {node: '>=22.20.0'}
+ hasBin: true
+
slugify@1.6.9:
resolution: {integrity: sha512-vZ7rfeehZui7wQs438JXBckYLkIIdfHOXsaVEUMyS5fHo1483l1bMdo0EDSWYclY0yZKFOipDy4KHuKs6ssvdg==}
engines: {node: '>=8.0.0'}
@@ -22299,6 +22307,11 @@ snapshots:
sisteransi@1.0.5: {}
+ skills@1.7.1:
+ dependencies:
+ tar: 7.5.22
+ yaml: 2.9.0
+
slugify@1.6.9: {}
smart-buffer@4.2.0:
From 458f63083bad930a94eb736d1a377d04fa097e12 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 19:07:27 -0700
Subject: [PATCH 11/35] feat: add skills from a source, view their files, and
let agents change Tools
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Settings → Tools → Skills gets Add skills (preview a source's skills, then
install them at the current scope), groups installed skills under the
source they came from with one switch, marks conflicting copies of a name,
and adds View files, Update and Remove to each skill's menu. Agents get
t3_tools_read, t3_tools_update, t3_skills_install and t3_skills_remove.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/mcp/McpHttpServer.ts | 5 +
.../src/mcp/toolkits/tools/handlers.test.ts | 123 +++++++
.../server/src/mcp/toolkits/tools/handlers.ts | 164 +++++++++
apps/server/src/mcp/toolkits/tools/tools.ts | 101 ++++++
apps/server/src/skills/SkillLibrary.test.ts | 9 +-
apps/server/src/skills/SkillLibrary.ts | 6 +-
.../components/settings/AddSkillsDialog.tsx | 219 +++++++++++
.../components/settings/SkillFilesDialog.tsx | 95 +++++
.../src/components/settings/ToolsSettings.tsx | 342 ++++++++++++++----
.../src/components/settings/settingsSearch.ts | 2 +-
.../settings/toolsSettings.logic.test.ts | 79 ++++
.../settings/toolsSettings.logic.ts | 78 +++-
docs/user/tools.md | 20 +
packages/client-runtime/src/state/server.ts | 27 ++
packages/client-runtime/src/t3ToolSummary.ts | 12 +
packages/contracts/src/skills.ts | 3 +
.../src/server/AgentSkillFolders.ts | 2 +-
packages/shared/package.json | 4 +
packages/shared/src/agentTools.ts | 112 ++++++
packages/shared/src/t3McpToolPresentation.ts | 11 +
20 files changed, 1318 insertions(+), 96 deletions(-)
create mode 100644 apps/server/src/mcp/toolkits/tools/handlers.test.ts
create mode 100644 apps/server/src/mcp/toolkits/tools/handlers.ts
create mode 100644 apps/server/src/mcp/toolkits/tools/tools.ts
create mode 100644 apps/web/src/components/settings/AddSkillsDialog.tsx
create mode 100644 apps/web/src/components/settings/SkillFilesDialog.tsx
create mode 100644 packages/shared/src/agentTools.ts
diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts
index f4da6e051a7c3..d22a48d0e6b6e 100644
--- a/apps/server/src/mcp/McpHttpServer.ts
+++ b/apps/server/src/mcp/McpHttpServer.ts
@@ -26,7 +26,9 @@ import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts";
import { EnvironmentToolkit } from "./toolkits/environment/tools.ts";
+import { ToolsToolkit } from "./toolkits/tools/tools.ts";
import * as EnvironmentHandlers from "./toolkits/environment/handlers.ts";
+import * as ToolsHandlers from "./toolkits/tools/handlers.ts";
import { ProjectToolkit } from "./toolkits/project/tools.ts";
import * as ProjectHandlers from "./toolkits/project/handlers.ts";
import { AttachmentToolkit } from "./toolkits/attachment/tools.ts";
@@ -818,6 +820,8 @@ const layerEnvironmentRegistration = toolkitRegistration(
const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
+const layerToolsRegistration = toolkitRegistration(ToolsToolkit, ToolsHandlers.layer);
+
export const layerAttachmentToolkit = toolkitRegistration(
AttachmentToolkit,
AttachmentHandlers.layer,
@@ -857,6 +861,7 @@ export const layer = Layer.mergeAll(
layerAttachmentToolkit,
layerProjectRegistration,
layerEnvironmentRegistration,
+ layerToolsRegistration,
layerPreviewControlsRegistration,
layerWorktreeToolkitRegistration,
layerPullRequestsToolkit,
diff --git a/apps/server/src/mcp/toolkits/tools/handlers.test.ts b/apps/server/src/mcp/toolkits/tools/handlers.test.ts
new file mode 100644
index 0000000000000..fd99c4faed9ee
--- /dev/null
+++ b/apps/server/src/mcp/toolkits/tools/handlers.test.ts
@@ -0,0 +1,123 @@
+import { expect, it } from "@effect/vitest";
+import {
+ DEFAULT_SERVER_SETTINGS,
+ EnvironmentId,
+ ProjectId,
+ ProviderInstanceId,
+ type ServerSettings,
+ type ServerSettingsPatch,
+ ThreadId,
+} from "@t3tools/contracts";
+import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Ref from "effect/Ref";
+import * as Stream from "effect/Stream";
+
+import * as Environment from "../../../environment/ServerEnvironment.ts";
+import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
+import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
+import * as ProjectService from "../../../project/ProjectService.ts";
+import * as Settings from "../../../serverSettings.ts";
+import * as SkillLibrary from "../../../skills/SkillLibrary.ts";
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
+import * as McpToolAccess from "../../McpToolAccess.ts";
+import { liveThreadShell } from "../../McpToolAccess.testkit.ts";
+import * as ToolsHandlers from "./handlers.ts";
+import { ToolsToolkit } from "./tools.ts";
+
+const environmentId = EnvironmentId.make("environment:tools");
+const threadId = ThreadId.make("thread:tools");
+const projectId = ProjectId.make("project:tools");
+
+const initial: ServerSettings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ disabledSkills: ["grill-me"],
+ mcpServers: {
+ context7: {
+ enabled: true,
+ transport: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp"],
+ env: [{ name: "CONTEXT7_API_KEY", value: "secret", sensitive: true }],
+ },
+ },
+ },
+};
+
+it.effect("switches skills and servers for a project as one patch, and never returns secrets", () =>
+ Effect.gen(function* () {
+ const settings = yield* Ref.make(initial);
+ const patches = yield* Ref.make>([]);
+ const layerDependencies = Layer.mergeAll(
+ ThreadCommandExecutor.layer,
+ Layer.succeed(McpInvocationContext.McpInvocationContext, {
+ environmentId,
+ requestNamespace: "provider:tools",
+ thread: {
+ threadId,
+ providerSessionId: "provider:tools",
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ },
+ client: undefined,
+ capabilities: new Set(["orchestration" as const]),
+ issuedAt: 0,
+ }),
+ Layer.mock(ThreadManagement.ThreadManagementService)({
+ getThreadShell: () => Effect.succeed(liveThreadShell(threadId)),
+ }),
+ Layer.mock(Environment.ServerEnvironment)({
+ getDescriptor: Effect.succeed({
+ environmentId,
+ label: "Test",
+ platform: { os: "linux", arch: "x64" },
+ serverVersion: "0.0.0",
+ capabilities: { repositoryIdentity: false },
+ }),
+ }),
+ Layer.mock(Settings.ServerSettingsService)({
+ getSettings: Ref.get(settings),
+ updateSettings: (patch) =>
+ Ref.update(patches, (list) => [...list, patch]).pipe(
+ Effect.andThen(
+ Ref.updateAndGet(settings, (current) => applyServerSettingsPatch(current, patch)),
+ ),
+ ),
+ }),
+ Layer.mock(ProjectService.ProjectService)({}),
+ Layer.mock(SkillLibrary.SkillLibrary)({}),
+ );
+ yield* Effect.gen(function* () {
+ const toolkit = yield* ToolsToolkit;
+ const result = yield* toolkit
+ .handle("t3_tools_update", {
+ projectId,
+ skills: [
+ { name: "grill-me", enabled: true },
+ { name: "tdd", enabled: false },
+ ],
+ mcpServers: [{ name: "context7", enabled: false }],
+ })
+ .pipe(Stream.unwrap, Stream.runCollect);
+ expect(result.at(-1)?.result).toEqual({
+ disabledSkills: ["tdd"],
+ mcpServers: [{ name: "context7", enabled: false, summary: "npx -y @upstash/context7-mcp" }],
+ });
+ // One write, so the project never sits half-changed.
+ expect(yield* Ref.get(patches)).toHaveLength(1);
+ expect((yield* Ref.get(settings)).projectSettingsOverrides[projectId]).toEqual({
+ disabledSkills: { "grill-me": false, tdd: true },
+ mcpServers: { context7: { enabled: false } },
+ });
+ // The environment itself is unchanged.
+ expect((yield* Ref.get(settings)).disabledSkills).toEqual(["grill-me"]);
+ }).pipe(
+ Effect.provide(
+ McpToolAccess.HandlersLayer.layer(ToolsHandlers.layer).pipe(
+ Layer.provideMerge(layerDependencies),
+ ),
+ ),
+ );
+ }),
+);
diff --git a/apps/server/src/mcp/toolkits/tools/handlers.ts b/apps/server/src/mcp/toolkits/tools/handlers.ts
new file mode 100644
index 0000000000000..c8e0909a2ba38
--- /dev/null
+++ b/apps/server/src/mcp/toolkits/tools/handlers.ts
@@ -0,0 +1,164 @@
+import {
+ mcpServerTransportSummary,
+ OrchestratorMcpFailure,
+ type ProjectId,
+ type ServerSettings,
+ type ServerSettingsPatch,
+ type SkillInstallTarget,
+} from "@t3tools/contracts";
+import { mcpServerEnabledPatch, skillsDisabledPatch } from "@t3tools/shared/agentTools";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
+import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+
+import * as Environment from "../../../environment/ServerEnvironment.ts";
+import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
+import * as ProjectService from "../../../project/ProjectService.ts";
+import * as Settings from "../../../serverSettings.ts";
+import * as SkillLibrary from "../../../skills/SkillLibrary.ts";
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
+import * as McpToolAccess from "../../McpToolAccess.ts";
+import { readCaller, unavailable } from "../../threadAccess.ts";
+import { ToolsToolkit } from "./tools.ts";
+
+/** What agents and the Tools page see for one scope; secrets never leave the server. */
+function toolsState(settings: ServerSettings, projectId: ProjectId | undefined) {
+ const resolved = resolveProjectSettings(settings, projectId ?? null).settings;
+ return {
+ disabledSkills: [...resolved.disabledSkills],
+ mcpServers: Object.entries(resolved.mcpServers).map(([name, server]) => ({
+ name,
+ enabled: server.enabled,
+ summary: mcpServerTransportSummary(server.transport),
+ })),
+ };
+}
+
+const access = Effect.gen(function* () {
+ const context = yield* readCaller();
+ const environment = yield* Environment.ServerEnvironment;
+ const descriptor = yield* environment.getDescriptor;
+ if (descriptor.environmentId !== context.scope.environmentId)
+ return yield* new OrchestratorMcpFailure({
+ code: "capability_denied",
+ message: "This credential belongs to another environment.",
+ });
+ return { settings: yield* Settings.ServerSettingsService };
+});
+
+/** The project's checkout, as the target of an install. */
+const projectTarget = (projectId: ProjectId | undefined) =>
+ Effect.gen(function* () {
+ if (projectId === undefined) return { kind: "environment" } satisfies SkillInstallTarget;
+ const projects = yield* ProjectService.ProjectService;
+ const project = yield* projects.getById(projectId).pipe(Effect.mapError(unavailable));
+ if (Option.isNone(project))
+ return yield* new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message: "The project was not found.",
+ });
+ return { kind: "project", cwd: project.value.workspaceRoot } satisfies SkillInstallTarget;
+ });
+
+const libraryFailure = (error: { readonly message: string }) =>
+ new OrchestratorMcpFailure({ code: "invalid_request", message: error.message });
+
+/** Run a change while the calling thread holds its lock, re-checking it first. */
+const asCaller = (
+ check: Effect.Effect,
+ change: Effect.Effect,
+) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
+ const guarded = check.pipe(Effect.andThen(change));
+ return yield* scope.thread === undefined
+ ? guarded
+ : executor.withLock(scope.thread.threadId, guarded);
+ });
+
+export const layer = McpToolAccess.toLayer(ToolsToolkit, {
+ t3_tools_read: McpToolAccess.reads((input) =>
+ Effect.gen(function* () {
+ const { settings } = yield* access;
+ const current = yield* settings.getSettings.pipe(Effect.mapError(unavailable));
+ return toolsState(current, input.projectId);
+ }),
+ ),
+ t3_tools_update: McpToolAccess.writesEnvironment((input, check) =>
+ asCaller(
+ check,
+ Effect.gen(function* () {
+ const { settings } = yield* access;
+ const projectId = input.projectId ?? null;
+ // Each change builds on the last; the patch is then read off the result,
+ // so everything lands in one write.
+ let next = yield* settings.getSettings.pipe(Effect.mapError(unavailable));
+ for (const enabled of [true, false]) {
+ const names = (input.skills ?? [])
+ .filter((skill) => skill.enabled === enabled)
+ .map((skill) => skill.name);
+ if (names.length > 0) {
+ next = applyServerSettingsPatch(
+ next,
+ skillsDisabledPatch(next, projectId, names, !enabled),
+ );
+ }
+ }
+ for (const server of input.mcpServers ?? []) {
+ const step = mcpServerEnabledPatch(next, projectId, server.name, server.enabled);
+ if (step === null)
+ return yield* new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message: `There is no Settings → Tools server named ${server.name}.`,
+ });
+ next = applyServerSettingsPatch(next, step);
+ }
+ const servers = (input.mcpServers ?? []).map((server) => server.name);
+ const patch: ServerSettingsPatch =
+ projectId === null
+ ? {
+ ...(input.skills === undefined ? {} : { disabledSkills: next.disabledSkills }),
+ ...(servers.length === 0
+ ? {}
+ : {
+ mcpServers: Object.fromEntries(
+ servers.map((name) => [name, next.mcpServers[name] ?? null]),
+ ),
+ }),
+ }
+ : ({
+ projectSettingsOverrides: {
+ [projectId]: next.projectSettingsOverrides[projectId] ?? null,
+ },
+ } as ServerSettingsPatch);
+ const saved = yield* settings.updateSettings(patch).pipe(Effect.mapError(unavailable));
+ return toolsState(saved, input.projectId);
+ }),
+ ),
+ ),
+ t3_skills_install: McpToolAccess.writesEnvironment((input, check) =>
+ asCaller(
+ check,
+ Effect.gen(function* () {
+ const library = yield* SkillLibrary.SkillLibrary;
+ const target = yield* projectTarget(input.projectId);
+ return yield* library
+ .install({ source: input.source, skills: input.skills, target })
+ .pipe(Effect.mapError(libraryFailure));
+ }),
+ ),
+ ),
+ t3_skills_remove: McpToolAccess.writesEnvironment((input, check) =>
+ asCaller(
+ check,
+ Effect.gen(function* () {
+ const library = yield* SkillLibrary.SkillLibrary;
+ const target = yield* projectTarget(input.projectId);
+ yield* library.remove({ name: input.name, target }).pipe(Effect.mapError(libraryFailure));
+ return {};
+ }),
+ ),
+ ),
+});
diff --git a/apps/server/src/mcp/toolkits/tools/tools.ts b/apps/server/src/mcp/toolkits/tools/tools.ts
new file mode 100644
index 0000000000000..c39c26540a1c6
--- /dev/null
+++ b/apps/server/src/mcp/toolkits/tools/tools.ts
@@ -0,0 +1,101 @@
+import {
+ InstalledSkillName,
+ McpServerName,
+ OrchestratorMcpFailure,
+ ProjectId,
+ SkillInstallResult,
+ SkillSource,
+ TrimmedNonEmptyString,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { Tool, Toolkit } from "effect/ai";
+
+import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts";
+import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
+import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
+import * as ProjectService from "../../../project/ProjectService.ts";
+import * as Settings from "../../../serverSettings.ts";
+import * as SkillLibrary from "../../../skills/SkillLibrary.ts";
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
+
+const shared = {
+ failure: OrchestratorMcpFailure,
+ failureMode: "return" as const,
+ dependencies: [
+ McpInvocationContext.McpInvocationContext,
+ ThreadManagementService.ThreadManagementService,
+ ServerEnvironment.ServerEnvironment,
+ Settings.ServerSettingsService,
+ ThreadCommandExecutor.ThreadCommandExecutor,
+ ProjectService.ProjectService,
+ SkillLibrary.SkillLibrary,
+ ],
+};
+
+/** Omit for the environment; a project id scopes the read or change to that project. */
+const Scope = { projectId: Schema.optional(ProjectId) };
+
+const ToolsState = Schema.Struct({
+ disabledSkills: Schema.Array(Schema.String),
+ mcpServers: Schema.Array(
+ Schema.Struct({
+ name: Schema.String,
+ enabled: Schema.Boolean,
+ /** The command line or URL; secret values are never returned. */
+ summary: Schema.String,
+ }),
+ ),
+});
+
+const ToolsReadTool = Tool.make("t3_tools_read", {
+ ...shared,
+ description:
+ "Read Settings → Tools for this environment or one project: the skills switched off and the MCP servers T3 gives every agent session. Changes apply to new agent sessions.",
+ parameters: Schema.Struct(Scope),
+ success: ToolsState,
+})
+ .annotate(Tool.Readonly, true)
+ .annotate(Tool.Destructive, false);
+
+const ToolsUpdateTool = Tool.make("t3_tools_update", {
+ ...shared,
+ description:
+ "Turn skills or Settings → Tools MCP servers on or off for this environment or one project. Skills are named as agents invoke them. Requires a live full-access/default calling thread. Applies to new agent sessions.",
+ parameters: Schema.Struct({
+ ...Scope,
+ skills: Schema.optional(
+ Schema.Array(Schema.Struct({ name: TrimmedNonEmptyString, enabled: Schema.Boolean })),
+ ),
+ mcpServers: Schema.optional(
+ Schema.Array(Schema.Struct({ name: McpServerName, enabled: Schema.Boolean })),
+ ),
+ }),
+ success: ToolsState,
+}).annotate(Tool.Destructive, true);
+
+const SkillsInstallTool = Tool.make("t3_skills_install", {
+ ...shared,
+ description:
+ "Install skills from a source (GitHub owner/repo, git URL, or a folder on this environment) for every agent, the way `npx skills add` does. With projectId they go into that project's .agents/skills; without, into the environment's ~/.agents/skills. Skills may include scripts agents can run: install only sources the user asked for. Requires a live full-access/default calling thread.",
+ parameters: Schema.Struct({
+ ...Scope,
+ source: SkillSource,
+ skills: Schema.Array(InstalledSkillName).check(Schema.isMinLength(1)),
+ }),
+ success: SkillInstallResult,
+}).annotate(Tool.Destructive, true);
+
+const SkillsRemoveTool = Tool.make("t3_skills_remove", {
+ ...shared,
+ description:
+ "Remove a skill installed from a source (with t3_skills_install, the Tools page, or `npx skills`), with every agent's link to it. Requires a live full-access/default calling thread.",
+ parameters: Schema.Struct({ ...Scope, name: InstalledSkillName }),
+ success: Schema.Struct({}),
+}).annotate(Tool.Destructive, true);
+
+export const ToolsToolkit = Toolkit.make(
+ ToolsReadTool,
+ ToolsUpdateTool,
+ SkillsInstallTool,
+ SkillsRemoveTool,
+);
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index da5962e86d454..b9218fd740255 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -83,11 +83,16 @@ const withLibrary = (
Ref.update(refreshed, (entries) => [...entries, entry]).pipe(
Effect.andThen(Ref.get(providers)),
);
- const registry = ProviderRegistry.ProviderRegistry.of({
+ const stub: Pick<
+ ProviderRegistry.ProviderRegistry["Service"],
+ "getProviders" | "refreshInstance" | "refreshWorkspaceSnapshot"
+ > = {
getProviders: Ref.get(providers),
refreshInstance: (instanceId) => record(`instance:${instanceId}`),
refreshWorkspaceSnapshot: ({ instanceId, cwd }) => record(`workspace:${instanceId}:${cwd}`),
- } as unknown as ProviderRegistry.ProviderRegistry["Service"]);
+ };
+ // SkillLibrary reads provider snapshots and asks for rescans, nothing else.
+ const registry = stub as ProviderRegistry.ProviderRegistry["Service"];
const realProject = yield* fileSystem.realPath(project);
const projects = ProjectService.ProjectService.of({
getByWorkspaceRoot: (root: string) =>
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index d3d35a33a269e..fb2d1e02fefcb 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -93,7 +93,7 @@ const SKIPPED_DIRECTORIES = new Set([".git", "node_modules"]);
* The CLI's install source for one locked skill: the skill's own folder in
* the source, at the recorded ref, as `buildUpdateInstallSource` builds it.
*/
-export function lockedInstallSource(entry: LockEntry): string {
+function lockedInstallSource(entry: LockEntry): string {
const base = entry.sourceUrl ?? entry.source;
const ref = entry.ref === undefined ? "" : `#${entry.ref}`;
const folder = entry.skillPath?.replace(/\/?SKILL\.md$/i, "") ?? "";
@@ -277,11 +277,13 @@ const make = Effect.gen(function* () {
(candidate) => path.dirname(folder) === candidate.folder && candidate.lock.has(name),
);
const entry = install?.lock.get(name);
- const { files } = yield* listFiles(folder);
+ const { files, truncated } = yield* listFiles(folder);
return {
path: skillPath,
folder,
hash: yield* sha256(contents),
+ files,
+ filesTruncated: truncated,
scripts: hasScripts(files),
...(install === undefined || entry === undefined
? {}
diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx
new file mode 100644
index 0000000000000..8528144c7a7eb
--- /dev/null
+++ b/apps/web/src/components/settings/AddSkillsDialog.tsx
@@ -0,0 +1,219 @@
+import type { EnvironmentId, SkillInstallTarget, SkillPreviewItem } from "@t3tools/contracts";
+import { useId, useState } from "react";
+
+import { serverEnvironment } from "../../state/server";
+import { formatEnvironmentQueryError } from "../../state/query";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { Checkbox } from "../ui/checkbox";
+import {
+ Dialog,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogPanel,
+ DialogPopup,
+ DialogTitle,
+} from "../ui/dialog";
+import { Input } from "../ui/input";
+import { Label } from "../ui/label";
+import { Spinner } from "../ui/spinner";
+
+/**
+ * Install skills from a source, as `npx skills add` does: paste the source,
+ * pick from the skills it holds, install for every agent at the current scope.
+ */
+export function AddSkillsDialog({
+ open,
+ onOpenChange,
+ environmentId,
+ target,
+ scopeLabel,
+ onInstalled,
+}: {
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+ readonly environmentId: EnvironmentId;
+ readonly target: SkillInstallTarget;
+ /** Where the skills go, e.g. "This Mac" or a project name. */
+ readonly scopeLabel: string;
+ readonly onInstalled: () => void;
+}) {
+ const id = useId();
+ const preview = useAtomCommand(serverEnvironment.previewSkills, { reportFailure: false });
+ const install = useAtomCommand(serverEnvironment.installSkills, { reportFailure: false });
+ const [source, setSource] = useState("");
+ const [found, setFound] = useState<{
+ readonly source: string;
+ readonly skills: ReadonlyArray;
+ } | null>(null);
+ const [selected, setSelected] = useState>(new Set());
+ const [busy, setBusy] = useState<"finding" | "installing" | null>(null);
+ const [error, setError] = useState(null);
+
+ const find = async () => {
+ const trimmed = source.trim();
+ if (trimmed.length === 0 || busy !== null) return;
+ setBusy("finding");
+ setError(null);
+ const result = await preview({ environmentId, input: { source: trimmed } });
+ setBusy(null);
+ if (result._tag === "Failure") {
+ setFound(null);
+ setError(formatEnvironmentQueryError(result.cause));
+ return;
+ }
+ setFound({ source: trimmed, skills: result.value.skills });
+ setSelected(new Set(result.value.skills.map((skill) => skill.name)));
+ };
+
+ const installSelected = async () => {
+ if (found === null || selected.size === 0 || busy !== null) return;
+ setBusy("installing");
+ setError(null);
+ const result = await install({
+ environmentId,
+ input: { source: found.source, skills: [...selected], target },
+ });
+ setBusy(null);
+ if (result._tag === "Failure") {
+ setError(formatEnvironmentQueryError(result.cause));
+ return;
+ }
+ const failed = result.value.outcomes.filter((outcome) => outcome.status !== "installed");
+ onInstalled();
+ if (failed.length > 0) {
+ setError(
+ failed
+ .map((outcome) => `${outcome.name || found.source}: ${outcome.error ?? outcome.status}`)
+ .join("\n"),
+ );
+ return;
+ }
+ onOpenChange(false);
+ };
+
+ const toggle = (name: string, checked: boolean) =>
+ setSelected((current) => {
+ const next = new Set(current);
+ if (checked) next.add(name);
+ else next.delete(name);
+ return next;
+ });
+
+ return (
+ {
+ if (busy === null) onOpenChange(next);
+ }}
+ >
+
+
+ Add skills
+
+ Installs for every agent on {scopeLabel}, the same way npx skills add does.
+
+
+
+ {
+ event.preventDefault();
+ void find();
+ }}
+ >
+
+
Source
+
+ {
+ setSource(event.target.value);
+ setFound(null);
+ }}
+ spellCheck={false}
+ autoFocus
+ />
+
+ {busy === "finding" ? : null}
+ Find skills
+
+
+
+ A GitHub owner/repo, a git URL, or a folder on the environment.
+
+
+ {found !== null ? (
+
+
+ {found.skills.length === 1 ? "1 skill" : `${found.skills.length} skills`}
+
+
+ {found.skills.map((skill) => (
+
+ toggle(skill.name, checked === true)}
+ />
+
+
+ {skill.name}
+ {skill.scripts ? (
+
+ Includes scripts
+
+ ) : null}
+
+ {skill.description ? (
+
+ {skill.description}
+
+ ) : null}
+
+ {skill.files.length === 1 ? "1 file" : `${skill.files.length} files`}
+ {skill.filesTruncated ? " or more" : ""}
+
+
+
+ ))}
+
+
+ Skills can tell agents to run their scripts. Install only sources you trust.
+
+
+ ) : null}
+ {error !== null ? (
+ {error}
+ ) : null}
+
+
+
+ onOpenChange(false)}>
+ Cancel
+
+ void installSelected()}
+ >
+ {busy === "installing" ? : null}
+ {selected.size > 1 ? `Install ${selected.size} skills` : "Install"}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/settings/SkillFilesDialog.tsx b/apps/web/src/components/settings/SkillFilesDialog.tsx
new file mode 100644
index 0000000000000..38f111531012e
--- /dev/null
+++ b/apps/web/src/components/settings/SkillFilesDialog.tsx
@@ -0,0 +1,95 @@
+import type { EnvironmentId, SkillFolderInfo } from "@t3tools/contracts";
+import { FileIcon, TriangleAlertIcon } from "lucide-react";
+import { useState } from "react";
+
+import { cn } from "~/lib/utils";
+import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
+import {
+ FileSurfaceFailure,
+ FileSurfaceLoading,
+ FileSurfaceNotice,
+} from "../files/fileSurfaceChrome";
+import { useProjectFileQuery } from "../files/projectFilesQueryState";
+import { Badge } from "../ui/badge";
+import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";
+
+/** A skill's files and one file's text, read-only, to check what a skill does. */
+export function SkillFilesDialog({
+ open,
+ onOpenChange,
+ environmentId,
+ name,
+ folder,
+}: {
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+ readonly environmentId: EnvironmentId;
+ readonly name: string;
+ readonly folder: SkillFolderInfo;
+}) {
+ const [selected, setSelected] = useState("SKILL.md");
+ const file = useProjectFileQuery(environmentId, folder.folder, selected, open);
+
+ return (
+
+
+
+
+
+ {name}
+
+ {folder.scripts ? (
+
+
+ Includes scripts
+
+ ) : null}
+
+ {folder.folder}
+
+
+
+ {folder.files.map((entry) => (
+
+ setSelected(entry.path)}
+ >
+
+ {entry.path}
+ {entry.executable ? (
+ script
+ ) : null}
+
+
+ ))}
+ {folder.filesTruncated ? (
+ More files not shown
+ ) : null}
+
+
+ {file.data?.truncated ? (
+
Showing the first 1 MB.
+ ) : null}
+ {file.data !== null ? (
+
+
+
+ ) : file.readError?.failure === "binary_file" ? (
+
+ ) : file.error !== null ? (
+
+ ) : (
+
+ )}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index f54b0a5b342bd..ec8fb2fdaefbc 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -8,12 +8,21 @@ import {
type ProjectId,
type ServerProvider,
type ServerSettingsPatch,
+ type SkillFolderInfo,
+ type SkillInstallTarget,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
+import {
+ isSkillDisabled,
+ mcpServerEnabledPatch,
+ projectOverridePatch,
+ skillsDisabledPatch,
+} from "@t3tools/shared/agentTools";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useEnvironmentsWithScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -34,7 +43,9 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Switch } from "../ui/switch";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { AddSkillsDialog } from "./AddSkillsDialog";
import { McpServerDialog } from "./McpServerDialog";
+import { SkillFilesDialog } from "./SkillFilesDialog";
import { useSettingsScope } from "./SettingsScopeContext";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
@@ -42,14 +53,15 @@ import {
collectSkillRows,
filterSkillRows,
groupSkillRows,
- isSkillDisabled,
listMcpServerRows,
type McpServerRow,
SKILL_GROUP_LABELS,
skillReachesSomeProviders,
type SkillRow,
+ type SkillRowDetails,
+ skillRowDetails,
+ splitRowsBySource,
type ToolsTab,
- withSkillDisabled,
} from "./toolsSettings.logic";
import { useScopedSettings, useScopedSettingsWriteAllowed } from "./useScopedSettings";
@@ -154,23 +166,6 @@ function usePersistToolsPatch() {
* Replace one key of a project's override entry, dropping the key (or the entry) when empty.
* The rest of the entry is resent as stored, since the patch replaces the whole entry.
*/
-function projectOverridePatch(
- settings: {
- readonly projectSettingsOverrides: Readonly>>;
- },
- projectId: ProjectId,
- key: K,
- value: Readonly>,
-): ServerSettingsPatch {
- const { [key]: _previous, ...rest } = settings.projectSettingsOverrides[projectId] ?? {};
- const next = Object.keys(value).length === 0 ? rest : { ...rest, [key]: value };
- return {
- projectSettingsOverrides: {
- [projectId]: Object.keys(next).length === 0 ? null : next,
- },
- } as ServerSettingsPatch;
-}
-
export function ToolsSettings({
tab = "skills",
onTabChange,
@@ -223,6 +218,47 @@ function SkillsPanel() {
[providers],
);
const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
+ // Installs go to the checkout shown, or to the environment's home folders.
+ const installTarget: SkillInstallTarget | null =
+ environmentId === null
+ ? null
+ : isProjectScope
+ ? cwd === null
+ ? null
+ : { kind: "project", cwd }
+ : { kind: "environment" };
+ const canInstall = useAtomValue(serverEnvironment.installSkills.permissionAtom(environmentId));
+ const updateSkill = useAtomCommand(serverEnvironment.updateSkill, { reportFailure: false });
+ const removeSkill = useAtomCommand(serverEnvironment.removeSkill, { reportFailure: false });
+ const [adding, setAdding] = useState(false);
+ const [viewing, setViewing] = useState<{
+ readonly name: string;
+ readonly folder: SkillFolderInfo;
+ } | null>(null);
+ const [removingSkill, setRemovingSkill] = useState<{
+ readonly name: string;
+ readonly target: SkillInstallTarget;
+ } | null>(null);
+ const [skillActionError, setSkillActionError] = useState(null);
+ const inspected = useEnvironmentQuery(
+ environmentId === null
+ ? null
+ : serverEnvironment.inspectSkills({
+ environmentId,
+ input: cwd === null ? {} : { cwd },
+ }),
+ );
+ const foldersByPath = useMemo(
+ () => new Map((inspected.data?.folders ?? []).map((folder) => [folder.path, folder])),
+ [inspected.data],
+ );
+ const scopeLabel = isProjectScope
+ ? scope.kind === "project" || scope.kind === "checkout"
+ ? scope.group.displayName
+ : ""
+ : scope.kind === "environment"
+ ? scope.label
+ : "this environment";
const refresh = async (fresh: boolean) => {
if (environmentId === null) return;
@@ -242,6 +278,29 @@ function SkillsPanel() {
);
} finally {
setRefreshing(false);
+ inspected.refresh();
+ }
+ };
+
+ const afterSkillChange = () => {
+ inspected.refresh();
+ };
+
+ const runSkillAction = async (
+ action: "update" | "remove",
+ input: { readonly name: string; readonly target: SkillInstallTarget },
+ ) => {
+ if (environmentId === null) return;
+ setSkillActionError(null);
+ const result =
+ action === "update"
+ ? await updateSkill({ environmentId, input })
+ : await removeSkill({ environmentId, input });
+ afterSkillChange();
+ if (result._tag === "Failure") {
+ setSkillActionError(
+ `Couldn't ${action} ${input.name}: ${formatEnvironmentQueryError(result.cause)}`,
+ );
}
};
@@ -259,19 +318,26 @@ function SkillsPanel() {
const rows = useMemo(() => collectSkillRows(providers, cwd), [cwd, providers]);
const groups = useMemo(() => groupSkillRows(filterSkillRows(rows, query)), [query, rows]);
+ const detailsByName = useMemo(
+ () => new Map(rows.map((row) => [row.name, skillRowDetails(row, foldersByPath)])),
+ [foldersByPath, rows],
+ );
+ const detailsOf = (row: SkillRow) =>
+ detailsByName.get(row.name) ?? skillRowDetails(row, foldersByPath);
- const setSkillDisabled = (name: string, disabled: boolean) =>
- persist(({ settings, projectId }) => {
- if (projectId === null) {
- return { disabledSkills: [...withSkillDisabled(settings.disabledSkills, name, disabled)] };
- }
- const switches = { ...settings.projectSettingsOverrides[projectId]?.disabledSkills };
- const inheritedOff = isSkillDisabled(settings.disabledSkills, name);
- delete switches[name];
- // A switch that matches the environment is not an override.
- if (disabled !== inheritedOff) switches[name] = disabled;
- return projectOverridePatch(settings, projectId, "disabledSkills", switches);
- });
+ const setSkillsDisabled = (skillRows: ReadonlyArray, disabled: boolean) =>
+ persist(({ settings, projectId }) =>
+ skillsDisabledPatch(
+ settings,
+ projectId,
+ skillRows.map((row) => row.name),
+ disabled,
+ ),
+ );
+ const setSkillDisabled = (name: string, disabled: boolean) => {
+ const row = rows.find((candidate) => candidate.name === name);
+ if (row !== undefined) setSkillsDisabled([row], disabled);
+ };
return (
<>
@@ -310,7 +376,16 @@ function SkillsPanel() {
Rescan skill folders
+ {installTarget !== null && canInstall ? (
+ setAdding(true)}>
+
+ Add skills
+
+ ) : null}
+ {skillActionError !== null ? (
+ {skillActionError}
+ ) : null}
{rows.length === 0 ? (
@@ -330,28 +405,74 @@ function SkillsPanel() {
) : (
groups.map(({ group, rows: groupRows }) => (
- {groupRows.map((row) => (
-
- candidate.projectId !== null &&
- Object.hasOwn(
- target?.settings.projectSettingsOverrides[candidate.projectId]
- ?.disabledSkills ?? {},
- row.name,
- ),
- )
- }
- showProviders={skillReachesSomeProviders(row, enabledProviders.length)}
- canWrite={canWrite}
- onChange={(enabled) => setSkillDisabled(row.name, !enabled)}
- />
- ))}
+ {splitRowsBySource(groupRows, (row) => detailsOf(row).installed?.source ?? null).map(
+ ({ source, rows: sourceRows }) => {
+ const renderRow = (row: SkillRow) => {
+ const details = detailsOf(row);
+ const { folder, installed } = details;
+ return (
+
+ candidate.projectId !== null &&
+ Object.hasOwn(
+ target?.settings.projectSettingsOverrides[candidate.projectId]
+ ?.disabledSkills ?? {},
+ row.name,
+ ),
+ )
+ }
+ showProviders={skillReachesSomeProviders(row, enabledProviders.length)}
+ canWrite={canWrite}
+ onChange={(enabled) => setSkillDisabled(row.name, !enabled)}
+ onView={folder === null ? null : () => setViewing({ name: row.name, folder })}
+ onUpdate={
+ installed === null || !canInstall
+ ? null
+ : () =>
+ void runSkillAction("update", {
+ name: row.name,
+ target: installed.target,
+ })
+ }
+ onRemove={
+ installed === null || !canInstall
+ ? null
+ : () => setRemovingSkill({ name: row.name, target: installed.target })
+ }
+ />
+ );
+ };
+ if (source === null) return sourceRows.map(renderRow);
+ const allOff = sourceRows.every((row) => isSkillDisabled(disabledSkills, row.name));
+ return (
+
+
+ From {source}
+
+ }
+ control={
+ setSkillsDisabled(sourceRows, !enabled)}
+ />
+ }
+ />
+ {sourceRows.map(renderRow)}
+
+ );
+ },
+ )}
))
)}
@@ -359,24 +480,79 @@ function SkillsPanel() {
Turning a skill off hides it from Claude, Codex and OpenCode, and from the composer's skill
menu. Other agents may still load it on their own. Changes apply to new sessions.
+ {adding && environmentId !== null && installTarget !== null ? (
+
+ ) : null}
+ {viewing !== null && environmentId !== null ? (
+ {
+ if (!open) setViewing(null);
+ }}
+ environmentId={environmentId}
+ name={viewing.name}
+ folder={viewing.folder}
+ />
+ ) : null}
+ !open && setRemovingSkill(null)}
+ >
+
+
+ Remove {removingSkill?.name}?
+
+ Deletes the skill's folder and every agent's link to it, as{" "}
+ npx skills remove does.
+
+
+
+ }>Cancel
+ {
+ if (removingSkill) void runSkillAction("remove", removingSkill);
+ setRemovingSkill(null);
+ }}
+ >
+ Remove
+
+
+
+
>
);
}
function SkillSettingsRow({
row,
+ details,
disabled,
overridden,
showProviders,
canWrite,
onChange,
+ onView,
+ onUpdate,
+ onRemove,
}: {
readonly row: SkillRow;
+ readonly details: SkillRowDetails;
readonly disabled: boolean;
readonly overridden: boolean;
readonly showProviders: boolean;
readonly canWrite: boolean;
readonly onChange: (enabled: boolean) => void;
+ readonly onView: (() => void) | null;
+ readonly onUpdate: (() => void) | null;
+ readonly onRemove: (() => void) | null;
}) {
const lockedOff = row.disabledByProvider;
return (
@@ -389,6 +565,23 @@ function SkillSettingsRow({
This project
) : null}
+ {details.conflict ? (
+
+ }>
+
+ Conflict
+
+
+
+ Different skills share this name. The switch turns all of them on or off:
+ {row.paths.map((path) => (
+
+ {path}
+
+ ))}
+
+
+ ) : null}
}
description={
@@ -422,6 +615,26 @@ function SkillSettingsRow({
disabled={!canWrite || lockedOff}
onCheckedChange={onChange}
/>
+ {onView !== null || onUpdate !== null || onRemove !== null ? (
+
+
+ }
+ >
+
+
+
+ {onView !== null ? View files : null}
+ {onUpdate !== null ? Update : null}
+ {onRemove !== null ? (
+
+ Remove
+
+ ) : null}
+
+
+ ) : null}
>
}
/>
@@ -504,26 +717,9 @@ function McpServersPanel() {
});
const setEnabled = (row: McpServerRow, enabled: boolean) =>
- persist(({ settings, projectId: targetProject }) => {
- if (targetProject === null) {
- const current = settings.mcpServers[row.name];
- return current ? { mcpServers: { [row.name]: { ...current, enabled } } } : null;
- }
- const entries: Record = {
- ...settings.projectSettingsOverrides[targetProject]?.mcpServers,
- };
- const own = entries[row.name];
- const inherited = settings.mcpServers[row.name];
- if (own?.transport !== undefined) {
- entries[row.name] = { ...own, enabled };
- } else if (inherited !== undefined && inherited.enabled === enabled) {
- // Back to the environment's value: no override needed.
- delete entries[row.name];
- } else {
- entries[row.name] = { enabled };
- }
- return projectOverridePatch(settings, targetProject, "mcpServers", entries);
- });
+ persist(({ settings, projectId: targetProject }) =>
+ mcpServerEnabledPatch(settings, targetProject, row.name, enabled),
+ );
const remove = (row: McpServerRow) =>
persist(({ settings, projectId: targetProject }) => {
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 21253e922b512..493502be6edb3 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -631,7 +631,7 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/tools",
scope: "project-defaults",
searchTerms: [
- "agent skills SKILL.md disable enable hide turn off slash commands .agents claude codex cursor",
+ "agent skills SKILL.md disable enable hide turn off slash commands .agents claude codex cursor install add npx skills github repo update remove scripts conflict",
],
},
{
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index 8b3c6bb37a1a6..a8a31416237c3 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -14,6 +14,9 @@ import {
parseArgs,
parseMcpServerJson,
formatArgs,
+ skillRowDetails,
+ splitRowsBySource,
+ type SkillRow,
} from "./toolsSettings.logic";
const provider = (
@@ -99,6 +102,82 @@ describe("collectSkillRows", () => {
});
});
+describe("skill row details", () => {
+ const row = (paths: ReadonlyArray): SkillRow => ({
+ name: "review",
+ description: undefined,
+ group: "personal",
+ paths,
+ providers: [],
+ disabledByProvider: false,
+ });
+ const folder = (path: string, folderPath: string, hash: string, scripts = false) => ({
+ path,
+ folder: folderPath,
+ hash,
+ files: [],
+ filesTruncated: false,
+ scripts,
+ });
+
+ it("flags a conflict only when two folders hold different text", () => {
+ const linked = new Map([
+ // Claude reaches the same folder through its link.
+ [
+ "/h/.claude/skills/review/SKILL.md",
+ folder("/h/.claude/skills/review/SKILL.md", "/h/.agents/skills/review", "a"),
+ ],
+ [
+ "/h/.agents/skills/review/SKILL.md",
+ folder("/h/.agents/skills/review/SKILL.md", "/h/.agents/skills/review", "a"),
+ ],
+ ]);
+ expect(skillRowDetails(row([...linked.keys()]), linked).conflict).toBe(false);
+
+ const copies = new Map([
+ [
+ "/h/.claude/skills/review/SKILL.md",
+ folder("/h/.claude/skills/review/SKILL.md", "/h/.claude/skills/review", "a"),
+ ],
+ [
+ "/p/.agents/skills/review/SKILL.md",
+ folder("/p/.agents/skills/review/SKILL.md", "/p/.agents/skills/review", "b", true),
+ ],
+ ]);
+ const details = skillRowDetails(row([...copies.keys()]), copies);
+ expect(details.conflict).toBe(true);
+ expect(details.scripts).toBe(true);
+ });
+
+ it("knows nothing about a row whose folders weren't inspected", () => {
+ expect(skillRowDetails(row(["/x/SKILL.md"]), new Map())).toEqual({
+ folder: null,
+ scripts: false,
+ conflict: false,
+ installed: null,
+ });
+ });
+
+ it("splits rows by source, unsourced first, then by source name", () => {
+ const rows = [
+ { name: "tdd", source: "mattpocock/skills" },
+ { name: "mine", source: null },
+ { name: "deploy", source: "acme/tools" },
+ { name: "grill-me", source: "mattpocock/skills" },
+ ];
+ expect(
+ splitRowsBySource(rows, (entry) => entry.source).map((group) => [
+ group.source,
+ group.rows.map((entry) => entry.name),
+ ]),
+ ).toEqual([
+ [null, ["mine"]],
+ ["acme/tools", ["deploy"]],
+ ["mattpocock/skills", ["tdd", "grill-me"]],
+ ]);
+ });
+});
+
describe("listMcpServerRows", () => {
const linear: McpServerConfig = {
enabled: true,
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 0562ebfad81a4..862f43fa63874 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -8,6 +8,7 @@ import {
type ProviderInstanceId,
type ServerProvider,
type ServerProviderSkill,
+ type SkillFolderInfo,
} from "@t3tools/contracts";
import {
resolveProviderSkillSourceKind,
@@ -168,27 +169,70 @@ export function filterSkillRows(rows: ReadonlyArray, query: string) {
);
}
-/** Whether `providers` covers only some of the enabled instances, so the row should name them. */
-export function skillReachesSomeProviders(row: SkillRow, enabledProviderCount: number): boolean {
- return row.providers.length < enabledProviderCount;
+/** What the server knows about a row's folders: see `skills.inspect`. */
+export interface SkillRowDetails {
+ /** The first copy's folder, to view its files; null when no folder was inspected. */
+ readonly folder: SkillFolderInfo | null;
+ /** Some copy holds a script an agent could run. */
+ readonly scripts: boolean;
+ /** Two copies of the name have different SKILL.md text. */
+ readonly conflict: boolean;
+ /** Set when the `skills` CLI installed the row's skill, so it can be updated or removed. */
+ readonly installed: NonNullable | null;
}
-/** The environment's list with one skill switched. Sorted so equal lists compare equal. */
-export function withSkillDisabled(
- disabledSkills: ReadonlyArray,
- name: string,
- disabled: boolean,
-): ReadonlyArray {
- const next = new Set(
- disabledSkills.filter((entry) => entry.toLowerCase() !== name.toLowerCase()),
- );
- if (disabled) next.add(name);
- return [...next].toSorted();
+const NO_DETAILS: SkillRowDetails = {
+ folder: null,
+ scripts: false,
+ conflict: false,
+ installed: null,
+};
+
+export function skillRowDetails(
+ row: SkillRow,
+ folders: ReadonlyMap,
+): SkillRowDetails {
+ const infos = row.paths.flatMap((path) => {
+ const info = folders.get(path);
+ return info === undefined ? [] : [info];
+ });
+ if (infos.length === 0) return NO_DETAILS;
+ // Two agents reaching one folder through a link report two paths for one copy.
+ const hashByFolder = new Map(infos.map((info) => [info.folder, info.hash]));
+ return {
+ folder: infos[0] ?? null,
+ scripts: infos.some((info) => info.scripts),
+ conflict: new Set(hashByFolder.values()).size > 1,
+ installed: infos.find((info) => info.installed !== undefined)?.installed ?? null,
+ };
}
-export function isSkillDisabled(disabledSkills: ReadonlyArray, name: string): boolean {
- const lowered = name.toLowerCase();
- return disabledSkills.some((entry) => entry.toLowerCase() === lowered);
+/**
+ * A group's rows split by the source the `skills` CLI installed them from,
+ * so a pack of skills reads as one block with one switch. Rows with no
+ * recorded source come first, under no heading.
+ */
+export function splitRowsBySource(
+ rows: ReadonlyArray,
+ sourceOf: (row: Row) => string | null,
+): ReadonlyArray<{ readonly source: string | null; readonly rows: ReadonlyArray }> {
+ const bySource = new Map();
+ for (const row of rows) {
+ const source = sourceOf(row);
+ const list = bySource.get(source) ?? [];
+ list.push(row);
+ bySource.set(source, list);
+ }
+ return [...bySource.entries()]
+ .toSorted(([left], [right]) =>
+ left === null ? -1 : right === null ? 1 : left.localeCompare(right),
+ )
+ .map(([source, sourceRows]) => ({ source, rows: sourceRows }));
+}
+
+/** Whether `providers` covers only some of the enabled instances, so the row should name them. */
+export function skillReachesSomeProviders(row: SkillRow, enabledProviderCount: number): boolean {
+ return row.providers.length < enabledProviderCount;
}
// ── MCP servers ────────────────────────────────────────────────────
diff --git a/docs/user/tools.md b/docs/user/tools.md
index 96d04496a6457..83384521a7aad 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -19,6 +19,26 @@ off and can't be turned on here.
With a project selected, a switch overrides the environment for that project only: you can turn a
skill off for one project, or back on where the environment has it off.
+A **Conflict** mark means two different skills share a name. The switch turns both of them on or
+off. **View files** in a skill's menu shows what is in its folder; a skill marked **Includes
+scripts** has files an agent could run.
+
+### Adding skills
+
+**Add skills** installs skills from a GitHub `owner/repo`, a git URL, or a folder on the
+environment, the same way `npx skills add` does. T3 Code lists the skills in the source first, so
+you can pick some and check which include scripts. Install only sources you trust.
+
+With a project selected, skills go into the project's `.agents/skills` folder and its
+`skills-lock.json`, which you can commit for your team. Otherwise they go into `~/.agents/skills`
+for every project. Agents that only read their own folder, such as Claude, get a link to the skill.
+
+Skills installed this way, here or with `npx skills` in a terminal, are grouped by where they came
+from, with one switch for the group. Their menu has **Update**, which installs the latest version
+from the same source, and **Remove**. Installing runs the open-source
+[`skills`](https://github.com/vercel-labs/skills) installer built into T3 Code, with its telemetry
+off. Installing, updating and removing skills needs permission to manage providers.
+
## MCP servers
The **MCP servers** tab lists servers T3 Code adds to every agent session, next to its own
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 91464b16a9b15..aabc46cf1be1d 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1175,6 +1175,33 @@ export function createServerEnvironmentAtoms(
]),
},
}),
+ // Skills installed from a source: read-only facts about the skill folders
+ // the agents report, and the installs that change them.
+ inspectSkills: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:skills:inspect",
+ tag: WS_METHODS.skillsInspect,
+ staleTimeMs: 30_000,
+ idleTtlMs: 5 * 60_000,
+ }),
+ previewSkills: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:skills:preview",
+ tag: WS_METHODS.skillsPreview,
+ }),
+ installSkills: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:skills:install",
+ tag: WS_METHODS.skillsInstall,
+ concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
+ }),
+ updateSkill: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:skills:update",
+ tag: WS_METHODS.skillsUpdate,
+ concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
+ }),
+ removeSkill: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:skills:remove",
+ tag: WS_METHODS.skillsRemove,
+ concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
+ }),
updateProvider: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:update-provider",
tag: WS_METHODS.serverUpdateProvider,
diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts
index b9a46fa65287f..b13635bd173a9 100644
--- a/packages/client-runtime/src/t3ToolSummary.ts
+++ b/packages/client-runtime/src/t3ToolSummary.ts
@@ -329,6 +329,18 @@ export function summarizeT3ToolCalls(
case "environment-update":
label = phrase("Updated", "update", `environment preferences ${times}`);
break;
+ case "tools-read":
+ label = phrase("Checked", "check", `skills and MCP servers ${times}`);
+ break;
+ case "tools-update":
+ label = phrase("Updated", "update", `skills and MCP servers ${times}`);
+ break;
+ case "skills-install":
+ label = phrase("Installed", "install", `skills ${times}`);
+ break;
+ case "skills-remove":
+ label = phrase("Removed", "remove", `skills ${times}`);
+ break;
case "attachment-prepare":
label = phrase(
"Prepared",
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
index f83e7bb69a386..06912bca49d70 100644
--- a/packages/contracts/src/skills.ts
+++ b/packages/contracts/src/skills.ts
@@ -100,6 +100,9 @@ export const SkillFolderInfo = Schema.Struct({
folder: Schema.String,
/** SHA-256 of SKILL.md, so two copies of a name can be compared. */
hash: Schema.String,
+ /** The folder's files, up to a limit, for viewing them with `projects.readFile`. */
+ files: Schema.Array(SkillFileEntry),
+ filesTruncated: Schema.Boolean,
scripts: Schema.Boolean,
/** Set when the `skills` CLI installed this folder: its lock names the source. */
installed: Schema.optional(
diff --git a/packages/provider-core/src/server/AgentSkillFolders.ts b/packages/provider-core/src/server/AgentSkillFolders.ts
index 4921305ad1962..3635267470e54 100644
--- a/packages/provider-core/src/server/AgentSkillFolders.ts
+++ b/packages/provider-core/src/server/AgentSkillFolders.ts
@@ -72,7 +72,7 @@ const AGENT_SKILL_FOLDERS: Readonly> = {
};
/** The folders a driver reads, or undefined for a driver this table doesn't know. */
-export const agentSkillFolders = (driver: ProviderDriverKind): AgentSkillFolders | undefined =>
+const agentSkillFolders = (driver: ProviderDriverKind): AgentSkillFolders | undefined =>
AGENT_SKILL_FOLDERS[driver];
/**
diff --git a/packages/shared/package.json b/packages/shared/package.json
index fdc368b6c3995..98e359d5897b6 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -135,6 +135,10 @@
"types": "./src/serverSettings.ts",
"import": "./src/serverSettings.ts"
},
+ "./agentTools": {
+ "types": "./src/agentTools.ts",
+ "import": "./src/agentTools.ts"
+ },
"./backgroundActivitySettings": {
"types": "./src/backgroundActivitySettings.ts",
"import": "./src/backgroundActivitySettings.ts"
diff --git a/packages/shared/src/agentTools.ts b/packages/shared/src/agentTools.ts
new file mode 100644
index 0000000000000..299b961d37a12
--- /dev/null
+++ b/packages/shared/src/agentTools.ts
@@ -0,0 +1,112 @@
+import type {
+ McpServerProjectOverride,
+ ProjectId,
+ ServerSettings,
+ ServerSettingsPatch,
+} from "@t3tools/contracts";
+
+/**
+ * Settings patches for Settings → Tools, shared by the web page and the
+ * agents' `t3_tools_update` tool so both write the same overrides. A project
+ * patch replaces that project's whole entry, so each one is built from the
+ * current settings rather than merged later.
+ */
+
+type ToolsSettings = Pick<
+ ServerSettings,
+ "disabledSkills" | "mcpServers" | "projectSettingsOverrides"
+>;
+
+/** One project's override entry with `key` replaced, dropping what became empty. */
+export function projectOverridePatch(
+ settings: Pick,
+ projectId: ProjectId,
+ key: "mcpServers" | "disabledSkills",
+ value: Readonly>,
+): ServerSettingsPatch {
+ const { [key]: _previous, ...rest } = settings.projectSettingsOverrides[projectId] ?? {};
+ const next = Object.keys(value).length === 0 ? rest : { ...rest, [key]: value };
+ return {
+ projectSettingsOverrides: {
+ [projectId]: Object.keys(next).length === 0 ? null : next,
+ },
+ } as ServerSettingsPatch;
+}
+
+/** The environment's list with one skill switched. Sorted so equal lists compare equal. */
+function withSkillDisabled(
+ disabledSkills: ReadonlyArray,
+ name: string,
+ disabled: boolean,
+): ReadonlyArray {
+ const next = new Set(
+ disabledSkills.filter((entry) => entry.toLowerCase() !== name.toLowerCase()),
+ );
+ if (disabled) next.add(name);
+ return [...next].sort();
+}
+
+export function isSkillDisabled(disabledSkills: ReadonlyArray, name: string): boolean {
+ const lowered = name.toLowerCase();
+ return disabledSkills.some((entry) => entry.toLowerCase() === lowered);
+}
+
+/**
+ * Switch skills on or off for the environment, or for one project. A project
+ * switch that matches the environment is dropped, since it overrides nothing.
+ */
+export function skillsDisabledPatch(
+ settings: ToolsSettings,
+ projectId: ProjectId | null,
+ names: ReadonlyArray,
+ disabled: boolean,
+): ServerSettingsPatch {
+ if (projectId === null) {
+ return {
+ disabledSkills: [
+ ...names.reduce(
+ (list, name) => withSkillDisabled(list, name, disabled),
+ settings.disabledSkills,
+ ),
+ ],
+ };
+ }
+ const switches = { ...settings.projectSettingsOverrides[projectId]?.disabledSkills };
+ for (const name of names) {
+ delete switches[name];
+ if (disabled !== isSkillDisabled(settings.disabledSkills, name)) switches[name] = disabled;
+ }
+ return projectOverridePatch(settings, projectId, "disabledSkills", switches);
+}
+
+/**
+ * Switch an MCP server on or off for the environment, or for one project.
+ * Null when the environment has no server of that name. A project's own server
+ * keeps its definition; an inherited one gets a switch, or loses it when it
+ * matches the environment again.
+ */
+export function mcpServerEnabledPatch(
+ settings: ToolsSettings,
+ projectId: ProjectId | null,
+ name: string,
+ enabled: boolean,
+): ServerSettingsPatch | null {
+ const inherited = settings.mcpServers[name];
+ if (projectId === null) {
+ return inherited ? { mcpServers: { [name]: { ...inherited, enabled } } } : null;
+ }
+ const entries: Record = {
+ ...settings.projectSettingsOverrides[projectId]?.mcpServers,
+ };
+ const own = entries[name];
+ if (own?.transport !== undefined) {
+ entries[name] = { ...own, enabled };
+ } else if (inherited === undefined) {
+ return null;
+ } else if (inherited.enabled === enabled) {
+ delete entries[name];
+ } else {
+ entries[name] = { enabled };
+ }
+ return projectOverridePatch(settings, projectId, "mcpServers", entries);
+}
diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts
index 11abf77f704be..4b96d6efe528d 100644
--- a/packages/shared/src/t3McpToolPresentation.ts
+++ b/packages/shared/src/t3McpToolPresentation.ts
@@ -50,6 +50,10 @@ export type T3McpToolSummaryAction =
| "project-clone"
| "environment-read"
| "environment-update"
+ | "tools-read"
+ | "tools-update"
+ | "skills-install"
+ | "skills-remove"
| "attachment-prepare"
| "attachment-discard"
| "attachment-send"
@@ -297,6 +301,13 @@ const T3_MCP_TOOLS: Readonly> = {
["Update", "Updating", "Updated", "environment preferences"],
"environment-update",
),
+ t3_tools_read: tool(["Read", "Reading", "Read", "skills and MCP servers"], "tools-read"),
+ t3_tools_update: tool(
+ ["Update", "Updating", "Updated", "skills and MCP servers"],
+ "tools-update",
+ ),
+ t3_skills_install: tool(["Install", "Installing", "Installed", "skills"], "skills-install"),
+ t3_skills_remove: tool(["Remove", "Removing", "Removed", "a skill"], "skills-remove"),
t3_thread_launch: tool(["Launch", "Launching", "Launched", "a project thread"], "thread-create"),
t3_project_list: tool(["List", "Listing", "Listed", "projects"], "project-list"),
t3_project_read: tool(["Read", "Reading", "Read", "a project"], "project-read"),
From ec2b4753c20f0df06d9529c0636409881f764b02 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 19:39:33 -0700
Subject: [PATCH 12/35] fix: address review findings on the skills installer
- remove: the skills CLI exits 0 when it can't delete a skill, so check the
folder and lock entry afterwards and report the failure.
- update: follow the CLI's own update source rules, using a GitLab or git
lock's recorded URL and full-depth discovery when a source can't take a
folder.
- Show a per-skill update failure, and lock the source field while finding.
- t3_tools_update builds its patch inside the settings write lock
(updateSettingsWith), so a concurrent change isn't overwritten.
- Project skill switches match names ignoring case, like the environment's.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/device/DeviceService.test.ts | 1 +
.../src/mcp/toolkits/tools/handlers.test.ts | 41 ++++++-
.../server/src/mcp/toolkits/tools/handlers.ts | 102 ++++++++++--------
.../ThreadSettlementService.test.ts | 1 +
.../src/provider/ProviderRegistry.test.ts | 9 ++
apps/server/src/serverSettings.ts | 16 +++
apps/server/src/skills/SkillLibrary.test.ts | 58 +++++++++-
apps/server/src/skills/SkillLibrary.ts | 90 +++++++++++++---
apps/server/src/skills/SkillsCli.ts | 3 +
apps/server/src/terminal/Manager.test.ts | 1 +
.../components/settings/AddSkillsDialog.tsx | 2 +
.../src/components/settings/ToolsSettings.tsx | 22 ++--
packages/shared/src/agentTools.test.ts | 18 ++++
packages/shared/src/agentTools.ts | 5 +-
packages/shared/src/projectSettings.ts | 13 ++-
15 files changed, 305 insertions(+), 77 deletions(-)
diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts
index 55a7ac28a67cf..ea23209f33017 100644
--- a/apps/server/src/device/DeviceService.test.ts
+++ b/apps/server/src/device/DeviceService.test.ts
@@ -142,6 +142,7 @@ const fixture = Effect.fn("fixture")(function* (
ServerSettings.ServerSettingsService,
ServerSettings.ServerSettingsService.of({
updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
+ updateSettingsWith: () => Effect.die("Unexpected settings update"),
withSettingsSnapshot: (use) => Effect.flatMap(Ref.get(settings), use),
start: Effect.void,
ready: Effect.void,
diff --git a/apps/server/src/mcp/toolkits/tools/handlers.test.ts b/apps/server/src/mcp/toolkits/tools/handlers.test.ts
index fd99c4faed9ee..b8c0012a30290 100644
--- a/apps/server/src/mcp/toolkits/tools/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/tools/handlers.test.ts
@@ -50,6 +50,8 @@ it.effect("switches skills and servers for a project as one patch, and never ret
Effect.gen(function* () {
const settings = yield* Ref.make(initial);
const patches = yield* Ref.make>([]);
+ // Applied once, right after the next read, as a concurrent write would be.
+ const interleave = yield* Ref.make<((current: ServerSettings) => ServerSettings) | null>(null);
const layerDependencies = Layer.mergeAll(
ThreadCommandExecutor.layer,
Layer.succeed(McpInvocationContext.McpInvocationContext, {
@@ -77,10 +79,20 @@ it.effect("switches skills and servers for a project as one patch, and never ret
}),
}),
Layer.mock(Settings.ServerSettingsService)({
- getSettings: Ref.get(settings),
- updateSettings: (patch) =>
- Ref.update(patches, (list) => [...list, patch]).pipe(
- Effect.andThen(
+ getSettings: Ref.get(settings).pipe(
+ Effect.tap(() =>
+ Ref.getAndSet(interleave, null).pipe(
+ Effect.flatMap((change) =>
+ change === null ? Effect.void : Ref.update(settings, change),
+ ),
+ ),
+ ),
+ ),
+ updateSettingsWith: (build) =>
+ Ref.get(settings).pipe(
+ Effect.map(build),
+ Effect.tap((patch) => Ref.update(patches, (list) => [...list, patch])),
+ Effect.flatMap((patch) =>
Ref.updateAndGet(settings, (current) => applyServerSettingsPatch(current, patch)),
),
),
@@ -112,6 +124,27 @@ it.effect("switches skills and servers for a project as one patch, and never ret
});
// The environment itself is unchanged.
expect((yield* Ref.get(settings)).disabledSkills).toEqual(["grill-me"]);
+
+ // Another change lands after this call reads settings, before it writes; it survives.
+ yield* Ref.set(interleave, (current) => ({
+ ...current,
+ projectSettingsOverrides: {
+ ...current.projectSettingsOverrides,
+ [projectId]: {
+ ...current.projectSettingsOverrides[projectId],
+ disabledSkills: {
+ ...current.projectSettingsOverrides[projectId]?.disabledSkills,
+ review: true,
+ },
+ },
+ },
+ }));
+ yield* toolkit
+ .handle("t3_tools_update", { projectId, skills: [{ name: "tdd", enabled: true }] })
+ .pipe(Stream.unwrap, Stream.runCollect);
+ expect(
+ (yield* Ref.get(settings)).projectSettingsOverrides[projectId]?.disabledSkills,
+ ).toEqual({ "grill-me": false, review: true });
}).pipe(
Effect.provide(
McpToolAccess.HandlersLayer.layer(ToolsHandlers.layer).pipe(
diff --git a/apps/server/src/mcp/toolkits/tools/handlers.ts b/apps/server/src/mcp/toolkits/tools/handlers.ts
index c8e0909a2ba38..e196af17d59cd 100644
--- a/apps/server/src/mcp/toolkits/tools/handlers.ts
+++ b/apps/server/src/mcp/toolkits/tools/handlers.ts
@@ -35,6 +35,53 @@ function toolsState(settings: ServerSettings, projectId: ProjectId | undefined)
};
}
+/**
+ * Every requested switch as one patch: each change builds on the last, and the
+ * patch carries the resulting entries, so they land in one write.
+ */
+function toolsUpdatePatch(
+ current: ServerSettings,
+ projectId: ProjectId | null,
+ input: {
+ readonly skills?:
+ | ReadonlyArray<{ readonly name: string; readonly enabled: boolean }>
+ | undefined;
+ readonly mcpServers?:
+ | ReadonlyArray<{ readonly name: string; readonly enabled: boolean }>
+ | undefined;
+ },
+): ServerSettingsPatch {
+ let next = current;
+ for (const enabled of [true, false]) {
+ const names = (input.skills ?? [])
+ .filter((skill) => skill.enabled === enabled)
+ .map((skill) => skill.name);
+ if (names.length > 0) {
+ next = applyServerSettingsPatch(next, skillsDisabledPatch(next, projectId, names, !enabled));
+ }
+ }
+ for (const server of input.mcpServers ?? []) {
+ const step = mcpServerEnabledPatch(next, projectId, server.name, server.enabled);
+ if (step !== null) next = applyServerSettingsPatch(next, step);
+ }
+ if (projectId !== null) {
+ return {
+ projectSettingsOverrides: { [projectId]: next.projectSettingsOverrides[projectId] ?? null },
+ } as ServerSettingsPatch;
+ }
+ const servers = (input.mcpServers ?? []).map((server) => server.name);
+ return {
+ ...(input.skills === undefined ? {} : { disabledSkills: next.disabledSkills }),
+ ...(servers.length === 0
+ ? {}
+ : {
+ mcpServers: Object.fromEntries(
+ servers.map((name) => [name, next.mcpServers[name] ?? null]),
+ ),
+ }),
+ };
+}
+
const access = Effect.gen(function* () {
const context = yield* readCaller();
const environment = yield* Environment.ServerEnvironment;
@@ -92,48 +139,19 @@ export const layer = McpToolAccess.toLayer(ToolsToolkit, {
Effect.gen(function* () {
const { settings } = yield* access;
const projectId = input.projectId ?? null;
- // Each change builds on the last; the patch is then read off the result,
- // so everything lands in one write.
- let next = yield* settings.getSettings.pipe(Effect.mapError(unavailable));
- for (const enabled of [true, false]) {
- const names = (input.skills ?? [])
- .filter((skill) => skill.enabled === enabled)
- .map((skill) => skill.name);
- if (names.length > 0) {
- next = applyServerSettingsPatch(
- next,
- skillsDisabledPatch(next, projectId, names, !enabled),
- );
- }
- }
- for (const server of input.mcpServers ?? []) {
- const step = mcpServerEnabledPatch(next, projectId, server.name, server.enabled);
- if (step === null)
- return yield* new OrchestratorMcpFailure({
- code: "invalid_request",
- message: `There is no Settings → Tools server named ${server.name}.`,
- });
- next = applyServerSettingsPatch(next, step);
- }
- const servers = (input.mcpServers ?? []).map((server) => server.name);
- const patch: ServerSettingsPatch =
- projectId === null
- ? {
- ...(input.skills === undefined ? {} : { disabledSkills: next.disabledSkills }),
- ...(servers.length === 0
- ? {}
- : {
- mcpServers: Object.fromEntries(
- servers.map((name) => [name, next.mcpServers[name] ?? null]),
- ),
- }),
- }
- : ({
- projectSettingsOverrides: {
- [projectId]: next.projectSettingsOverrides[projectId] ?? null,
- },
- } as ServerSettingsPatch);
- const saved = yield* settings.updateSettings(patch).pipe(Effect.mapError(unavailable));
+ const current = yield* settings.getSettings.pipe(Effect.mapError(unavailable));
+ const missing = (input.mcpServers ?? []).find(
+ (server) => mcpServerEnabledPatch(current, projectId, server.name, true) === null,
+ );
+ if (missing !== undefined)
+ return yield* new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message: `There is no Settings → Tools server named ${missing.name}.`,
+ });
+ // Built from the settings the write sees, so a concurrent change isn't lost.
+ const saved = yield* settings
+ .updateSettingsWith((latest) => toolsUpdatePatch(latest, projectId, input))
+ .pipe(Effect.mapError(unavailable));
return toolsState(saved, input.projectId);
}),
),
diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
index 4b0e451e0ae66..e6942a0833437 100644
--- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
@@ -572,6 +572,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
ready: Effect.void,
getSettings: Ref.get(settings),
updateSettings,
+ updateSettingsWith: () => Effect.die("Unexpected settings update"),
updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)),
streamChanges: Stream.fromPubSub(settingsChanges),
diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts
index d0c1f348a7366..0debbc0c7badc 100644
--- a/apps/server/src/provider/ProviderRegistry.test.ts
+++ b/apps/server/src/provider/ProviderRegistry.test.ts
@@ -361,6 +361,15 @@ function makeMutableServerSettingsService(
yield* PubSub.publish(changes, next);
return next;
}),
+ updateSettingsWith: (patch) =>
+ Effect.gen(function* () {
+ const current = yield* Ref.get(settingsRef);
+ const next = applyServerSettingsPatch(current, patch(current));
+ encodeServerSettings(next);
+ yield* Ref.set(settingsRef, next);
+ yield* PubSub.publish(changes, next);
+ return next;
+ }),
updateProviderInstance: (mutation, patch = {}) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 660b7310eedd7..ccf0dd11f9c56 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -282,6 +282,14 @@ export class ServerSettingsService extends Context.Service<
patch: ServerSettingsPatch,
) => Effect.Effect;
+ /**
+ * Patch settings with a patch built from the latest settings inside the
+ * write lock, so a change derived from them can't undo a concurrent one.
+ */
+ readonly updateSettingsWith: (
+ patch: (current: ServerSettings) => ServerSettingsPatch,
+ ) => Effect.Effect;
+
/** Apply a patch and one provider-instance mutation against the same latest settings snapshot. */
readonly updateProviderInstance: (
mutation: ProviderInstanceMutation,
@@ -346,6 +354,10 @@ const makeTest = (overrides: DeepPartial = {}) =>
updateTestSettings((currentSettings) =>
Effect.succeed(applyServerSettingsPatch(currentSettings, patch)),
),
+ updateSettingsWith: (patch) =>
+ updateTestSettings((currentSettings) =>
+ Effect.succeed(applyServerSettingsPatch(currentSettings, patch(currentSettings))),
+ ),
updateProviderInstance: (mutation, patch = {}) =>
updateTestSettings((currentSettings) =>
Effect.gen(function* () {
@@ -1471,6 +1483,10 @@ const make = Effect.gen(function* () {
updateAndPersistSettings((current) =>
Effect.succeed(applyServerSettingsPatch(current, patch)),
),
+ updateSettingsWith: (patch) =>
+ updateAndPersistSettings((current) =>
+ Effect.succeed(applyServerSettingsPatch(current, patch(current))),
+ ),
updateProviderInstance: (mutation, patch = {}) =>
updateAndPersistSettings((current) =>
Effect.gen(function* () {
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index b9218fd740255..8956adb999a1d 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { assert, it } from "@effect/vitest";
+import { assert, describe, expect, it } from "@effect/vitest";
import {
ProjectId,
ProviderDriverKind,
@@ -22,6 +22,7 @@ import * as ProcessRunner from "../processRunner.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
import * as SkillLibrary from "./SkillLibrary.ts";
+import { lockedInstallSource } from "./SkillLibrary.ts";
const SKILL = (name: string, description: string) =>
`---\nname: ${name}\ndescription: ${description}\n---\n\nUse ${name}.\n`;
@@ -232,3 +233,58 @@ it.effect(
),
60_000,
);
+
+it.effect(
+ "fails a removal the CLI couldn't finish, which it reports with a zero exit",
+ () =>
+ withLibrary(({ library, project, source }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const target = { kind: "project", cwd: project } as const;
+ yield* library.install({ source, skills: ["notes"], target });
+ const folder = path.join(project, ".agents", "skills");
+ yield* fileSystem.chmod(folder, 0o555);
+ const failure = yield* library
+ .remove({ name: "notes", target })
+ .pipe(Effect.flip, Effect.ensuring(fileSystem.chmod(folder, 0o755).pipe(Effect.ignore)));
+ assert.equal(failure.reason, "cliFailed");
+ assert.isTrue(yield* fileSystem.exists(path.join(folder, "notes")));
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 120_000,
+);
+
+describe("lockedInstallSource", () => {
+ it("updates one skill from its folder, as `npx skills update` does", () => {
+ const skillPath = "skills/productivity/grill-me/SKILL.md";
+ expect(
+ lockedInstallSource({ source: "mattpocock/skills", sourceType: "github", skillPath }, "home"),
+ ).toEqual({ source: "mattpocock/skills/skills/productivity/grill-me", fullDepth: false });
+ // A source that can't take a folder is searched in full, so a root SKILL.md can't win.
+ expect(
+ lockedInstallSource(
+ { source: "git@example.com:team/skills.git", sourceType: "git", skillPath, ref: "v2" },
+ "project",
+ ),
+ ).toEqual({ source: "git@example.com:team/skills.git#v2", fullDepth: true });
+ });
+
+ it("uses a recorded GitLab URL, and refuses a GitLab shorthand GitHub would answer", () => {
+ const skillPath = "tools/review/SKILL.md";
+ expect(
+ lockedInstallSource(
+ {
+ source: "group/repo",
+ sourceType: "gitlab",
+ sourceUrl: "https://gitlab.com/group/repo",
+ skillPath,
+ },
+ "project",
+ ),
+ ).toEqual({ source: "https://gitlab.com/group/repo/tools/review", fullDepth: false });
+ expect(
+ lockedInstallSource({ source: "group/repo", sourceType: "gitlab", skillPath }, "project"),
+ ).toBeNull();
+ });
+});
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index fb2d1e02fefcb..cbe412002d7a1 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -89,22 +89,57 @@ const MAX_DIRECTORIES = 200;
/** Folders an installer or VCS leaves behind, never part of the skill. */
const SKIPPED_DIRECTORIES = new Set([".git", "node_modules"]);
+/*
+ * Where to reinstall a locked skill from. A port of the CLI's own update
+ * (`update-source.ts` in vercel-labs/skills 1.7.1), so Update here and
+ * `npx skills update` fetch the same thing.
+ */
+
+/** Only GitHub-style shorthands and GitHub or GitLab URLs can take a folder after them. */
+function takesSubpath(source: string): boolean {
+ if (source.startsWith("git@") || source.startsWith("ssh://") || source.endsWith(".git")) {
+ return false;
+ }
+ if (!/^https?:\/\//.test(source)) return true;
+ return /^https?:\/\/(?:github|gitlab)\.com\//.test(source);
+}
+
+/**
+ * A source other than GitHub, as a project lock records it. Older locks wrote
+ * GitLab and generic Git sources as a bare `group/repo`, which would be read
+ * as GitHub, so those need the recorded URL.
+ */
+function nonGithubSource(entry: LockEntry): string | null {
+ if (entry.sourceUrl !== undefined) return entry.sourceUrl;
+ const bare = !entry.source.includes(":") && !/^[./]/.test(entry.source);
+ return (entry.sourceType === "git" || entry.sourceType === "gitlab") && bare
+ ? null
+ : entry.source;
+}
+
/**
- * The CLI's install source for one locked skill: the skill's own folder in
- * the source, at the recorded ref, as `buildUpdateInstallSource` builds it.
+ * The CLI's `add` source for one locked skill: its folder in the source at the
+ * recorded ref, or the whole repository with `fullDepth` when the source can't
+ * take a folder. Null when the lock doesn't say which host it came from.
*/
-function lockedInstallSource(entry: LockEntry): string {
- const base = entry.sourceUrl ?? entry.source;
+export function lockedInstallSource(
+ entry: LockEntry,
+ level: "home" | "project",
+): { readonly source: string; readonly fullDepth: boolean } | null {
+ const github = entry.sourceType === undefined || entry.sourceType === "github";
+ const source =
+ level === "project" || !github
+ ? nonGithubSource(entry)
+ : entry.skillPath === undefined
+ ? (entry.sourceUrl ?? entry.source)
+ : entry.source;
+ if (source === null) return null;
const ref = entry.ref === undefined ? "" : `#${entry.ref}`;
const folder = entry.skillPath?.replace(/\/?SKILL\.md$/i, "") ?? "";
- // Only GitHub-style shorthands and GitHub or GitLab URLs take a subpath.
- const takesSubpath =
- folder !== "" &&
- !entry.source.endsWith(".git") &&
- !/^(?:git@|ssh:\/\/)/.test(entry.source) &&
- (!/^https?:\/\//.test(entry.source) ||
- /^https?:\/\/(?:github|gitlab)\.com\//.test(entry.source));
- return takesSubpath ? `${entry.source}/${folder}${ref}` : `${base}${ref}`;
+ if (folder !== "" && takesSubpath(source)) {
+ return { source: `${source}/${folder}${ref}`, fullDepth: false };
+ }
+ return { source: `${source}${ref}`, fullDepth: folder !== "" };
}
const make = Effect.gen(function* () {
@@ -375,7 +410,12 @@ const make = Effect.gen(function* () {
})),
});
- const installInto = (target: SkillInstallTarget, source: string, skills: ReadonlyArray) =>
+ const installInto = (
+ target: SkillInstallTarget,
+ source: string,
+ skills: ReadonlyArray,
+ fullDepth = false,
+ ) =>
Effect.gen(function* () {
const drivers: ReadonlyArray = (yield* enabledProviders).map(
(provider: ServerProvider) => provider.driver,
@@ -385,6 +425,7 @@ const make = Effect.gen(function* () {
skills,
agents: skillsCliInstallAgents(drivers, target.kind === "environment" ? "home" : "project"),
global: target.kind === "environment",
+ fullDepth,
cwd: targetPaths(target).root,
});
yield* refreshAgents(target);
@@ -417,7 +458,15 @@ const make = Effect.gen(function* () {
function* (input) {
const target = yield* resolveTarget(input.target);
const entry = yield* lockedEntry(target, input.name);
- return yield* installInto(target, lockedInstallSource(entry), [input.name]);
+ const from = lockedInstallSource(entry, target.kind === "environment" ? "home" : "project");
+ if (from === null) {
+ return yield* new SkillLibraryError({
+ reason: "notInstalled",
+ message:
+ "This skill's lock doesn't record which host it came from. Install it again from its URL.",
+ });
+ }
+ return yield* installInto(target, from.source, [input.name], from.fullDepth);
},
);
@@ -425,11 +474,12 @@ const make = Effect.gen(function* () {
function* (input) {
const target = yield* resolveTarget(input.target);
yield* lockedEntry(target, input.name);
+ const paths = targetPaths(target);
yield* cli
.remove({
skills: [input.name],
global: target.kind === "environment",
- cwd: targetPaths(target).root,
+ cwd: paths.root,
})
.pipe(
Effect.catchTags({
@@ -437,6 +487,16 @@ const make = Effect.gen(function* () {
}),
);
yield* refreshAgents(target);
+ // The CLI reports a skill it couldn't delete without failing, so check what's left.
+ const folderLeft = yield* fileSystem
+ .exists(path.join(paths.folder, input.name))
+ .pipe(Effect.orElseSucceed(() => false));
+ const lockLeft = (yield* readLock(paths.lock)).has(input.name);
+ if (folderLeft || lockLeft) {
+ return yield* cliFailed(
+ `Couldn't remove ${input.name}. Check the permissions of ${folderLeft ? paths.folder : paths.lock}.`,
+ );
+ }
},
);
diff --git a/apps/server/src/skills/SkillsCli.ts b/apps/server/src/skills/SkillsCli.ts
index 44fecad739a17..33a7aa1df331a 100644
--- a/apps/server/src/skills/SkillsCli.ts
+++ b/apps/server/src/skills/SkillsCli.ts
@@ -46,6 +46,8 @@ export interface SkillsCliAddInput {
readonly agents: ReadonlyArray;
/** Install into the home folders instead of `cwd`. */
readonly global: boolean;
+ /** Look through the whole repository, not just its root skill. */
+ readonly fullDepth?: boolean;
/** The project root, or the temp folder a preview unpacks into. */
readonly cwd: string;
}
@@ -108,6 +110,7 @@ const make = Effect.gen(function* () {
"--agent",
...input.agents,
...(input.global ? ["--global"] : []),
+ ...(input.fullDepth === true ? ["--full-depth"] : []),
"--yes",
"--json",
],
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index 5a40f7bbb9334..21637dce8c1ea 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -2200,6 +2200,7 @@ it.layer(
ready: Effect.void,
getSettings: Effect.fail(settingsError),
updateSettings: () => Effect.fail(settingsError),
+ updateSettingsWith: () => Effect.fail(settingsError),
updateProviderInstance: () => Effect.fail(settingsError),
withSettingsSnapshot: () => Effect.fail(settingsError),
streamChanges: Stream.empty,
diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx
index 8528144c7a7eb..01394b3b423c8 100644
--- a/apps/web/src/components/settings/AddSkillsDialog.tsx
+++ b/apps/web/src/components/settings/AddSkillsDialog.tsx
@@ -129,6 +129,8 @@ export function AddSkillsDialog({
{
if (environmentId === null) return;
setSkillActionError(null);
- const result =
- action === "update"
- ? await updateSkill({ environmentId, input })
- : await removeSkill({ environmentId, input });
+ const failure = async () => {
+ if (action === "remove") {
+ const result = await removeSkill({ environmentId, input });
+ return result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null;
+ }
+ const result = await updateSkill({ environmentId, input });
+ if (result._tag === "Failure") return formatEnvironmentQueryError(result.cause);
+ // The CLI reports a skill it couldn't reinstall as a result, not an error.
+ const failed = result.value.outcomes.find((outcome) => outcome.status !== "installed");
+ return failed === undefined ? null : (failed.error ?? failed.status);
+ };
+ const message = await failure();
afterSkillChange();
- if (result._tag === "Failure") {
- setSkillActionError(
- `Couldn't ${action} ${input.name}: ${formatEnvironmentQueryError(result.cause)}`,
- );
- }
+ if (message !== null) setSkillActionError(`Couldn't ${action} ${input.name}: ${message}`);
};
// A project's skills live in its checkout, which each provider only scans
diff --git a/packages/shared/src/agentTools.test.ts b/packages/shared/src/agentTools.test.ts
index 1641e5e151041..88ac48272c4f1 100644
--- a/packages/shared/src/agentTools.test.ts
+++ b/packages/shared/src/agentTools.test.ts
@@ -10,6 +10,7 @@ import {
import * as Schema from "effect/Schema";
import { describe, expect, it } from "vite-plus/test";
+import { skillsDisabledPatch } from "./agentTools.ts";
import { resolveProjectSettings } from "./projectSettings.ts";
import { applyServerSettingsPatch } from "./serverSettings.ts";
@@ -92,6 +93,23 @@ describe("project tools overrides", () => {
});
});
+describe("skill switches", () => {
+ it("turns an inherited skill back on for a project whatever its case", () => {
+ const settings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ disabledSkills: ["Grill-Me"],
+ projectSettingsOverrides: { [projectId]: { disabledSkills: { "GRILL-ME": true } } },
+ } satisfies ServerSettings;
+ const next = applyServerSettingsPatch(
+ settings,
+ skillsDisabledPatch(settings, projectId, ["grill-me"], false),
+ );
+ // One switch replaces the differently cased one, and it wins over the environment's spelling.
+ expect(next.projectSettingsOverrides[projectId]?.disabledSkills).toEqual({ "grill-me": false });
+ expect(resolveProjectSettings(next, projectId).settings.disabledSkills).toEqual([]);
+ });
+});
+
describe("mcpServers patches", () => {
it("replaces one server at a time and removes it with null", () => {
const current = { ...DEFAULT_SERVER_SETTINGS, mcpServers: { linear, supabase } };
diff --git a/packages/shared/src/agentTools.ts b/packages/shared/src/agentTools.ts
index 299b961d37a12..bd9a985517497 100644
--- a/packages/shared/src/agentTools.ts
+++ b/packages/shared/src/agentTools.ts
@@ -73,7 +73,10 @@ export function skillsDisabledPatch(
}
const switches = { ...settings.projectSettingsOverrides[projectId]?.disabledSkills };
for (const name of names) {
- delete switches[name];
+ // One switch per name, whatever its case.
+ for (const existing of Object.keys(switches)) {
+ if (existing.toLowerCase() === name.toLowerCase()) delete switches[existing];
+ }
if (disabled !== isSkillDisabled(settings.disabledSkills, name)) switches[name] = disabled;
}
return projectOverridePatch(settings, projectId, "disabledSkills", switches);
diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts
index 5895f2226b370..a6d0b1f44a0bc 100644
--- a/packages/shared/src/projectSettings.ts
+++ b/packages/shared/src/projectSettings.ts
@@ -232,18 +232,21 @@ function mergeProjectMcpServers(
return merged as McpServers;
}
-/** The environment's disabled skills with a project's per-name switches applied. */
+/**
+ * The environment's disabled skills with a project's per-name switches
+ * applied. Names match ignoring case, as agents and the composer match them.
+ */
export function mergeProjectDisabledSkills(
environment: DisabledSkills,
project: DisabledSkillsProjectOverride | undefined,
): DisabledSkills {
if (project === undefined) return environment;
- const disabled = new Set(environment);
+ const disabled = new Map(environment.map((name) => [name.toLowerCase(), name]));
for (const [name, off] of Object.entries(project)) {
- if (off) disabled.add(name);
- else disabled.delete(name);
+ if (off) disabled.set(name.toLowerCase(), disabled.get(name.toLowerCase()) ?? name);
+ else disabled.delete(name.toLowerCase());
}
- return [...disabled].sort();
+ return [...disabled.values()].sort();
}
/** Replace the project's entry, dropping it entirely when nothing is overridden. */
From 64303a5bb980fa8166422cf8bfb34bb88dbf551d Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 19:51:27 -0700
Subject: [PATCH 13/35] fix: run skill changes one at a time, and keep the
environment's spelling
- install, update and remove share a lock: each skills CLI run rewrites a
whole lock file, so two at once could drop each other's entries.
- A project skill switch is written with the environment's spelling of
the name.
- The CLI child gets the host environment it resolved (HostProcessEnvironment)
rather than the process's own, so tests run it against their temp home.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/skills/SkillLibrary.test.ts | 24 +++++++++++++
apps/server/src/skills/SkillLibrary.ts | 38 ++++++++++++++-------
apps/server/src/skills/SkillsCli.ts | 5 +++
packages/shared/src/agentTools.test.ts | 4 +--
packages/shared/src/agentTools.ts | 5 ++-
5 files changed, 61 insertions(+), 15 deletions(-)
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index 8956adb999a1d..757af762d2d18 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -255,6 +255,30 @@ it.effect(
120_000,
);
+it.effect(
+ "keeps both lock entries when two installs run at once",
+ () =>
+ withLibrary(({ library, home, source }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const target = { kind: "environment" } as const;
+ yield* Effect.all(
+ [
+ library.install({ source, skills: ["notes"], target }),
+ library.install({ source, skills: ["review"], target }),
+ ],
+ { concurrency: "unbounded" },
+ );
+ const lock = JSON.parse(
+ yield* fileSystem.readFileString(path.join(home, ".agents", ".skill-lock.json")),
+ ) as { skills: Record };
+ expect(Object.keys(lock.skills).toSorted()).toEqual(["notes", "review"]);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 120_000,
+);
+
describe("lockedInstallSource", () => {
it("updates one skill from its folder, as `npx skills update` does", () => {
const skillPath = "skills/productivity/grill-me/SKILL.md";
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index cbe412002d7a1..2e08a83c117af 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -42,6 +42,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import * as Semaphore from "effect/Semaphore";
import { parse as parseYamlDocument } from "yaml";
import * as ProjectService from "../project/ProjectService.ts";
@@ -147,6 +148,9 @@ const make = Effect.gen(function* () {
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const cli = yield* SkillsCli.SkillsCli;
+ // Each CLI run rewrites a whole lock file without locking it, so two at once
+ // can drop each other's entries. Installs are rare; run them one at a time.
+ const changes = yield* Semaphore.make(1);
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const projectService = yield* ProjectService.ProjectService;
const environment = yield* HostProcessEnvironment;
@@ -435,7 +439,7 @@ const make = Effect.gen(function* () {
const install: SkillLibrary["Service"]["install"] = Effect.fn("SkillLibrary.install")(
function* (input) {
const target = yield* resolveTarget(input.target);
- return yield* installInto(target, input.source, input.skills);
+ return yield* installInto(target, input.source, input.skills).pipe(changes.withPermits(1));
},
);
@@ -457,7 +461,13 @@ const make = Effect.gen(function* () {
const update: SkillLibrary["Service"]["update"] = Effect.fn("SkillLibrary.update")(
function* (input) {
const target = yield* resolveTarget(input.target);
- const entry = yield* lockedEntry(target, input.name);
+ return yield* updateLocked(target, input.name).pipe(changes.withPermits(1));
+ },
+ );
+
+ const updateLocked = (target: SkillInstallTarget, name: string) =>
+ Effect.gen(function* () {
+ const entry = yield* lockedEntry(target, name);
const from = lockedInstallSource(entry, target.kind === "environment" ? "home" : "project");
if (from === null) {
return yield* new SkillLibraryError({
@@ -466,18 +476,23 @@ const make = Effect.gen(function* () {
"This skill's lock doesn't record which host it came from. Install it again from its URL.",
});
}
- return yield* installInto(target, from.source, [input.name], from.fullDepth);
- },
- );
+ return yield* installInto(target, from.source, [name], from.fullDepth);
+ });
const remove: SkillLibrary["Service"]["remove"] = Effect.fn("SkillLibrary.remove")(
function* (input) {
const target = yield* resolveTarget(input.target);
- yield* lockedEntry(target, input.name);
+ yield* removeLocked(target, input.name).pipe(changes.withPermits(1));
+ },
+ );
+
+ const removeLocked = (target: SkillInstallTarget, name: string) =>
+ Effect.gen(function* () {
+ yield* lockedEntry(target, name);
const paths = targetPaths(target);
yield* cli
.remove({
- skills: [input.name],
+ skills: [name],
global: target.kind === "environment",
cwd: paths.root,
})
@@ -489,16 +504,15 @@ const make = Effect.gen(function* () {
yield* refreshAgents(target);
// The CLI reports a skill it couldn't delete without failing, so check what's left.
const folderLeft = yield* fileSystem
- .exists(path.join(paths.folder, input.name))
+ .exists(path.join(paths.folder, name))
.pipe(Effect.orElseSucceed(() => false));
- const lockLeft = (yield* readLock(paths.lock)).has(input.name);
+ const lockLeft = (yield* readLock(paths.lock)).has(name);
if (folderLeft || lockLeft) {
return yield* cliFailed(
- `Couldn't remove ${input.name}. Check the permissions of ${folderLeft ? paths.folder : paths.lock}.`,
+ `Couldn't remove ${name}. Check the permissions of ${folderLeft ? paths.folder : paths.lock}.`,
);
}
- },
- );
+ });
return SkillLibrary.of({ inspect, preview, install, update, remove });
});
diff --git a/apps/server/src/skills/SkillsCli.ts b/apps/server/src/skills/SkillsCli.ts
index 33a7aa1df331a..215202394ec82 100644
--- a/apps/server/src/skills/SkillsCli.ts
+++ b/apps/server/src/skills/SkillsCli.ts
@@ -13,6 +13,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
+import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
import * as ProcessRunner from "../processRunner.ts";
@@ -80,6 +81,9 @@ const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
const make = Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
const self = yield* resolveSelfInvocation();
+ // The host's environment, including the PATH the server resolved, decides
+ // which home the CLI installs into, so it's passed in whole.
+ const environment = yield* HostProcessEnvironment;
const run = (command: "add" | "remove", args: ReadonlyArray, cwd: string) =>
processRunner
@@ -88,6 +92,7 @@ const make = Effect.gen(function* () {
args: [...selfInvocationArgs(self, ["skills-cli", command, ...args])],
cwd,
env: {
+ ...environment,
ELECTRON_RUN_AS_NODE: "1",
DISABLE_TELEMETRY: "1",
DO_NOT_TRACK: "1",
diff --git a/packages/shared/src/agentTools.test.ts b/packages/shared/src/agentTools.test.ts
index 88ac48272c4f1..c82b5af448e30 100644
--- a/packages/shared/src/agentTools.test.ts
+++ b/packages/shared/src/agentTools.test.ts
@@ -104,8 +104,8 @@ describe("skill switches", () => {
settings,
skillsDisabledPatch(settings, projectId, ["grill-me"], false),
);
- // One switch replaces the differently cased one, and it wins over the environment's spelling.
- expect(next.projectSettingsOverrides[projectId]?.disabledSkills).toEqual({ "grill-me": false });
+ // One switch replaces the differently cased one, spelled as the environment spells it.
+ expect(next.projectSettingsOverrides[projectId]?.disabledSkills).toEqual({ "Grill-Me": false });
expect(resolveProjectSettings(next, projectId).settings.disabledSkills).toEqual([]);
});
});
diff --git a/packages/shared/src/agentTools.ts b/packages/shared/src/agentTools.ts
index bd9a985517497..5a863afd05852 100644
--- a/packages/shared/src/agentTools.ts
+++ b/packages/shared/src/agentTools.ts
@@ -77,7 +77,10 @@ export function skillsDisabledPatch(
for (const existing of Object.keys(switches)) {
if (existing.toLowerCase() === name.toLowerCase()) delete switches[existing];
}
- if (disabled !== isSkillDisabled(settings.disabledSkills, name)) switches[name] = disabled;
+ // Spelled as the environment spells it, so the switch reads as the same skill.
+ const spelling =
+ settings.disabledSkills.find((entry) => entry.toLowerCase() === name.toLowerCase()) ?? name;
+ if (disabled !== isSkillDisabled(settings.disabledSkills, name)) switches[spelling] = disabled;
}
return projectOverridePatch(settings, projectId, "disabledSkills", switches);
}
From 28399ce84d23883db3f93ee33be7982afabd93b9 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 19:57:41 -0700
Subject: [PATCH 14/35] fix: rescan listed projects after a global skill
change, and handle any skill name
- A global install, update or remove now rescans every project an agent has
listed, since a project's skill list includes the global skills.
- Project skill switches use a null-prototype map, so a skill named
__proto__ gets a switch like any other.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/skills/SkillLibrary.test.ts | 14 +++++++++--
apps/server/src/skills/SkillLibrary.ts | 26 ++++++++++++++-------
packages/shared/src/agentTools.test.ts | 11 +++++++++
packages/shared/src/agentTools.ts | 6 ++++-
4 files changed, 45 insertions(+), 12 deletions(-)
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index 757af762d2d18..ebec7741b3769 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -256,13 +256,22 @@ it.effect(
);
it.effect(
- "keeps both lock entries when two installs run at once",
+ "keeps both lock entries when two installs run at once, and rescans listed projects",
() =>
- withLibrary(({ library, home, source }) =>
+ withLibrary(({ library, home, project, source, providers, refreshed }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const target = { kind: "environment" } as const;
+ // Claude has listed this project's skills, which include the global ones.
+ yield* Ref.set(providers, [
+ {
+ ...claude,
+ workspaceSnapshots: [
+ { cwd: project, checkedAt: "2026-10-09T00:00:00Z", slashCommands: [], skills: [] },
+ ],
+ },
+ ]);
yield* Effect.all(
[
library.install({ source, skills: ["notes"], target }),
@@ -274,6 +283,7 @@ it.effect(
yield* fileSystem.readFileString(path.join(home, ".agents", ".skill-lock.json")),
) as { skills: Record };
expect(Object.keys(lock.skills).toSorted()).toEqual(["notes", "review"]);
+ expect(yield* Ref.get(refreshed)).toContain(`workspace:claude:${project}`);
}).pipe(Effect.provide(NodeServices.layer)),
),
120_000,
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index 2e08a83c117af..2b78b0b4a3633 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -208,16 +208,24 @@ const make = Effect.gen(function* () {
const refreshAgents = (target: SkillInstallTarget) =>
Effect.gen(function* () {
const providers = yield* enabledProviders;
+ // A project's skill list includes the global skills, so a global change
+ // rescans every project an agent has listed, not just its own folders.
+ const scans = providers.flatMap((provider) =>
+ target.kind === "environment"
+ ? (provider.workspaceSnapshots ?? []).map((snapshot) => ({
+ instanceId: provider.instanceId,
+ cwd: snapshot.cwd,
+ }))
+ : [{ instanceId: provider.instanceId, cwd: target.cwd }],
+ );
yield* Effect.forEach(
- providers,
- (provider) =>
- target.kind === "environment"
- ? providerRegistry.refreshInstance(provider.instanceId)
- : providerRegistry.refreshWorkspaceSnapshot({
- instanceId: provider.instanceId,
- cwd: target.cwd,
- fresh: true,
- }),
+ target.kind === "environment" ? providers : [],
+ (provider) => providerRegistry.refreshInstance(provider.instanceId),
+ { concurrency: "unbounded", discard: true },
+ );
+ yield* Effect.forEach(
+ scans,
+ (scan) => providerRegistry.refreshWorkspaceSnapshot({ ...scan, fresh: true }),
{ concurrency: "unbounded", discard: true },
);
});
diff --git a/packages/shared/src/agentTools.test.ts b/packages/shared/src/agentTools.test.ts
index c82b5af448e30..592b2067788f8 100644
--- a/packages/shared/src/agentTools.test.ts
+++ b/packages/shared/src/agentTools.test.ts
@@ -110,6 +110,17 @@ describe("skill switches", () => {
});
});
+describe("skill switch names", () => {
+ it("switches a skill named __proto__ like any other", () => {
+ const settings = { ...DEFAULT_SERVER_SETTINGS, disabledSkills: [] } satisfies ServerSettings;
+ const next = applyServerSettingsPatch(
+ settings,
+ skillsDisabledPatch(settings, projectId, ["__proto__"], true),
+ );
+ expect(resolveProjectSettings(next, projectId).settings.disabledSkills).toEqual(["__proto__"]);
+ });
+});
+
describe("mcpServers patches", () => {
it("replaces one server at a time and removes it with null", () => {
const current = { ...DEFAULT_SERVER_SETTINGS, mcpServers: { linear, supabase } };
diff --git a/packages/shared/src/agentTools.ts b/packages/shared/src/agentTools.ts
index 5a863afd05852..b041b3362abf1 100644
--- a/packages/shared/src/agentTools.ts
+++ b/packages/shared/src/agentTools.ts
@@ -71,7 +71,11 @@ export function skillsDisabledPatch(
],
};
}
- const switches = { ...settings.projectSettingsOverrides[projectId]?.disabledSkills };
+ // Null-prototype, so a skill named like an Object property (`__proto__`) is a key like any other.
+ const switches: Record = Object.assign(
+ Object.create(null),
+ settings.projectSettingsOverrides[projectId]?.disabledSkills,
+ );
for (const name of names) {
// One switch per name, whatever its case.
for (const existing of Object.keys(switches)) {
From 58f6a829ee44807b2044085d20c4f625a2adf41a Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Fri, 9 Oct 2026 20:02:53 -0700
Subject: [PATCH 15/35] fix: scan one folder's agents in turn, and ignore
inherited server names
- After a skill change, agents that list the same folder rescan it one
after another: a fresh scan drops the others' snapshots of that folder,
and the registry discards a scan whose starting snapshot changed.
- mcpServerEnabledPatch reads only own keys, so `constructor` isn't taken
for an inherited server.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/skills/SkillLibrary.test.ts | 37 +++++++++++++++++----
apps/server/src/skills/SkillLibrary.ts | 30 +++++++++++------
packages/shared/src/agentTools.test.ts | 11 +++++-
packages/shared/src/agentTools.ts | 7 ++--
4 files changed, 66 insertions(+), 19 deletions(-)
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index ebec7741b3769..aac1b96891a96 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -84,13 +84,28 @@ const withLibrary = (
Ref.update(refreshed, (entries) => [...entries, entry]).pipe(
Effect.andThen(Ref.get(providers)),
);
+ // Folders being scanned right now: a second scan of one is an overlap.
+ const scanning = yield* Ref.make>([]);
+ const scan = (instanceId: string, cwd: string) =>
+ Ref.get(scanning).pipe(
+ Effect.tap((busy) => (busy.includes(cwd) ? record(`overlap:${cwd}`) : Effect.void)),
+ Effect.andThen(Ref.update(scanning, (busy) => [...busy, cwd])),
+ Effect.andThen(Effect.yieldNow),
+ Effect.andThen(record(`workspace:${instanceId}:${cwd}`)),
+ Effect.ensuring(
+ Ref.update(scanning, (busy) => {
+ const index = busy.indexOf(cwd);
+ return index === -1 ? busy : [...busy.slice(0, index), ...busy.slice(index + 1)];
+ }),
+ ),
+ );
const stub: Pick<
ProviderRegistry.ProviderRegistry["Service"],
"getProviders" | "refreshInstance" | "refreshWorkspaceSnapshot"
> = {
getProviders: Ref.get(providers),
refreshInstance: (instanceId) => record(`instance:${instanceId}`),
- refreshWorkspaceSnapshot: ({ instanceId, cwd }) => record(`workspace:${instanceId}:${cwd}`),
+ refreshWorkspaceSnapshot: ({ instanceId, cwd }) => scan(instanceId, cwd),
};
// SkillLibrary reads provider snapshots and asks for rescans, nothing else.
const registry = stub as ProviderRegistry.ProviderRegistry["Service"];
@@ -263,13 +278,19 @@ it.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const target = { kind: "environment" } as const;
- // Claude has listed this project's skills, which include the global ones.
+ // Two agents have listed this project's skills, which include the global ones.
+ const listed = {
+ workspaceSnapshots: [
+ { cwd: project, checkedAt: "2026-10-09T00:00:00Z", slashCommands: [], skills: [] },
+ ],
+ };
yield* Ref.set(providers, [
+ { ...claude, ...listed },
{
...claude,
- workspaceSnapshots: [
- { cwd: project, checkedAt: "2026-10-09T00:00:00Z", slashCommands: [], skills: [] },
- ],
+ ...listed,
+ driver: ProviderDriverKind.make("codex"),
+ instanceId: ProviderInstanceId.make("codex"),
},
]);
yield* Effect.all(
@@ -283,7 +304,11 @@ it.effect(
yield* fileSystem.readFileString(path.join(home, ".agents", ".skill-lock.json")),
) as { skills: Record };
expect(Object.keys(lock.skills).toSorted()).toEqual(["notes", "review"]);
- expect(yield* Ref.get(refreshed)).toContain(`workspace:claude:${project}`);
+ const refreshes = yield* Ref.get(refreshed);
+ expect(refreshes).toContain(`workspace:claude:${project}`);
+ expect(refreshes).toContain(`workspace:codex:${project}`);
+ // A fresh scan drops other agents' snapshots of the folder, so they take turns.
+ expect(refreshes.filter((entry) => entry.startsWith("overlap:"))).toEqual([]);
}).pipe(Effect.provide(NodeServices.layer)),
),
120_000,
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index 2b78b0b4a3633..ed5268894fb7f 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -210,22 +210,32 @@ const make = Effect.gen(function* () {
const providers = yield* enabledProviders;
// A project's skill list includes the global skills, so a global change
// rescans every project an agent has listed, not just its own folders.
- const scans = providers.flatMap((provider) =>
- target.kind === "environment"
- ? (provider.workspaceSnapshots ?? []).map((snapshot) => ({
- instanceId: provider.instanceId,
- cwd: snapshot.cwd,
- }))
- : [{ instanceId: provider.instanceId, cwd: target.cwd }],
- );
+ const scansByCwd = new Map>();
+ for (const provider of providers) {
+ const cwds =
+ target.kind === "environment"
+ ? (provider.workspaceSnapshots ?? []).map((snapshot) => snapshot.cwd)
+ : [target.cwd];
+ for (const cwd of cwds)
+ scansByCwd.set(cwd, [...(scansByCwd.get(cwd) ?? []), provider.instanceId]);
+ }
yield* Effect.forEach(
target.kind === "environment" ? providers : [],
(provider) => providerRegistry.refreshInstance(provider.instanceId),
{ concurrency: "unbounded", discard: true },
);
+ // A fresh scan drops the other agents' snapshots of its folder, and a
+ // scan whose starting snapshot changed is discarded, so one folder's
+ // agents scan one after another. Different folders scan in parallel.
yield* Effect.forEach(
- scans,
- (scan) => providerRegistry.refreshWorkspaceSnapshot({ ...scan, fresh: true }),
+ scansByCwd,
+ ([cwd, instanceIds]) =>
+ Effect.forEach(
+ instanceIds,
+ (instanceId) =>
+ providerRegistry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh: true }),
+ { discard: true },
+ ),
{ concurrency: "unbounded", discard: true },
);
});
diff --git a/packages/shared/src/agentTools.test.ts b/packages/shared/src/agentTools.test.ts
index 592b2067788f8..6c92ead66e1ef 100644
--- a/packages/shared/src/agentTools.test.ts
+++ b/packages/shared/src/agentTools.test.ts
@@ -10,7 +10,7 @@ import {
import * as Schema from "effect/Schema";
import { describe, expect, it } from "vite-plus/test";
-import { skillsDisabledPatch } from "./agentTools.ts";
+import { mcpServerEnabledPatch, skillsDisabledPatch } from "./agentTools.ts";
import { resolveProjectSettings } from "./projectSettings.ts";
import { applyServerSettingsPatch } from "./serverSettings.ts";
@@ -121,6 +121,15 @@ describe("skill switch names", () => {
});
});
+describe("server switch names", () => {
+ it("refuses a server the settings only inherit from Object", () => {
+ expect(
+ mcpServerEnabledPatch(DEFAULT_SERVER_SETTINGS, projectId, "constructor", false),
+ ).toBeNull();
+ expect(mcpServerEnabledPatch(DEFAULT_SERVER_SETTINGS, null, "constructor", false)).toBeNull();
+ });
+});
+
describe("mcpServers patches", () => {
it("replaces one server at a time and removes it with null", () => {
const current = { ...DEFAULT_SERVER_SETTINGS, mcpServers: { linear, supabase } };
diff --git a/packages/shared/src/agentTools.ts b/packages/shared/src/agentTools.ts
index b041b3362abf1..a707f1c9d2973 100644
--- a/packages/shared/src/agentTools.ts
+++ b/packages/shared/src/agentTools.ts
@@ -101,14 +101,17 @@ export function mcpServerEnabledPatch(
name: string,
enabled: boolean,
): ServerSettingsPatch | null {
- const inherited = settings.mcpServers[name];
+ // Own keys only: `constructor` must not read as a server the object inherits.
+ const inherited = Object.hasOwn(settings.mcpServers, name)
+ ? settings.mcpServers[name]
+ : undefined;
if (projectId === null) {
return inherited ? { mcpServers: { [name]: { ...inherited, enabled } } } : null;
}
const entries: Record = {
...settings.projectSettingsOverrides[projectId]?.mcpServers,
};
- const own = entries[name];
+ const own = Object.hasOwn(entries, name) ? entries[name] : undefined;
if (own?.transport !== undefined) {
entries[name] = { ...own, enabled };
} else if (inherited === undefined) {
From bd9994d354561199ffcfd52c5d457ed24439f719 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 20:16:49 -0700
Subject: [PATCH 16/35] feat(web): Skills list and skill page in the style of
#17513
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Ports the Skills UI from n0mahd's skills series (#17513) onto the Tools page:
- dense one-line rows, sections with counts and a hint ('This project · 2
· Lives in this repo'), ✦ when every agent loads a skill;
- installed packs as collapsible 'From owner/repo' groups with one switch
and the first three skills shown;
- a Needs attention filter (conflicts, and project or global skills an
enabled agent doesn't load);
- a skill page replacing the View files dialog: Used by chips, the source,
Includes scripts with the script files, Copy path, Update and Remove, a
file tree with script labels, SKILL.md rendered or as source, each copy
of a conflicting name, and Escape back to the list.
The server marks each file as a script, so the list and the tree agree.
After an install, one agent rescans a project fresh and the rest follow
without dropping its result, so every agent's list shows the new skill.
Co-Authored-By: n0mahd <39080654+n0mahd@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/skills/SkillLibrary.test.ts | 26 +-
apps/server/src/skills/SkillLibrary.ts | 15 +-
.../src/components/settings/SkillAgents.tsx | 61 +++
.../src/components/settings/SkillDetail.tsx | 252 ++++++++++
.../src/components/settings/SkillFiles.tsx | 193 +++++++
.../components/settings/SkillFilesDialog.tsx | 95 ----
.../web/src/components/settings/SkillList.tsx | 238 +++++++++
.../src/components/settings/ToolsSettings.tsx | 470 ++++++++----------
.../settings/toolsSettings.logic.test.ts | 53 ++
.../settings/toolsSettings.logic.ts | 159 +++++-
apps/web/src/hooks/useAfterDelay.ts | 18 +
packages/contracts/src/skills.ts | 2 +
12 files changed, 1196 insertions(+), 386 deletions(-)
create mode 100644 apps/web/src/components/settings/SkillAgents.tsx
create mode 100644 apps/web/src/components/settings/SkillDetail.tsx
create mode 100644 apps/web/src/components/settings/SkillFiles.tsx
delete mode 100644 apps/web/src/components/settings/SkillFilesDialog.tsx
create mode 100644 apps/web/src/components/settings/SkillList.tsx
create mode 100644 apps/web/src/hooks/useAfterDelay.ts
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index aac1b96891a96..5d6b8f91607b2 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -105,7 +105,10 @@ const withLibrary = (
> = {
getProviders: Ref.get(providers),
refreshInstance: (instanceId) => record(`instance:${instanceId}`),
- refreshWorkspaceSnapshot: ({ instanceId, cwd }) => scan(instanceId, cwd),
+ refreshWorkspaceSnapshot: ({ instanceId, cwd, fresh }) =>
+ record(`fresh:${instanceId}:${cwd}:${fresh === true}`).pipe(
+ Effect.andThen(scan(instanceId, cwd)),
+ ),
};
// SkillLibrary reads provider snapshots and asks for rescans, nothing else.
const registry = stub as ProviderRegistry.ProviderRegistry["Service"];
@@ -158,10 +161,10 @@ it.effect(
],
);
assert.deepEqual(
- preview.skills[1]?.files.map((file) => [file.path, file.executable]),
+ preview.skills[1]?.files.map((file) => [file.path, file.executable, file.script]),
[
- ["SKILL.md", false],
- ["bin/run", true],
+ ["SKILL.md", false, false],
+ ["bin/run", true, true],
],
);
assert.isFalse(yield* fileSystem.exists(`${home}/.agents`));
@@ -187,7 +190,10 @@ it.effect(
const claudeLink = path.join(project, ".claude", "skills", "review", "SKILL.md");
assert.isTrue(yield* fileSystem.exists(claudeLink));
assert.isFalse(yield* fileSystem.exists(path.join(project, ".agents/skills/notes")));
- assert.deepEqual(yield* Ref.get(refreshed), [`workspace:claude:${project}`]);
+ assert.deepEqual(
+ (yield* Ref.get(refreshed)).filter((entry) => entry.startsWith("workspace:")),
+ [`workspace:claude:${project}`],
+ );
yield* Ref.set(providers, [
{
@@ -307,8 +313,16 @@ it.effect(
const refreshes = yield* Ref.get(refreshed);
expect(refreshes).toContain(`workspace:claude:${project}`);
expect(refreshes).toContain(`workspace:codex:${project}`);
- // A fresh scan drops other agents' snapshots of the folder, so they take turns.
+ // A fresh scan drops other agents' snapshots of the folder, so they take turns,
+ // and only the first is fresh: a later one would drop the first one's result.
expect(refreshes.filter((entry) => entry.startsWith("overlap:"))).toEqual([]);
+ // Each of the two installs rescans the project once, Claude fresh and Codex after it.
+ expect(refreshes.filter((entry) => entry.startsWith("fresh:"))).toEqual([
+ `fresh:claude:${project}:true`,
+ `fresh:codex:${project}:false`,
+ `fresh:claude:${project}:true`,
+ `fresh:codex:${project}:false`,
+ ]);
}).pipe(Effect.provide(NodeServices.layer)),
),
120_000,
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index ed5268894fb7f..96355cbad6c6f 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -224,7 +224,9 @@ const make = Effect.gen(function* () {
(provider) => providerRegistry.refreshInstance(provider.instanceId),
{ concurrency: "unbounded", discard: true },
);
- // A fresh scan drops the other agents' snapshots of its folder, and a
+ // A fresh scan drops every other agent's snapshot of its folder. So one
+ // agent scans fresh, which drops the rest's stale lists (and clears its
+ // own caches), then the others rescan without dropping it in turn. A
// scan whose starting snapshot changed is discarded, so one folder's
// agents scan one after another. Different folders scan in parallel.
yield* Effect.forEach(
@@ -232,8 +234,8 @@ const make = Effect.gen(function* () {
([cwd, instanceIds]) =>
Effect.forEach(
instanceIds,
- (instanceId) =>
- providerRegistry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh: true }),
+ (instanceId, index) =>
+ providerRegistry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh: index === 0 }),
{ discard: true },
),
{ concurrency: "unbounded", discard: true },
@@ -270,18 +272,19 @@ const make = Effect.gen(function* () {
}
if (!link && info?.type !== "File") continue;
if (files.length >= MAX_FILES) return { files, truncated: true };
+ const executable = info !== undefined && (info.mode & 0o111) !== 0;
files.push({
path: childPath,
size: info === undefined ? 0 : Number(info.size),
- executable: info !== undefined && (info.mode & 0o111) !== 0,
+ executable,
+ script: executable || childPath.startsWith("bin/") || SCRIPT_EXTENSION.test(childPath),
});
}
}
return { files, truncated };
});
- const hasScripts = (files: ReadonlyArray) =>
- files.some((file) => file.executable || SCRIPT_EXTENSION.test(file.path));
+ const hasScripts = (files: ReadonlyArray) => files.some((file) => file.script);
const sha256 = (text: string) =>
crypto.digest("SHA-256", new TextEncoder().encode(text)).pipe(
diff --git a/apps/web/src/components/settings/SkillAgents.tsx b/apps/web/src/components/settings/SkillAgents.tsx
new file mode 100644
index 0000000000000..1258e9b59ebea
--- /dev/null
+++ b/apps/web/src/components/settings/SkillAgents.tsx
@@ -0,0 +1,61 @@
+import { SparklesIcon } from "lucide-react";
+
+import { shouldShowInstanceBadge } from "../../providerInstances";
+import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { availabilityNote, type SkillAgent, type SkillAvailability } from "./toolsSettings.logic";
+
+/** An agent's icon. Instances that share a driver carry a badge, so they can be told apart. */
+export function SkillAgentIcon({
+ agent,
+ agents,
+ active = true,
+}: {
+ agent: SkillAgent;
+ /** Every agent on the page, to know whether this one shares its driver with another. */
+ agents: ReadonlyArray;
+ active?: boolean;
+}) {
+ return (
+
+
+
+ );
+}
+
+/**
+ * Who loads a skill: one mark when every enabled agent does, otherwise the
+ * agents that do. A tight run of icons, so a row stays on one line.
+ */
+export function SkillAgents({
+ value,
+ agents,
+}: {
+ value: SkillAvailability;
+ agents: ReadonlyArray;
+}) {
+ const label = availabilityNote(value);
+ if (!value.everyone && value.agents.length === 0) return null;
+ return (
+
+ }
+ >
+ {value.everyone ? (
+
+ ) : (
+ value.agents.map((agent) => (
+
+ ))
+ )}
+
+ {label}
+
+ );
+}
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
new file mode 100644
index 0000000000000..a923b80c69636
--- /dev/null
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -0,0 +1,252 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { AlertTriangleIcon, ArrowLeftIcon, MoreHorizontalIcon } from "lucide-react";
+import { lazy, Suspense, useEffect, useEffectEvent, useState } from "react";
+
+import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
+import { Skeleton } from "../ui/skeleton";
+import { toastManager } from "../ui/toast";
+import { Toggle, ToggleGroup } from "../ui/toggle-group";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { SkillAgentIcon } from "./SkillAgents";
+import {
+ skillAttention,
+ type SkillAgent,
+ type SkillRow,
+ type SkillRowDetails,
+} from "./toolsSettings.logic";
+
+// The tree and the viewer pull in the file-tree and highlighter code.
+const SkillFiles = lazy(() => import("./SkillFiles"));
+
+/**
+ * Escape goes from a skill back to the list. Settings leaves the page on
+ * Escape from its own window listener, so this one runs first, in the capture
+ * phase. Escape inside a field, dialog or menu belongs to that control.
+ */
+function useEscapeToList(onBack: () => void) {
+ const goBack = useEffectEvent((event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.defaultPrevented || event.repeat || event.isComposing)
+ return;
+ if (
+ event.target instanceof Element &&
+ event.target.closest(
+ 'input,textarea,select,[contenteditable],[role="dialog"],[role="alertdialog"],[role="menu"]',
+ )
+ )
+ return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ onBack();
+ });
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => goBack(event);
+ window.addEventListener("keydown", onKeyDown, { capture: true });
+ return () => window.removeEventListener("keydown", onKeyDown, { capture: true });
+ }, []);
+}
+
+/**
+ * One skill: what it says, which agents load it, and its files. Adapted from
+ * the skill page in #17513.
+ */
+export function SkillDetail({
+ row,
+ details,
+ agents,
+ groupLabel,
+ environmentId,
+ onBack,
+ onUpdate,
+ onRemove,
+}: {
+ row: SkillRow;
+ details: SkillRowDetails;
+ agents: ReadonlyArray;
+ /** The list section the skill came from, for the breadcrumb. */
+ groupLabel: string;
+ environmentId: EnvironmentId;
+ onBack: () => void;
+ onUpdate: (() => void) | null;
+ onRemove: (() => void) | null;
+}) {
+ useEscapeToList(onBack);
+ const loads = new Set(row.providers.map((provider) => provider.instanceId));
+ const warning = skillAttention(row, details, agents);
+ // A name can be several folders (a conflict, or a project copy over a global one).
+ const [folderPath, setFolderPath] = useState(details.folder?.folder ?? null);
+ const folder =
+ details.copies.find((copy) => copy.folder === folderPath) ?? details.folder ?? null;
+ const scripts = folder?.files.filter((file) => file.script).map((file) => file.path) ?? [];
+
+ const copyPath = (path: string) => {
+ void writeTextToClipboard(path, "skill path").then(
+ (copied) => {
+ if (copied) toastManager.add({ type: "success", title: "Path copied", description: path });
+ },
+ (error: unknown) => {
+ toastManager.add({
+ type: "error",
+ title: "Failed to copy path",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ });
+ },
+ );
+ };
+
+ return (
+
+
+
+
+ Back
+ Skills
+
+ / {groupLabel}
+
+
+
+
{row.name}
+
+ {row.description || "No description yet."}
+
+
+
+ Used by
+ {agents.length === 0 ? (
+ No agents are enabled.
+ ) : null}
+ {agents.map((agent) => {
+ const on = loads.has(agent.instanceId);
+ return (
+
+
+ }
+ >
+
+ {agent.displayName}
+
+
+ {on
+ ? `${agent.displayName} loads this skill.`
+ : `${agent.displayName} doesn't load this skill.`}
+
+
+ );
+ })}
+
+ {folder !== null || onUpdate !== null || onRemove !== null ? (
+
+ }
+ >
+
+
+
+ {folder !== null ? (
+ copyPath(folder.folder)}>Copy path
+ ) : null}
+ {onUpdate !== null ? Update : null}
+ {onRemove !== null ? (
+
+ Remove
+
+ ) : null}
+
+
+ ) : null}
+
+ {warning !== null || scripts.length > 0 || details.installed !== null ? (
+
+ {details.installed !== null ? (
+
+ From {details.installed.source}
+
+ ) : null}
+ {warning !== null ? (
+
{warning.detail}
+ ) : null}
+ {scripts.length > 0 ? (
+
+
+ }
+ >
+
+ Includes scripts
+
+
+ {scripts.slice(0, 8).join(", ")}
+ {scripts.length > 8 ? ` and ${scripts.length - 8} more` : ""}
+
+
+ ) : null}
+
+ ) : null}
+
+
+
+ {folder !== null ? (
+
+ {details.copies.length > 1 ? (
+ {
+ if (next[0] !== undefined) setFolderPath(next[0]);
+ }}
+ >
+ {details.copies.map((copy, index) => (
+
+ Copy {index + 1}
+
+ ))}
+
+ ) : null}
+
+ {folder.folder}
+
+
+ ) : null}
+ {folder === null ? (
+
+ This agent doesn't say where the skill's files are, so they can't be shown.
+
+ ) : (
+
+
+
+
+ }
+ >
+
+
+ )}
+ {folder?.filesTruncated ? (
+
+ Only some of this skill's files are shown.
+
+ ) : null}
+
+
+ );
+}
diff --git a/apps/web/src/components/settings/SkillFiles.tsx b/apps/web/src/components/settings/SkillFiles.tsx
new file mode 100644
index 0000000000000..09860d98d7b18
--- /dev/null
+++ b/apps/web/src/components/settings/SkillFiles.tsx
@@ -0,0 +1,193 @@
+import { FileTree, useFileTree } from "@pierre/trees/react";
+import type { EnvironmentId, SkillFileEntry } from "@t3tools/contracts";
+import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";
+import { useMemo, useState } from "react";
+import ReactMarkdown, { type Components } from "react-markdown";
+
+import { useTheme } from "../../hooks/useTheme";
+import { T3_PIERRE_ICONS } from "../../pierre-icons";
+import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "../../pierre-tree-theme";
+import { useProjectFileQuery } from "../files/projectFilesQueryState";
+import ReadOnlySourcePreview from "../files/ReadOnlySourcePreview";
+import { Button } from "../ui/button";
+import { compareSkillFiles, skillBody } from "./toolsSettings.logic";
+
+const SKILL_FILE = "SKILL.md";
+/** The tree and the viewer share one height, so the page doesn't jump between files. */
+const PANE_HEIGHT = "h-[26rem]";
+
+/**
+ * A skill's files as a tree beside a read-only viewer. Loaded when a skill
+ * opens, since the tree and the highlighter are large. Adapted from the
+ * skills page in #17513.
+ */
+export default function SkillFiles({
+ environmentId,
+ folder,
+ files,
+}: {
+ environmentId: EnvironmentId;
+ /** The skill's folder after following links. */
+ folder: string;
+ files: ReadonlyArray;
+}) {
+ const { resolvedTheme } = useTheme();
+ const fileSet = useMemo(() => new Set(files.map((file) => file.path)), [files]);
+ const scripts = useMemo(
+ () => new Set(files.filter((file) => file.script).map((file) => file.path)),
+ [files],
+ );
+ const [current, setCurrent] = useState(
+ fileSet.has(SKILL_FILE) ? SKILL_FILE : (files[0]?.path ?? ""),
+ );
+ const [treeOpen, setTreeOpen] = useState(false);
+ const { model } = useFileTree({
+ paths: [...fileSet],
+ sort: compareSkillFiles,
+ density: "compact",
+ flattenEmptyDirectories: true,
+ initialExpansion: "open",
+ initialSelectedPaths: current ? [current] : [],
+ icons: T3_PIERRE_ICONS,
+ // Files an agent could run say so, matching "Includes scripts" above.
+ renderRowDecoration: ({ item }) =>
+ scripts.has(item.path) ? { text: "script", title: "Agents can run this" } : null,
+ search: false,
+ unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
+ onSelectionChange: (selected) => {
+ const path = selected.at(-1);
+ // Folders end in a slash; only files open.
+ if (path !== undefined && fileSet.has(path)) {
+ setCurrent(path);
+ setTreeOpen(false);
+ }
+ },
+ });
+
+ return (
+
+
+
+ setTreeOpen(!treeOpen)}
+ >
+ {treeOpen ? : }
+ Files ({files.length}) · {current}
+
+
+
+
+
+
+
+
+ );
+}
+
+/** One file, read when it is picked. SKILL.md also renders as text. */
+function FilePane({
+ environmentId,
+ folder,
+ path,
+}: {
+ environmentId: EnvironmentId;
+ folder: string;
+ path: string;
+}) {
+ const file = useProjectFileQuery(environmentId, folder, path === "" ? null : path);
+ const [source, setSource] = useState(false);
+ const isSkillFile = path === SKILL_FILE;
+ return (
+
+
+ {path}
+
+ {isSkillFile ? (
+ <>
+ setSource(false)}
+ >
+ Preview
+
+ setSource(true)}
+ >
+ Source
+
+ >
+ ) : (
+ Read-only
+ )}
+
+
+ {file.data !== null ? (
+ <>
+ {file.data.truncated ? (
+
+ This file is large, so only the start is shown.
+
+ ) : null}
+ {isSkillFile && !source ? (
+
+
+ {skillBody(file.data.contents)}
+
+
+ ) : (
+
+ )}
+ >
+ ) : file.isPending ? (
+
+ Loading {path}…
+
+ ) : (
+
+ {file.readError?.failure === "binary_file"
+ ? "This file isn't text."
+ : (file.error ?? "This file can't be previewed here.")}
+
+ )}
+
+
+ );
+}
+
+/**
+ * SKILL.md's body as text. Code wraps at phone width. Links and images stay
+ * plain text, so reading a skill never opens a page or fetches anything.
+ */
+const SKILL_MARKDOWN_COMPONENTS = {
+ pre: ({ children }) => (
+ {children}
+ ),
+ code: ({ children }) => {children},
+ h1: ({ children }) => {children} ,
+ h2: ({ children }) => {children} ,
+ h3: ({ children }) => {children} ,
+ p: ({ children }) => {children}
,
+ ul: ({ children }) => ,
+ ol: ({ children }) => {children} ,
+ a: ({ children }) => {children} ,
+ img: ({ alt }) => {alt} ,
+} satisfies Components;
diff --git a/apps/web/src/components/settings/SkillFilesDialog.tsx b/apps/web/src/components/settings/SkillFilesDialog.tsx
deleted file mode 100644
index 38f111531012e..0000000000000
--- a/apps/web/src/components/settings/SkillFilesDialog.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import type { EnvironmentId, SkillFolderInfo } from "@t3tools/contracts";
-import { FileIcon, TriangleAlertIcon } from "lucide-react";
-import { useState } from "react";
-
-import { cn } from "~/lib/utils";
-import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
-import {
- FileSurfaceFailure,
- FileSurfaceLoading,
- FileSurfaceNotice,
-} from "../files/fileSurfaceChrome";
-import { useProjectFileQuery } from "../files/projectFilesQueryState";
-import { Badge } from "../ui/badge";
-import { Dialog, DialogHeader, DialogPopup, DialogTitle } from "../ui/dialog";
-
-/** A skill's files and one file's text, read-only, to check what a skill does. */
-export function SkillFilesDialog({
- open,
- onOpenChange,
- environmentId,
- name,
- folder,
-}: {
- readonly open: boolean;
- readonly onOpenChange: (open: boolean) => void;
- readonly environmentId: EnvironmentId;
- readonly name: string;
- readonly folder: SkillFolderInfo;
-}) {
- const [selected, setSelected] = useState("SKILL.md");
- const file = useProjectFileQuery(environmentId, folder.folder, selected, open);
-
- return (
-
-
-
-
-
- {name}
-
- {folder.scripts ? (
-
-
- Includes scripts
-
- ) : null}
-
- {folder.folder}
-
-
-
- {folder.files.map((entry) => (
-
- setSelected(entry.path)}
- >
-
- {entry.path}
- {entry.executable ? (
- script
- ) : null}
-
-
- ))}
- {folder.filesTruncated ? (
- More files not shown
- ) : null}
-
-
- {file.data?.truncated ? (
-
Showing the first 1 MB.
- ) : null}
- {file.data !== null ? (
-
-
-
- ) : file.readError?.failure === "binary_file" ? (
-
- ) : file.error !== null ? (
-
- ) : (
-
- )}
-
-
-
-
- );
-}
diff --git a/apps/web/src/components/settings/SkillList.tsx b/apps/web/src/components/settings/SkillList.tsx
new file mode 100644
index 0000000000000..8ddc6748b8fe9
--- /dev/null
+++ b/apps/web/src/components/settings/SkillList.tsx
@@ -0,0 +1,238 @@
+import { ChevronRightIcon } from "lucide-react";
+import { memo, useState, type MouseEvent } from "react";
+
+import { cn } from "../../lib/utils";
+import { GitHubIcon } from "../Icons";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { Switch } from "../ui/switch";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { SettingsGroup } from "./SettingsGroup";
+import { SkillAgents } from "./SkillAgents";
+import {
+ SOURCE_GROUP_PREVIEW,
+ skillAttention,
+ skillAvailability,
+ type SkillAgent,
+ type SkillRow,
+ type SkillRowDetails,
+} from "./toolsSettings.logic";
+
+/*
+ * The Skills list: dense one-line rows grouped by section and by the source a
+ * pack was installed from. Adapted from the skills list in #17513.
+ */
+
+/** Keeps a click on a control inside a clickable row from also opening the row. */
+const stopRowClick = (event: MouseEvent) => event.stopPropagation();
+
+export interface SkillListRow {
+ readonly row: SkillRow;
+ readonly details: SkillRowDetails;
+ /** The skill is off here, by this scope's settings. */
+ readonly disabled: boolean;
+ /** The project switch differs from the environment's. */
+ readonly overridden: boolean;
+}
+
+interface RowHandlers {
+ readonly agents: ReadonlyArray;
+ readonly canWrite: boolean;
+ readonly onToggle: (rows: ReadonlyArray, enabled: boolean) => void;
+ readonly onOpen: (name: string) => void;
+}
+
+const SkillListItem = memo(function SkillListItem({
+ item,
+ nested,
+ agents,
+ canWrite,
+ onToggle,
+ onOpen,
+}: RowHandlers & { item: SkillListRow; nested: boolean }) {
+ const { row, details, disabled, overridden } = item;
+ const lockedOff = row.disabledByProvider;
+ const warning = skillAttention(row, details, agents);
+ return (
+
+ onOpen(row.name)}
+ className={cn(
+ "flex cursor-pointer items-center gap-3 py-2 pr-3 hover:bg-muted/40 sm:pr-4",
+ nested ? "pl-9 sm:pl-10" : "pl-3 sm:pl-4",
+ )}
+ >
+
+
+ {row.name}
+
+
+ {lockedOff
+ ? "Turned off in the agent's own settings."
+ : row.description || "No description yet."}
+
+
+
+ {overridden ? (
+
+ This project
+
+ ) : null}
+ {warning?.kind === "conflict" ? (
+
+ }>
+
+ Conflict
+
+
+
+ {warning.detail}
+
+
+ ) : null}
+
+
+
+
+ onToggle([row], enabled)}
+ />
+
+
+
+
+
+ );
+});
+
+/** A pack's heading row and its skills: the first few, and a row that reveals the rest. */
+function SourceGroup({
+ source,
+ items,
+ ...handlers
+}: RowHandlers & { source: string; items: ReadonlyArray }) {
+ const [open, setOpen] = useState(true);
+ const [showAll, setShowAll] = useState(false);
+ const allOff = items.every((item) => item.disabled || item.row.disabledByProvider);
+ const shown = showAll ? items : items.slice(0, SOURCE_GROUP_PREVIEW);
+ const hidden = items.length - shown.length;
+ const github = /^[\w.-]+\/[\w.-]+$/.test(source) || source.includes("github.com");
+ return (
+ <>
+
+ setOpen((value) => !value)}
+ className="flex cursor-pointer items-center gap-2 px-3 py-2 hover:bg-muted/40 sm:px-4"
+ >
+
+
+ {github ? (
+
+ ) : null}
+ From {source}
+
+ {items.length}
+
+
+
+
+ handlers.onToggle(
+ items.map((item) => item.row),
+ enabled,
+ )
+ }
+ />
+
+ {/* The width of a row's chevron, so this switch sits over the rows' switches. */}
+
+
+
+ {open
+ ? shown.map((item) => (
+
+ ))
+ : null}
+ {open && items.length > SOURCE_GROUP_PREVIEW ? (
+
+ setShowAll((value) => !value)}>
+ {hidden > 0 ? `${hidden} more` : "Show fewer"}
+
+
+ ) : null}
+ >
+ );
+}
+
+/** One section: its name and count, then its packs and loose skills. */
+export function SkillListSection({
+ title,
+ hint,
+ total,
+ groups,
+ emptyText,
+ ...handlers
+}: RowHandlers & {
+ title: string;
+ /** A short muted phrase beside the name, in plain words. */
+ hint: string;
+ /** Every skill in the section before the search narrows it. */
+ total: number;
+ groups: ReadonlyArray<{
+ readonly source: string | null;
+ readonly rows: ReadonlyArray;
+ }>;
+ emptyText: string;
+}) {
+ return (
+
+
+
+ {title} · {total}
+
+ {hint}
+
+
+ {groups.length === 0 ? (
+ {emptyText}
+ ) : (
+
+ {groups.map(({ source, rows }) =>
+ source === null ? (
+ rows.map((item) => (
+
+ ))
+ ) : (
+
+ ),
+ )}
+
+ )}
+
+
+ );
+}
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index 01c5a85dc8884..41e1ade358d0e 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -8,7 +8,6 @@ import {
type ProjectId,
type ServerProvider,
type ServerSettingsPatch,
- type SkillFolderInfo,
type SkillInstallTarget,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
@@ -19,14 +18,14 @@ import {
skillsDisabledPatch,
} from "@t3tools/shared/agentTools";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
-import { MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
+import { MoreHorizontalIcon, PlusIcon, SearchIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useAfterDelay } from "../../hooks/useAfterDelay";
import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useEnvironmentsWithScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
-import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
import {
AlertDialog,
AlertDialogClose,
@@ -40,12 +39,16 @@ import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
+import { RefreshIcon } from "../ui/refresh-icon";
+import { Skeleton } from "../ui/skeleton";
import { Switch } from "../ui/switch";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { AddSkillsDialog } from "./AddSkillsDialog";
import { McpServerDialog } from "./McpServerDialog";
-import { SkillFilesDialog } from "./SkillFilesDialog";
+import { SettingsGroup } from "./SettingsGroup";
+import { SkillDetail } from "./SkillDetail";
+import { SkillListSection, type SkillListRow } from "./SkillList";
import { useSettingsScope } from "./SettingsScopeContext";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
@@ -55,10 +58,12 @@ import {
groupSkillRows,
listMcpServerRows,
type McpServerRow,
+ SKILL_GROUP_HINTS,
SKILL_GROUP_LABELS,
- skillReachesSomeProviders,
+ skillAgents,
+ skillAttention,
+ type SkillGroupKind,
type SkillRow,
- type SkillRowDetails,
skillRowDetails,
splitRowsBySource,
type ToolsTab,
@@ -66,6 +71,8 @@ import {
import { useScopedSettings, useScopedSettingsWriteAllowed } from "./useScopedSettings";
const EMPTY_PROVIDERS: ReadonlyArray = [];
+/** A scan that finishes sooner than this shows no placeholder at all. */
+const SKELETON_DELAY_MS = 150;
interface ToolsTarget {
readonly environmentId: EnvironmentId;
@@ -212,6 +219,9 @@ function SkillsPanel() {
reportFailure: false,
});
const [query, setQuery] = useState("");
+ const [onlyAttention, setOnlyAttention] = useState(false);
+ // The skill whose page is open in place of the list.
+ const [openName, setOpenName] = useState(null);
const [refreshing, setRefreshing] = useState(false);
const enabledProviders = useMemo(
() => providers.filter((provider) => provider.enabled),
@@ -231,10 +241,6 @@ function SkillsPanel() {
const updateSkill = useAtomCommand(serverEnvironment.updateSkill, { reportFailure: false });
const removeSkill = useAtomCommand(serverEnvironment.removeSkill, { reportFailure: false });
const [adding, setAdding] = useState(false);
- const [viewing, setViewing] = useState<{
- readonly name: string;
- readonly folder: SkillFolderInfo;
- } | null>(null);
const [removingSkill, setRemovingSkill] = useState<{
readonly name: string;
readonly target: SkillInstallTarget;
@@ -321,13 +327,36 @@ function SkillsPanel() {
}, [cwd, refresh, scanKey]);
const rows = useMemo(() => collectSkillRows(providers, cwd), [cwd, providers]);
- const groups = useMemo(() => groupSkillRows(filterSkillRows(rows, query)), [query, rows]);
+ const agents = useMemo(() => skillAgents(providers), [providers]);
const detailsByName = useMemo(
() => new Map(rows.map((row) => [row.name, skillRowDetails(row, foldersByPath)])),
[foldersByPath, rows],
);
const detailsOf = (row: SkillRow) =>
detailsByName.get(row.name) ?? skillRowDetails(row, foldersByPath);
+ const attentionNames = useMemo(
+ () =>
+ new Set(
+ rows
+ .filter((row) => {
+ const details = detailsByName.get(row.name);
+ return details !== undefined && skillAttention(row, details, agents) !== null;
+ })
+ .map((row) => row.name),
+ ),
+ [agents, detailsByName, rows],
+ );
+ const visibleRows = useMemo(
+ () =>
+ filterSkillRows(rows, query).filter((row) => !onlyAttention || attentionNames.has(row.name)),
+ [attentionNames, onlyAttention, query, rows],
+ );
+ const groups = useMemo(() => groupSkillRows(visibleRows), [visibleRows]);
+ const totals = useMemo(() => {
+ const counts = new Map();
+ for (const row of rows) counts.set(row.group, (counts.get(row.group) ?? 0) + 1);
+ return counts;
+ }, [rows]);
const setSkillsDisabled = (skillRows: ReadonlyArray, disabled: boolean) =>
persist(({ settings, projectId }) =>
@@ -338,152 +367,153 @@ function SkillsPanel() {
disabled,
),
);
- const setSkillDisabled = (name: string, disabled: boolean) => {
- const row = rows.find((candidate) => candidate.name === name);
- if (row !== undefined) setSkillsDisabled([row], disabled);
+ const projectOverrides = (name: string) =>
+ isProjectScope &&
+ targets.some(
+ (candidate) =>
+ candidate.projectId !== null &&
+ Object.hasOwn(
+ target?.settings.projectSettingsOverrides[candidate.projectId]?.disabledSkills ?? {},
+ name,
+ ),
+ );
+ const listItem = (row: SkillRow): SkillListRow => ({
+ row,
+ details: detailsOf(row),
+ disabled: isSkillDisabled(disabledSkills, row.name),
+ overridden: projectOverrides(row.name),
+ });
+ const updateOf = (row: SkillRow) => {
+ const installed = detailsOf(row).installed;
+ return installed === null || !canInstall
+ ? null
+ : () => void runSkillAction("update", { name: row.name, target: installed.target });
};
+ const removeOf = (row: SkillRow) => {
+ const installed = detailsOf(row).installed;
+ return installed === null || !canInstall
+ ? null
+ : () => setRemovingSkill({ name: row.name, target: installed.target });
+ };
+
+ const opened = openName === null ? null : (rows.find((row) => row.name === openName) ?? null);
+ const showSkeleton = useAfterDelay(rows.length === 0 && refreshing, SKELETON_DELAY_MS);
return (
<>
-
-
-
-
-
-
- setQuery(event.target.value)}
- aria-label="Filter skills"
- />
-
-
- void refresh(true)}
- />
- }
- >
-
-
- Rescan skill folders
-
- {installTarget !== null && canInstall ? (
-
setAdding(true)}>
-
- Add skills
-
- ) : null}
-
- {skillActionError !== null ? (
- {skillActionError}
- ) : null}
-
- {rows.length === 0 ? (
-
-
-
- ) : groups.length === 0 ? (
-
-
-
+ {opened !== null && environmentId !== null ? (
+ setOpenName(null)}
+ onUpdate={updateOf(opened)}
+ onRemove={removeOf(opened)}
+ />
) : (
- groups.map(({ group, rows: groupRows }) => (
-
- {splitRowsBySource(groupRows, (row) => detailsOf(row).installed?.source ?? null).map(
- ({ source, rows: sourceRows }) => {
- const renderRow = (row: SkillRow) => {
- const details = detailsOf(row);
- const { folder, installed } = details;
- return (
-
- candidate.projectId !== null &&
- Object.hasOwn(
- target?.settings.projectSettingsOverrides[candidate.projectId]
- ?.disabledSkills ?? {},
- row.name,
- ),
- )
- }
- showProviders={skillReachesSomeProviders(row, enabledProviders.length)}
- canWrite={canWrite}
- onChange={(enabled) => setSkillDisabled(row.name, !enabled)}
- onView={folder === null ? null : () => setViewing({ name: row.name, folder })}
- onUpdate={
- installed === null || !canInstall
- ? null
- : () =>
- void runSkillAction("update", {
- name: row.name,
- target: installed.target,
- })
- }
- onRemove={
- installed === null || !canInstall
- ? null
- : () => setRemovingSkill({ name: row.name, target: installed.target })
- }
- />
- );
- };
- if (source === null) return sourceRows.map(renderRow);
- const allOff = sourceRows.every((row) => isSkillDisabled(disabledSkills, row.name));
- return (
-
-
- From {source}
-
- }
- control={
- setSkillsDisabled(sourceRows, !enabled)}
- />
- }
+ <>
+
+
+
+
+
+
+ setQuery(event.target.value)}
+ aria-label="Search skills"
+ />
+
+ {rows.length > 0 ? (
+
setOnlyAttention((value) => !value)}
+ >
+ Needs attention ({attentionNames.size})
+
+ ) : null}
+
+ void refresh(true)}
/>
- {sourceRows.map(renderRow)}
-
- );
- },
- )}
+ }
+ >
+
+
+ Rescan skill folders
+
+ {installTarget !== null && canInstall ? (
+ setAdding(true)}>
+
+ Add skills
+
+ ) : null}
+
+ {skillActionError !== null ? (
+ {skillActionError}
+ ) : null}
- ))
+ {showSkeleton ? : null}
+ {rows.length === 0 && !refreshing ? (
+
+
+
+ ) : rows.length > 0 && groups.length === 0 ? (
+
+
+
+ ) : (
+ groups.map(({ group, rows: groupRows }) => (
+ item.details.installed?.source ?? null,
+ )}
+ emptyText="No matching skills."
+ agents={agents}
+ canWrite={canWrite}
+ onToggle={(skillRows, enabled) => setSkillsDisabled(skillRows, !enabled)}
+ onOpen={setOpenName}
+ />
+ ))
+ )}
+
+ Turning a skill off hides it from Claude, Codex and OpenCode, and from the composer's
+ skill menu. Other agents may still load it on their own. Changes apply to new sessions.
+
+ >
)}
-
- Turning a skill off hides it from Claude, Codex and OpenCode, and from the composer's skill
- menu. Other agents may still load it on their own. Changes apply to new sessions.
-
{adding && environmentId !== null && installTarget !== null ? (
) : null}
- {viewing !== null && environmentId !== null ? (
- {
- if (!open) setViewing(null);
- }}
- environmentId={environmentId}
- name={viewing.name}
- folder={viewing.folder}
- />
- ) : null}
!open && setRemovingSkill(null)}
@@ -522,7 +541,10 @@ function SkillsPanel() {
{
- if (removingSkill) void runSkillAction("remove", removingSkill);
+ if (removingSkill) {
+ void runSkillAction("remove", removingSkill);
+ if (removingSkill.name === openName) setOpenName(null);
+ }
setRemovingSkill(null);
}}
>
@@ -535,113 +557,27 @@ function SkillsPanel() {
);
}
-function SkillSettingsRow({
- row,
- details,
- disabled,
- overridden,
- showProviders,
- canWrite,
- onChange,
- onView,
- onUpdate,
- onRemove,
-}: {
- readonly row: SkillRow;
- readonly details: SkillRowDetails;
- readonly disabled: boolean;
- readonly overridden: boolean;
- readonly showProviders: boolean;
- readonly canWrite: boolean;
- readonly onChange: (enabled: boolean) => void;
- readonly onView: (() => void) | null;
- readonly onUpdate: (() => void) | null;
- readonly onRemove: (() => void) | null;
-}) {
- const lockedOff = row.disabledByProvider;
+/** Placeholder rows for a slow first scan, laid out like the sections they stand in for. */
+function SkillsSkeleton() {
return (
-
- {row.name}
- {overridden ? (
-
- This project
-
- ) : null}
- {details.conflict ? (
-
- }>
-
- Conflict
-
-
-
- Different skills share this name. The switch turns all of them on or off:
- {row.paths.map((path) => (
-
- {path}
-
- ))}
-
-
- ) : null}
-
- }
- description={
- lockedOff
- ? "Turned off in the agent's own settings."
- : (row.description ?? row.paths[0] ?? undefined)
- }
- className={disabled || lockedOff ? "[&_h3]:text-muted-foreground" : undefined}
- control={
- <>
- {showProviders ? (
-
- {row.providers.map((provider) => (
-
- }>
-
-
- {provider.displayName}
-
- ))}
-
- ) : null}
-
- {onView !== null || onUpdate !== null || onRemove !== null ? (
-
-
- }
- >
-
-
-
- {onView !== null ? View files : null}
- {onUpdate !== null ? Update : null}
- {onRemove !== null ? (
-
- Remove
-
- ) : null}
-
-
- ) : null}
- >
- }
- />
+
+
+
+
+
+
+ {[0, 1, 2, 3].map((row) => (
+
+
+
+
+
+
+
+ ))}
+
+
+
);
}
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index a8a31416237c3..45040dec8c60f 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -14,6 +14,10 @@ import {
parseArgs,
parseMcpServerJson,
formatArgs,
+ skillAgents,
+ skillAttention,
+ skillAvailability,
+ skillBody,
skillRowDetails,
splitRowsBySource,
type SkillRow,
@@ -152,6 +156,7 @@ describe("skill row details", () => {
it("knows nothing about a row whose folders weren't inspected", () => {
expect(skillRowDetails(row(["/x/SKILL.md"]), new Map())).toEqual({
folder: null,
+ copies: [],
scripts: false,
conflict: false,
installed: null,
@@ -178,6 +183,54 @@ describe("skill row details", () => {
});
});
+describe("skill availability and attention", () => {
+ const agents = skillAgents([
+ provider("claudeAgent", [], { displayName: "Claude" }),
+ provider("codex", [], { displayName: "Codex" }),
+ provider("cursor", [], { displayName: "Cursor", enabled: false }),
+ ]);
+ const ref = (instanceId: string) => ({
+ instanceId: ProviderInstanceId.make(instanceId),
+ driver: ProviderDriverKind.make(instanceId),
+ displayName: instanceId,
+ });
+ const row = (group: SkillRow["group"], providers: ReadonlyArray): SkillRow => ({
+ name: "review",
+ description: undefined,
+ group,
+ paths: [],
+ providers: providers.map(ref),
+ disabledByProvider: false,
+ });
+ const noDetails = skillRowDetails(row("personal", []), new Map());
+
+ it("counts only enabled agents, and says when every one loads a skill", () => {
+ expect(agents.map((agent) => agent.displayName)).toEqual(["Claude", "Codex"]);
+ expect(skillAvailability(row("personal", ["claudeAgent", "codex"]), agents).everyone).toBe(
+ true,
+ );
+ const partial = skillAvailability(row("personal", ["codex"]), agents);
+ expect([partial.everyone, partial.missing.map((agent) => agent.displayName)]).toEqual([
+ false,
+ ["Claude"],
+ ]);
+ });
+
+ it("flags a skill some agents miss, but not a plugin or built-in one", () => {
+ expect(skillAttention(row("personal", ["codex"]), noDetails, agents)?.detail).toBe(
+ "Not available to Claude.",
+ );
+ expect(skillAttention(row("plugin", ["codex"]), noDetails, agents)).toBeNull();
+ expect(skillAttention(row("system", ["codex"]), noDetails, agents)).toBeNull();
+ expect(skillAttention(row("project", ["claudeAgent", "codex"]), noDetails, agents)).toBeNull();
+ });
+
+ it("strips SKILL.md's header for the rendered view", () => {
+ expect(skillBody("---\nname: review\n---\n\n# Review\nBody")).toBe("# Review\nBody");
+ expect(skillBody("# No header")).toBe("# No header");
+ });
+});
+
describe("listMcpServerRows", () => {
const linear: McpServerConfig = {
enabled: true,
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 862f43fa63874..09312fa3269b5 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -25,12 +25,20 @@ export function validateToolsSearch(raw: Record): { tab?: Tools
export type SkillGroupKind = "project" | "personal" | "plugin" | "system";
export const SKILL_GROUP_LABELS: Readonly> = {
- project: "Repository",
- personal: "Personal",
+ project: "This project",
+ personal: "Global",
plugin: "Plugins",
system: "Built in",
};
+/** What each section means, beside its name. */
+export const SKILL_GROUP_HINTS: Readonly> = {
+ project: "Lives in this repo",
+ personal: "In all your projects",
+ plugin: "From the agents' plugins",
+ system: "Ships with the agent",
+};
+
export interface SkillProviderRef {
readonly instanceId: ProviderInstanceId;
readonly driver: ProviderDriverKind;
@@ -171,8 +179,10 @@ export function filterSkillRows(rows: ReadonlyArray, query: string) {
/** What the server knows about a row's folders: see `skills.inspect`. */
export interface SkillRowDetails {
- /** The first copy's folder, to view its files; null when no folder was inspected. */
+ /** The copy shown first: the installed one, else the first found; null when none was inspected. */
readonly folder: SkillFolderInfo | null;
+ /** Each distinct folder holding a skill of this name, the shown one first. */
+ readonly copies: ReadonlyArray;
/** Some copy holds a script an agent could run. */
readonly scripts: boolean;
/** Two copies of the name have different SKILL.md text. */
@@ -183,6 +193,7 @@ export interface SkillRowDetails {
const NO_DETAILS: SkillRowDetails = {
folder: null,
+ copies: [],
scripts: false,
conflict: false,
installed: null,
@@ -198,12 +209,16 @@ export function skillRowDetails(
});
if (infos.length === 0) return NO_DETAILS;
// Two agents reaching one folder through a link report two paths for one copy.
- const hashByFolder = new Map(infos.map((info) => [info.folder, info.hash]));
+ const byFolder = new Map(infos.map((info) => [info.folder, info]));
+ const copies = [...byFolder.values()].toSorted(
+ (left, right) => Number(right.installed !== undefined) - Number(left.installed !== undefined),
+ );
return {
- folder: infos[0] ?? null,
- scripts: infos.some((info) => info.scripts),
- conflict: new Set(hashByFolder.values()).size > 1,
- installed: infos.find((info) => info.installed !== undefined)?.installed ?? null,
+ folder: copies[0] ?? null,
+ copies,
+ scripts: copies.some((info) => info.scripts),
+ conflict: new Set(copies.map((info) => info.hash)).size > 1,
+ installed: copies.find((info) => info.installed !== undefined)?.installed ?? null,
};
}
@@ -212,7 +227,7 @@ export function skillRowDetails(
* so a pack of skills reads as one block with one switch. Rows with no
* recorded source come first, under no heading.
*/
-export function splitRowsBySource(
+export function splitRowsBySource(
rows: ReadonlyArray,
sourceOf: (row: Row) => string | null,
): ReadonlyArray<{ readonly source: string | null; readonly rows: ReadonlyArray }> {
@@ -230,9 +245,129 @@ export function splitRowsBySource(
.map(([source, sourceRows]) => ({ source, rows: sourceRows }));
}
-/** Whether `providers` covers only some of the enabled instances, so the row should name them. */
-export function skillReachesSomeProviders(row: SkillRow, enabledProviderCount: number): boolean {
- return row.providers.length < enabledProviderCount;
+/** An enabled agent on the page, as its icon and name show it. */
+export interface SkillAgent {
+ readonly instanceId: ProviderInstanceId;
+ readonly driverKind: ProviderDriverKind;
+ readonly displayName: string;
+ readonly accentColor?: string | undefined;
+}
+
+export function skillAgents(providers: ReadonlyArray): ReadonlyArray {
+ return providers
+ .filter((provider) => provider.enabled)
+ .map((provider) => ({
+ instanceId: provider.instanceId,
+ driverKind: provider.driver,
+ displayName: provider.displayName ?? provider.instanceId,
+ ...(provider.accentColor === undefined ? {} : { accentColor: provider.accentColor }),
+ }));
+}
+
+/** Which enabled agents load a skill, and which don't. */
+export interface SkillAvailability {
+ /** Every enabled agent loads it, so the row shows one mark instead of every icon. */
+ readonly everyone: boolean;
+ readonly agents: ReadonlyArray;
+ readonly missing: ReadonlyArray;
+}
+
+export function skillAvailability(
+ row: SkillRow,
+ agents: ReadonlyArray,
+): SkillAvailability {
+ const loads = new Set(row.providers.map((provider) => provider.instanceId));
+ const present = agents.filter((agent) => loads.has(agent.instanceId));
+ const missing = agents.filter((agent) => !loads.has(agent.instanceId));
+ return { everyone: agents.length > 0 && missing.length === 0, agents: present, missing };
+}
+
+const joinNames = (names: ReadonlyArray) =>
+ names.length <= 1
+ ? (names[0] ?? "")
+ : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
+
+export function availabilityNote(value: SkillAvailability): string {
+ return value.everyone
+ ? "Available to all your agents"
+ : value.agents.length === 0
+ ? "No enabled agent loads this skill"
+ : `Not available to ${joinNames(value.missing.map((agent) => agent.displayName))}`;
+}
+
+/**
+ * Why a skill needs a look, in one plain sentence, or null. Only a conflict
+ * marks the row itself; the rest show in the Needs attention filter and on
+ * the skill's page.
+ */
+export interface SkillAttention {
+ readonly kind: "conflict" | "missing";
+ readonly detail: string;
+}
+
+export function skillAttention(
+ row: SkillRow,
+ details: SkillRowDetails,
+ agents: ReadonlyArray,
+): SkillAttention | null {
+ if (details.conflict) {
+ return {
+ kind: "conflict",
+ detail: `Different skills are named “${row.name}”. Its switch turns all of them on or off.`,
+ };
+ }
+ // A plugin or built-in skill belongs to its agent; others never load it.
+ if (row.group !== "project" && row.group !== "personal") return null;
+ const availability = skillAvailability(row, agents);
+ if (availability.missing.length === 0) return null;
+ return {
+ kind: "missing",
+ detail: `Not available to ${joinNames(availability.missing.map((agent) => agent.displayName))}.`,
+ };
+}
+
+/** Rows with no recorded source show first; a pack collapses past this many rows. */
+export const SOURCE_GROUP_PREVIEW = 3;
+
+/** The tree's usual order (folders first, then names), with the root SKILL.md on top. */
+export function compareSkillFiles(
+ left: {
+ readonly path: string;
+ readonly isDirectory: boolean;
+ readonly segments: readonly string[];
+ },
+ right: {
+ readonly path: string;
+ readonly isDirectory: boolean;
+ readonly segments: readonly string[];
+ },
+): number {
+ const pinned = Number(right.path === "SKILL.md") - Number(left.path === "SKILL.md");
+ if (pinned !== 0) return pinned;
+ const shared = Math.min(left.segments.length, right.segments.length);
+ for (let depth = 0; depth < shared; depth += 1) {
+ const a = left.segments[depth] ?? "";
+ const b = right.segments[depth] ?? "";
+ if (a === b) continue;
+ const aFolder = depth < left.segments.length - 1 || left.isDirectory;
+ const bFolder = depth < right.segments.length - 1 || right.isDirectory;
+ if (aFolder !== bFolder) return aFolder ? -1 : 1;
+ return (
+ a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }) || (a < b ? -1 : 1)
+ );
+ }
+ return left.segments.length - right.segments.length;
+}
+
+const FRONTMATTER = /^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;
+
+/** SKILL.md without its header, for the rendered view. */
+export function skillBody(contents: string): string {
+ const match = FRONTMATTER.exec(contents);
+ return (match === null ? contents : contents.slice(match[0].length)).replace(
+ /^(?:[ \t]*\r?\n)*/,
+ "",
+ );
}
// ── MCP servers ────────────────────────────────────────────────────
diff --git a/apps/web/src/hooks/useAfterDelay.ts b/apps/web/src/hooks/useAfterDelay.ts
new file mode 100644
index 0000000000000..72d728801b1c1
--- /dev/null
+++ b/apps/web/src/hooks/useAfterDelay.ts
@@ -0,0 +1,18 @@
+import { useEffect, useState } from "react";
+
+/**
+ * True once `active` has stayed true for `delayMs`, and false again as soon as
+ * it stops, so a placeholder never flashes for a load that finishes quickly.
+ */
+export function useAfterDelay(active: boolean, delayMs: number) {
+ const [elapsed, setElapsed] = useState(false);
+ useEffect(() => {
+ if (!active) return;
+ const timer = setTimeout(() => setElapsed(true), delayMs);
+ return () => {
+ clearTimeout(timer);
+ setElapsed(false);
+ };
+ }, [active, delayMs]);
+ return active && elapsed;
+}
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
index 06912bca49d70..a622c9c22954b 100644
--- a/packages/contracts/src/skills.ts
+++ b/packages/contracts/src/skills.ts
@@ -39,6 +39,8 @@ export const SkillFileEntry = Schema.Struct({
path: Schema.String,
size: NonNegativeInt,
executable: Schema.Boolean,
+ /** A file an agent could run: executable, under `bin/`, or a script by its extension. */
+ script: Schema.Boolean,
});
export type SkillFileEntry = typeof SkillFileEntry.Type;
From b26a78de2363daaf591ff64f172f379ba48ac82a Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 20:23:49 -0700
Subject: [PATCH 17/35] fix(server): install and track skills by the skills
CLI's own name
The CLI matches --skill against a skill's SKILL.md name and keys its lock
files by it, but installs into that name sanitized as a folder (`Git
Review` -> `git-review`). Preview now returns the CLI's name with the
folder, and inspect, update and remove find a lock entry by either form.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/skills/SkillLibrary.test.ts | 45 ++++++++++--
apps/server/src/skills/SkillLibrary.ts | 72 +++++++++++++++----
.../components/settings/AddSkillsDialog.tsx | 2 +-
packages/contracts/src/skills.ts | 14 +++-
4 files changed, 111 insertions(+), 22 deletions(-)
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index 5d6b8f91607b2..d1fb02c35239a 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -77,6 +77,12 @@ const withLibrary = (
path.join(source, "notes", "SKILL.md"),
SKILL("notes", "Take notes."),
);
+ // A name that isn't a folder name: the CLI installs it into `git-review`.
+ yield* fileSystem.makeDirectory(path.join(source, "gitreview"), { recursive: true });
+ yield* fileSystem.writeFileString(
+ path.join(source, "gitreview", "SKILL.md"),
+ SKILL("Git Review", "Review with git."),
+ );
const providers = yield* Ref.make>([claude]);
const refreshed = yield* Ref.make>([]);
@@ -154,14 +160,20 @@ it.effect(
const fileSystem = yield* FileSystem.FileSystem;
const preview = yield* library.preview({ source });
assert.deepEqual(
- preview.skills.map((skill) => [skill.name, skill.description, skill.scripts]),
+ preview.skills.map((skill) => [
+ skill.name,
+ skill.folder,
+ skill.description,
+ skill.scripts,
+ ]),
[
- ["notes", "Take notes.", false],
- ["review", "Review a change.", true],
+ ["Git Review", "git-review", "Review with git.", false],
+ ["notes", "notes", "Take notes.", false],
+ ["review", "review", "Review a change.", true],
],
);
assert.deepEqual(
- preview.skills[1]?.files.map((file) => [file.path, file.executable, file.script]),
+ preview.skills[2]?.files.map((file) => [file.path, file.executable, file.script]),
[
["SKILL.md", false, false],
["bin/run", true, true],
@@ -328,6 +340,31 @@ it.effect(
120_000,
);
+it.effect(
+ "installs, updates and removes a skill whose name isn't its folder",
+ () =>
+ withLibrary(({ library, project, source }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const target = { kind: "project", cwd: project } as const;
+ const preview = yield* library.preview({ source });
+ const gitReview = preview.skills.find((skill) => skill.folder === "git-review");
+ assert.equal(gitReview?.name, "Git Review");
+ const installed = yield* library.install({ source, skills: ["Git Review"], target });
+ assert.deepEqual(installed.outcomes, [{ name: "Git Review", status: "installed" }]);
+ const folder = path.join(project, ".agents", "skills", "git-review");
+ assert.isTrue(yield* fileSystem.exists(folder));
+ // The list knows the skill by its folder; update and remove find the lock's name.
+ const updated = yield* library.update({ name: "git-review", target });
+ assert.deepEqual(updated.outcomes, [{ name: "Git Review", status: "installed" }]);
+ yield* library.remove({ name: "git-review", target });
+ assert.isFalse(yield* fileSystem.exists(folder));
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 180_000,
+);
+
describe("lockedInstallSource", () => {
it("updates one skill from its folder, as `npx skills update` does", () => {
const skillPath = "skills/productivity/grill-me/SKILL.md";
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index 96355cbad6c6f..5bc5ad581d16b 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -83,6 +83,34 @@ const decodeLock = Schema.decodeUnknownOption(
fromLenientJson(Schema.Struct({ skills: Schema.Record(Schema.String, LockEntry) })),
);
+/** The folder the CLI installs a skill into: its name lowercased, other characters as `-`. */
+function skillFolderName(name: string): string {
+ return (
+ name
+ .toLowerCase()
+ .replace(/[^a-z0-9._]+/g, "-")
+ .replace(/^[.-]+|[.-]+$/g, "")
+ .slice(0, 255) || "unnamed-skill"
+ );
+}
+
+/**
+ * A lock's entry for a skill folder. Locks key entries by the skill's own
+ * name (`Git Review`), which installs into its sanitized folder (`git-review`).
+ */
+function lockEntryFor(
+ lock: ReadonlyMap,
+ name: string,
+): { readonly key: string; readonly entry: LockEntry } | undefined {
+ const exact = lock.get(name);
+ if (exact !== undefined) return { key: name, entry: exact };
+ const folder = skillFolderName(name);
+ for (const [key, entry] of lock) {
+ if (skillFolderName(key) === folder) return { key, entry };
+ }
+ return undefined;
+}
+
const SCRIPT_EXTENSION = /\.(?:sh|bash|zsh|fish|ps1|bat|cmd|py|rb|pl|js|mjs|cjs|ts|mts|php)$/i;
/** Bounds on the walk of one skill folder, so a huge tree costs a fixed amount. */
const MAX_FILES = 500;
@@ -334,9 +362,12 @@ const make = Effect.gen(function* () {
const folder = yield* realPath(path.dirname(skillPath));
const name = path.basename(folder);
const install = installs.find(
- (candidate) => path.dirname(folder) === candidate.folder && candidate.lock.has(name),
+ (candidate) =>
+ path.dirname(folder) === candidate.folder &&
+ lockEntryFor(candidate.lock, name) !== undefined,
);
- const entry = install?.lock.get(name);
+ const entry =
+ install === undefined ? undefined : lockEntryFor(install.lock, name)?.entry;
const { files, truncated } = yield* listFiles(folder);
return {
path: skillPath,
@@ -402,18 +433,27 @@ const make = Effect.gen(function* () {
});
}
const folder = path.join(scratch, STANDARD_SKILL_FOLDER);
- const names = yield* fileSystem
+ const folders = yield* fileSystem
.readDirectory(folder)
.pipe(Effect.orElseSucceed((): string[] => []));
- const skills = yield* Effect.forEach(names.toSorted(), (name) =>
+ // The CLI's own name for each skill, which `--skill` matches, by the folder it chose.
+ const nameByFolder = new Map(
+ installed.flatMap((result) =>
+ result.name === undefined
+ ? []
+ : [[skillFolderName(result.name), result.name] as const],
+ ),
+ );
+ const skills = yield* Effect.forEach(folders.toSorted(), (skillFolder) =>
Effect.gen(function* () {
- const root = path.join(folder, name);
+ const root = path.join(folder, skillFolder);
const contents = yield* fileSystem
.readFileString(path.join(root, "SKILL.md"))
.pipe(Effect.orElseSucceed(() => ""));
const { files, truncated } = yield* listFiles(root);
return {
- name,
+ name: nameByFolder.get(skillFolder) ?? skillFolder,
+ folder: skillFolder,
description: describeSkill(contents),
files,
filesTruncated: truncated,
@@ -464,18 +504,19 @@ const make = Effect.gen(function* () {
},
);
+ /** The lock entry for a skill, by its CLI name or its folder, and the name the lock uses. */
const lockedEntry = (target: SkillInstallTarget, name: string) =>
readLock(targetPaths(target).lock).pipe(
Effect.flatMap((lock) => {
- const entry = lock.get(name);
- return entry === undefined
+ const found = lockEntryFor(lock, name);
+ return found === undefined
? Effect.fail(
new SkillLibraryError({
reason: "notInstalled",
message: "Only skills installed from a source can be updated or removed here.",
}),
)
- : Effect.succeed(entry);
+ : Effect.succeed(found);
}),
);
@@ -488,7 +529,7 @@ const make = Effect.gen(function* () {
const updateLocked = (target: SkillInstallTarget, name: string) =>
Effect.gen(function* () {
- const entry = yield* lockedEntry(target, name);
+ const { key, entry } = yield* lockedEntry(target, name);
const from = lockedInstallSource(entry, target.kind === "environment" ? "home" : "project");
if (from === null) {
return yield* new SkillLibraryError({
@@ -497,7 +538,8 @@ const make = Effect.gen(function* () {
"This skill's lock doesn't record which host it came from. Install it again from its URL.",
});
}
- return yield* installInto(target, from.source, [name], from.fullDepth);
+ // The CLI matches `--skill` against the skill's own name, which the lock keys by.
+ return yield* installInto(target, from.source, [key], from.fullDepth);
});
const remove: SkillLibrary["Service"]["remove"] = Effect.fn("SkillLibrary.remove")(
@@ -509,11 +551,11 @@ const make = Effect.gen(function* () {
const removeLocked = (target: SkillInstallTarget, name: string) =>
Effect.gen(function* () {
- yield* lockedEntry(target, name);
+ const { key } = yield* lockedEntry(target, name);
const paths = targetPaths(target);
yield* cli
.remove({
- skills: [name],
+ skills: [key],
global: target.kind === "environment",
cwd: paths.root,
})
@@ -525,9 +567,9 @@ const make = Effect.gen(function* () {
yield* refreshAgents(target);
// The CLI reports a skill it couldn't delete without failing, so check what's left.
const folderLeft = yield* fileSystem
- .exists(path.join(paths.folder, name))
+ .exists(path.join(paths.folder, skillFolderName(key)))
.pipe(Effect.orElseSucceed(() => false));
- const lockLeft = (yield* readLock(paths.lock)).has(name);
+ const lockLeft = (yield* readLock(paths.lock)).has(key);
if (folderLeft || lockLeft) {
return yield* cliFailed(
`Couldn't remove ${name}. Check the permissions of ${folderLeft ? paths.folder : paths.lock}.`,
diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx
index 01394b3b423c8..34b411720b0fa 100644
--- a/apps/web/src/components/settings/AddSkillsDialog.tsx
+++ b/apps/web/src/components/settings/AddSkillsDialog.tsx
@@ -173,7 +173,7 @@ export function AddSkillsDialog({
/>
- {skill.name}
+ {skill.folder}
{skill.scripts ? (
Includes scripts
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
index a622c9c22954b..fd76e9d4f1c5c 100644
--- a/packages/contracts/src/skills.ts
+++ b/packages/contracts/src/skills.ts
@@ -27,10 +27,17 @@ export const SkillSource = TrimmedNonEmptyString.check(
),
);
-/** A skill's folder name, the name agents invoke it by, as the CLI sanitizes it. */
+/**
+ * A skill as the `skills` CLI names it: the `name` in its SKILL.md, which the
+ * CLI matches `--skill` against and keys its lock files by. Its folder (and
+ * the name agents invoke it by) is that name sanitized, so `Git Review` lives
+ * in `git-review`. Either form identifies an installed skill.
+ */
export const InstalledSkillName = TrimmedNonEmptyString.check(
Schema.isMaxLength(255),
- Schema.isPattern(/^[a-z0-9._][a-z0-9._-]*$/),
+ Schema.makeFilter((name: string) =>
+ name.startsWith("-") ? "A skill name can't start with a dash." : true,
+ ),
);
export type InstalledSkillName = typeof InstalledSkillName.Type;
@@ -48,7 +55,10 @@ export const SkillPreviewInput = Schema.Struct({ source: SkillSource });
export type SkillPreviewInput = typeof SkillPreviewInput.Type;
export const SkillPreviewItem = Schema.Struct({
+ /** What to pass to install: the CLI's name for the skill. */
name: InstalledSkillName,
+ /** The folder it installs into, the name agents invoke it by. */
+ folder: TrimmedNonEmptyString,
description: Schema.String,
/** Up to a limit; `filesTruncated` says when some were left out. */
files: Schema.Array(SkillFileEntry),
From 742568839c75a9ac9a332dcca9ff45a72c696098 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 20:37:13 -0700
Subject: [PATCH 18/35] fix: cap a skill install at 200 skills, and read large
installer results whole
- The Add skills dialog ticks at most 200 skills, the most one install
takes, says so for a bigger source, and the agent tool shares the limit.
- The skills CLI prints its --json result and exits at once, so a result
over 64 KiB was cut short in the pipe and the preview failed. The
subcommand now exits only after stdout drains.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/cli/skillsCli.ts | 10 ++++++
apps/server/src/mcp/toolkits/tools/tools.ts | 3 +-
apps/server/src/skills/SkillLibrary.test.ts | 31 +++++++++++++++++++
.../components/settings/AddSkillsDialog.tsx | 21 +++++++++++--
packages/contracts/src/skills.ts | 8 ++++-
5 files changed, 69 insertions(+), 4 deletions(-)
diff --git a/apps/server/src/cli/skillsCli.ts b/apps/server/src/cli/skillsCli.ts
index 42f0f44922ae2..d003a6a0e3ed5 100644
--- a/apps/server/src/cli/skillsCli.ts
+++ b/apps/server/src/cli/skillsCli.ts
@@ -9,6 +9,16 @@ import { Argument, Command } from "effect/cli";
* of the server.
*/
export async function runSkillsCli(args: ReadonlyArray): Promise {
+ // The CLI prints its `--json` result and calls `process.exit` straight
+ // away. Writes to a pipe are asynchronous, so whatever hasn't flushed would
+ // be lost: a large result is cut at 64 KiB. Exit only once stdout drained.
+ const exit = process.exit.bind(process);
+ process.exit = ((code?: number | string | null) => {
+ process.exitCode = code ?? process.exitCode;
+ if (process.stdout.writableLength === 0) return exit(process.exitCode);
+ process.stdout.once("drain", () => exit(process.exitCode));
+ return undefined as never;
+ }) as typeof process.exit;
// The CLI reads its command from argv[2] onward.
process.argv = [process.argv[0] ?? "node", "skills", ...args];
await import("skills/dist/cli.mjs");
diff --git a/apps/server/src/mcp/toolkits/tools/tools.ts b/apps/server/src/mcp/toolkits/tools/tools.ts
index c39c26540a1c6..ffcef1d376bd9 100644
--- a/apps/server/src/mcp/toolkits/tools/tools.ts
+++ b/apps/server/src/mcp/toolkits/tools/tools.ts
@@ -3,6 +3,7 @@ import {
McpServerName,
OrchestratorMcpFailure,
ProjectId,
+ SkillInstallInput,
SkillInstallResult,
SkillSource,
TrimmedNonEmptyString,
@@ -80,7 +81,7 @@ const SkillsInstallTool = Tool.make("t3_skills_install", {
parameters: Schema.Struct({
...Scope,
source: SkillSource,
- skills: Schema.Array(InstalledSkillName).check(Schema.isMinLength(1)),
+ skills: SkillInstallInput.fields.skills,
}),
success: SkillInstallResult,
}).annotate(Tool.Destructive, true);
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index d1fb02c35239a..ec5736236cd6e 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -365,6 +365,37 @@ it.effect(
180_000,
);
+it.effect(
+ "previews a source whose result is larger than one pipe buffer",
+ () =>
+ withLibrary(({ library, home }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ // About 360 bytes of JSON per skill, so 250 skills is well past 64 KiB.
+ const big = path.join(home, "big");
+ yield* Effect.forEach(
+ Array.from({ length: 250 }, (_, index) => `skill-${String(index).padStart(3, "0")}`),
+ (name) =>
+ fileSystem
+ .makeDirectory(path.join(big, name), { recursive: true })
+ .pipe(
+ Effect.andThen(
+ fileSystem.writeFileString(
+ path.join(big, name, "SKILL.md"),
+ SKILL(name, `Skill ${name}.`),
+ ),
+ ),
+ ),
+ { discard: true },
+ );
+ const preview = yield* library.preview({ source: big });
+ assert.equal(preview.skills.length, 250);
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 180_000,
+);
+
describe("lockedInstallSource", () => {
it("updates one skill from its folder, as `npx skills update` does", () => {
const skillPath = "skills/productivity/grill-me/SKILL.md";
diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx
index 34b411720b0fa..f51e3b3f1f337 100644
--- a/apps/web/src/components/settings/AddSkillsDialog.tsx
+++ b/apps/web/src/components/settings/AddSkillsDialog.tsx
@@ -1,4 +1,9 @@
-import type { EnvironmentId, SkillInstallTarget, SkillPreviewItem } from "@t3tools/contracts";
+import {
+ type EnvironmentId,
+ MAX_SKILLS_PER_INSTALL,
+ type SkillInstallTarget,
+ type SkillPreviewItem,
+} from "@t3tools/contracts";
import { useId, useState } from "react";
import { serverEnvironment } from "../../state/server";
@@ -65,7 +70,10 @@ export function AddSkillsDialog({
return;
}
setFound({ source: trimmed, skills: result.value.skills });
- setSelected(new Set(result.value.skills.map((skill) => skill.name)));
+ // Everything is ticked, up to what one install takes.
+ setSelected(
+ new Set(result.value.skills.slice(0, MAX_SKILLS_PER_INSTALL).map((skill) => skill.name)),
+ );
};
const installSelected = async () => {
@@ -96,11 +104,13 @@ export function AddSkillsDialog({
const toggle = (name: string, checked: boolean) =>
setSelected((current) => {
+ if (checked && current.size >= MAX_SKILLS_PER_INSTALL) return current;
const next = new Set(current);
if (checked) next.add(name);
else next.delete(name);
return next;
});
+ const full = selected.size >= MAX_SKILLS_PER_INSTALL;
return (
toggle(skill.name, checked === true)}
/>
@@ -193,6 +204,12 @@ export function AddSkillsDialog({
))}
+ {found.skills.length > MAX_SKILLS_PER_INSTALL ? (
+
+ One install takes up to {MAX_SKILLS_PER_INSTALL} skills. Install the rest
+ afterwards.
+
+ ) : null}
Skills can tell agents to run their scripts. Install only sources you trust.
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
index fd76e9d4f1c5c..64e62bee23279 100644
--- a/packages/contracts/src/skills.ts
+++ b/packages/contracts/src/skills.ts
@@ -71,9 +71,15 @@ export type SkillPreviewItem = typeof SkillPreviewItem.Type;
export const SkillPreviewResult = Schema.Struct({ skills: Schema.Array(SkillPreviewItem) });
export type SkillPreviewResult = typeof SkillPreviewResult.Type;
+/** The most skills one install takes; a bigger pack installs in several goes. */
+export const MAX_SKILLS_PER_INSTALL = 200;
+
export const SkillInstallInput = Schema.Struct({
source: SkillSource,
- skills: Schema.Array(InstalledSkillName).check(Schema.isMinLength(1), Schema.isMaxLength(200)),
+ skills: Schema.Array(InstalledSkillName).check(
+ Schema.isMinLength(1),
+ Schema.isMaxLength(MAX_SKILLS_PER_INSTALL),
+ ),
target: SkillInstallTarget,
});
export type SkillInstallInput = typeof SkillInstallInput.Type;
From b0c21cbaad281014dec793763fbc4b5cf99b04be Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 20:45:33 -0700
Subject: [PATCH 19/35] fix(server): flush the skills installer's output by
making stdout blocking
Deferring process.exit until stdout drained let the CLI's code run on
past an exit it relied on: `add --list` returned into the install path.
A blocking stdout pipe writes everything before the next statement, so
process.exit stays immediate and nothing is cut.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/cli/skillsCli.ts | 17 ++++++++---------
1 file changed, 8 insertions(+), 9 deletions(-)
diff --git a/apps/server/src/cli/skillsCli.ts b/apps/server/src/cli/skillsCli.ts
index d003a6a0e3ed5..9ca9290579144 100644
--- a/apps/server/src/cli/skillsCli.ts
+++ b/apps/server/src/cli/skillsCli.ts
@@ -10,15 +10,14 @@ import { Argument, Command } from "effect/cli";
*/
export async function runSkillsCli(args: ReadonlyArray): Promise {
// The CLI prints its `--json` result and calls `process.exit` straight
- // away. Writes to a pipe are asynchronous, so whatever hasn't flushed would
- // be lost: a large result is cut at 64 KiB. Exit only once stdout drained.
- const exit = process.exit.bind(process);
- process.exit = ((code?: number | string | null) => {
- process.exitCode = code ?? process.exitCode;
- if (process.stdout.writableLength === 0) return exit(process.exitCode);
- process.stdout.once("drain", () => exit(process.exitCode));
- return undefined as never;
- }) as typeof process.exit;
+ // away. Writes to a pipe are asynchronous on POSIX, so whatever hasn't
+ // flushed would be lost: a large result is cut at 64 KiB. A blocking pipe
+ // finishes each write before the next statement, so exit loses nothing.
+ // (Windows pipes are already synchronous.)
+ const stdout = process.stdout as typeof process.stdout & {
+ readonly _handle?: { readonly setBlocking?: (blocking: boolean) => void };
+ };
+ stdout._handle?.setBlocking?.(true);
// The CLI reads its command from argv[2] onward.
process.argv = [process.argv[0] ?? "node", "skills", ...args];
await import("skills/dist/cli.mjs");
From 57d3b32a59968b8b8fedf06f62227cb8ef5acd04 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 21:18:41 -0700
Subject: [PATCH 20/35] fix(web): name an open skill in the settings header,
not above the page
The skill page drew its own Skills / section crumb under the scope picker.
The open skill now lives in the URL (?skill=), so the settings header reads
Settings / Tools / , with Tools leading back to the list.
Co-Authored-By: Claude Opus 5.5
---
.../settings/SettingsBreadcrumb.tsx | 26 +++++++++--
.../src/components/settings/SkillDetail.tsx | 21 ++-------
.../src/components/settings/ToolsSettings.tsx | 44 ++++++++++++++-----
.../settings/toolsSettings.logic.ts | 14 +++++-
apps/web/src/routes/settings.tools.tsx | 12 ++++-
5 files changed, 82 insertions(+), 35 deletions(-)
diff --git a/apps/web/src/components/settings/SettingsBreadcrumb.tsx b/apps/web/src/components/settings/SettingsBreadcrumb.tsx
index c4e019d6fcf7c..dd68e3ae92d16 100644
--- a/apps/web/src/components/settings/SettingsBreadcrumb.tsx
+++ b/apps/web/src/components/settings/SettingsBreadcrumb.tsx
@@ -1,3 +1,5 @@
+import { Link, useSearch } from "@tanstack/react-router";
+
import {
WorkspaceBreadcrumb,
WorkspaceBreadcrumbItem,
@@ -17,11 +19,14 @@ function settingsBreadcrumbLabel(pathname: string): string | null {
}
/**
- * `Settings / Section`. The scope a change applies to lives at the top of the
- * page content, see `SettingsScopeSentence`.
+ * `Settings / Section`, or `Settings / Tools / skill` on a skill's page, where
+ * Tools leads back to the list. The scope a change applies to lives at the top
+ * of the page content, see `SettingsScopeSentence`.
*/
export function SettingsBreadcrumb({ pathname }: { pathname: string }) {
const sectionLabel = settingsBreadcrumbLabel(pathname);
+ const skill = useSearch({ strict: false, select: (search) => search.skill });
+ const page = pathname === "/settings/tools" ? skill : undefined;
return (
@@ -31,8 +36,23 @@ export function SettingsBreadcrumb({ pathname }: { pathname: string }) {
>
) : null}
+ {page !== undefined && sectionLabel ? (
+ <>
+
+ {/* The settings route keeps the scope on a link without search. */}
+
+ {sectionLabel}
+
+
+
+ >
+ ) : null}
- {sectionLabel ?? "Settings"}
+ {page ?? sectionLabel ?? "Settings"}
);
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
index a923b80c69636..e9fe0b0cd0819 100644
--- a/apps/web/src/components/settings/SkillDetail.tsx
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -1,5 +1,5 @@
import type { EnvironmentId } from "@t3tools/contracts";
-import { AlertTriangleIcon, ArrowLeftIcon, MoreHorizontalIcon } from "lucide-react";
+import { AlertTriangleIcon, MoreHorizontalIcon } from "lucide-react";
import { lazy, Suspense, useEffect, useEffectEvent, useState } from "react";
import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
@@ -49,14 +49,14 @@ function useEscapeToList(onBack: () => void) {
}
/**
- * One skill: what it says, which agents load it, and its files. Adapted from
- * the skill page in #17513.
+ * One skill: what it says, which agents load it, and its files. The settings
+ * header names it and leads back to the list. Adapted from the skill page in
+ * #17513.
*/
export function SkillDetail({
row,
details,
agents,
- groupLabel,
environmentId,
onBack,
onUpdate,
@@ -65,8 +65,6 @@ export function SkillDetail({
row: SkillRow;
details: SkillRowDetails;
agents: ReadonlyArray;
- /** The list section the skill came from, for the breadcrumb. */
- groupLabel: string;
environmentId: EnvironmentId;
onBack: () => void;
onUpdate: (() => void) | null;
@@ -98,17 +96,6 @@ export function SkillDetail({
return (
-
-
-
- Back
- Skills
-
- / {groupLabel}
-
{row.name}
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index 41e1ade358d0e..71f696f227f9e 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -169,16 +169,18 @@ function usePersistToolsPatch() {
);
}
-/**
- * Replace one key of a project's override entry, dropping the key (or the entry) when empty.
- * The rest of the entry is resent as stored, since the patch replaces the whole entry.
- */
+/** Settings → Tools: the skills and MCP servers agents get, as two tabs. */
export function ToolsSettings({
tab = "skills",
+ skill,
onTabChange,
+ onOpenSkill,
}: {
readonly tab?: ToolsTab;
+ /** The skill whose page is open in place of the list; the header names it. */
+ readonly skill?: string;
readonly onTabChange: (tab: ToolsTab) => void;
+ readonly onOpenSkill: (name: string | null) => void;
}) {
const selectTab = onTabChange;
return (
@@ -197,14 +199,24 @@ export function ToolsSettings({
MCP servers
- {tab === "mcp" ?
:
}
+ {tab === "mcp" ? (
+
+ ) : (
+
+ )}
);
}
// ── Skills ───────────────────────────────────────────────────────────
-function SkillsPanel() {
+function SkillsPanel({
+ openName,
+ onOpen,
+}: {
+ openName: string | null;
+ onOpen: (name: string | null) => void;
+}) {
const { scope, target } = useSettingsScope();
const environmentId = target?.environmentId ?? null;
const targets = useToolsTargets();
@@ -220,8 +232,6 @@ function SkillsPanel() {
});
const [query, setQuery] = useState("");
const [onlyAttention, setOnlyAttention] = useState(false);
- // The skill whose page is open in place of the list.
- const [openName, setOpenName] = useState
(null);
const [refreshing, setRefreshing] = useState(false);
const enabledProviders = useMemo(
() => providers.filter((provider) => provider.enabled),
@@ -407,12 +417,22 @@ function SkillsPanel() {
row={opened}
details={detailsOf(opened)}
agents={agents}
- groupLabel={SKILL_GROUP_LABELS[opened.group]}
environmentId={environmentId}
- onBack={() => setOpenName(null)}
+ onBack={() => onOpen(null)}
onUpdate={updateOf(opened)}
onRemove={removeOf(opened)}
/>
+ ) : openName !== null ? (
+ // A link or Back to a skill that isn't here (yet, or any more).
+
+
+
) : (
<>
setSkillsDisabled(skillRows, !enabled)}
- onOpen={setOpenName}
+ onOpen={onOpen}
/>
))
)}
@@ -543,7 +563,7 @@ function SkillsPanel() {
onClick={() => {
if (removingSkill) {
void runSkillAction("remove", removingSkill);
- if (removingSkill.name === openName) setOpenName(null);
+ if (removingSkill.name === openName) onOpen(null);
}
setRemovingSkill(null);
}}
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 09312fa3269b5..0105c60d9f3c7 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -17,8 +17,18 @@ import {
export type ToolsTab = "skills" | "mcp";
-export function validateToolsSearch(raw: Record): { tab?: ToolsTab } {
- return raw.tab === "mcp" || raw.tab === "skills" ? { tab: raw.tab } : {};
+/** `tab` picks the tab; `skill` is the skill whose page is open on the Skills tab. */
+export function validateToolsSearch(raw: Record): {
+ tab?: ToolsTab;
+ skill?: string;
+} {
+ const tab = raw.tab === "mcp" || raw.tab === "skills" ? raw.tab : undefined;
+ const skill =
+ tab !== "mcp" && typeof raw.skill === "string" && raw.skill.length > 0 ? raw.skill : undefined;
+ return {
+ ...(tab === undefined ? {} : { tab }),
+ ...(skill === undefined ? {} : { skill }),
+ };
}
/** Where a skill lives, the groups the Skills tab shows in order. */
diff --git a/apps/web/src/routes/settings.tools.tsx b/apps/web/src/routes/settings.tools.tsx
index ddcf66562afd4..7654a6fc2a473 100644
--- a/apps/web/src/routes/settings.tools.tsx
+++ b/apps/web/src/routes/settings.tools.tsx
@@ -4,7 +4,7 @@ import { ToolsSettings } from "../components/settings/ToolsSettings";
import { validateToolsSearch } from "../components/settings/toolsSettings.logic";
function SettingsToolsRoute() {
- const { tab } = Route.useSearch();
+ const { tab, skill } = Route.useSearch();
const navigate = Route.useNavigate();
// A settings search result links by hash, so it opens the tab it points at.
const hash = useLocation({ select: (location) => location.hash });
@@ -12,6 +12,7 @@ function SettingsToolsRoute() {
return (
void navigate({
// The settings route keeps the scope; Skills is the default tab.
@@ -20,6 +21,15 @@ function SettingsToolsRoute() {
resetScroll: false,
})
}
+ // Like a tab, a skill's page replaces the entry: Escape from the list
+ // then still leaves Settings rather than reopening the skill.
+ onOpenSkill={(name) =>
+ void navigate({
+ search: name === null ? {} : { skill: name },
+ replace: true,
+ resetScroll: false,
+ })
+ }
/>
);
}
From efe7aa6a102865ca0e499eced5fd116048b95fea Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 21:28:27 -0700
Subject: [PATCH 21/35] fix(web): show project skills only for the project
picked, and line up pack rows
At All projects, Codex's own skill list (read in the folder T3 was launched
from) filled a This project section that belonged to no picked project.
Project skills now come only from a scan of the picked checkout.
Skills inside a From pack, and its N more row, now start where the
pack's name does instead of under its icon.
Co-Authored-By: Claude Opus 5.5
---
.../web/src/components/settings/SkillList.tsx | 22 ++--
.../settings/toolsSettings.logic.test.ts | 120 ++++++++++++------
.../settings/toolsSettings.logic.ts | 18 +--
3 files changed, 104 insertions(+), 56 deletions(-)
diff --git a/apps/web/src/components/settings/SkillList.tsx b/apps/web/src/components/settings/SkillList.tsx
index 8ddc6748b8fe9..bd7a454bb6df4 100644
--- a/apps/web/src/components/settings/SkillList.tsx
+++ b/apps/web/src/components/settings/SkillList.tsx
@@ -1,10 +1,9 @@
-import { ChevronRightIcon } from "lucide-react";
+import { ChevronRightIcon, PackageIcon } from "lucide-react";
import { memo, useState, type MouseEvent } from "react";
import { cn } from "../../lib/utils";
import { GitHubIcon } from "../Icons";
import { Badge } from "../ui/badge";
-import { Button } from "../ui/button";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SettingsGroup } from "./SettingsGroup";
@@ -59,7 +58,8 @@ const SkillListItem = memo(function SkillListItem({
onClick={() => onOpen(row.name)}
className={cn(
"flex cursor-pointer items-center gap-3 py-2 pr-3 hover:bg-muted/40 sm:pr-4",
- nested ? "pl-9 sm:pl-10" : "pl-3 sm:pl-4",
+ // Nested rows start where their pack's name does: past its chevron and icon.
+ nested ? "pl-15 sm:pl-16" : "pl-3 sm:pl-4",
)}
>
{github ? (
-
- ) : null}
+
+ ) : (
+
+ )}
From {source}
{items.length}
@@ -178,10 +180,14 @@ function SourceGroup({
))
: null}
{open && items.length > SOURCE_GROUP_PREVIEW ? (
-
- setShowAll((value) => !value)}>
+
+ setShowAll((value) => !value)}
+ className="w-full cursor-pointer py-2 pr-3 pl-15 text-left text-xs text-muted-foreground outline-none hover:bg-muted/40 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:pr-4 sm:pl-16"
+ >
{hidden > 0 ? `${hidden} more` : "Show fewer"}
-
+
) : null}
>
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index 45040dec8c60f..8143e52cdf734 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -37,50 +37,77 @@ const provider = (
}) as ServerProvider;
describe("collectSkillRows", () => {
- it("merges one skill across providers and folders, grouped by its most specific location", () => {
- const rows = collectSkillRows(
+ const codexSkills: ServerProvider["skills"] = [
+ {
+ name: "frontend-design",
+ path: "/home/me/.agents/skills/frontend-design/SKILL.md",
+ scope: "user",
+ enabled: true,
+ },
+ {
+ name: "test-t3-app",
+ path: "/work/t3/.agents/skills/test-t3-app/SKILL.md",
+ scope: "repo",
+ enabled: true,
+ },
+ // A repository folder that happens to be called `plugins`.
+ {
+ name: "release",
+ path: "/work/t3/packages/plugins/.agents/skills/release/SKILL.md",
+ scope: "repo",
+ enabled: true,
+ },
+ // A plugin skill the provider reports with no scope.
+ {
+ name: "docs",
+ path: "/home/me/.claude/plugins/cache/acme/docs/skills/docs/SKILL.md",
+ enabled: true,
+ },
+ ];
+ const providers = [
+ provider("claudeAgent", [
+ {
+ name: "frontend-design",
+ path: "/home/me/.claude/skills/frontend-design/SKILL.md",
+ scope: "user",
+ enabled: true,
+ },
+ ]),
+ // Codex was launched in /work/other, whose repository skills it lists
+ // until a scan of the picked checkout arrives.
+ provider(
+ "codex",
[
- provider("claudeAgent", [
- {
- name: "frontend-design",
- path: "/home/me/.claude/skills/frontend-design/SKILL.md",
- scope: "user",
- enabled: true,
- },
- ]),
- provider("codex", [
- {
- name: "frontend-design",
- path: "/home/me/.agents/skills/frontend-design/SKILL.md",
- scope: "user",
- enabled: true,
- },
- {
- name: "test-t3-app",
- path: "/work/t3/.agents/skills/test-t3-app/SKILL.md",
- scope: "repo",
- enabled: true,
- },
- // A repository folder that happens to be called `plugins`.
- {
- name: "release",
- path: "/work/t3/packages/plugins/.agents/skills/release/SKILL.md",
- scope: "repo",
- enabled: true,
- },
- // A plugin skill the provider reports with no scope.
+ ...codexSkills.filter((skill) => skill.scope !== "repo"),
+ {
+ name: "launch-folder-skill",
+ path: "/work/other/.agents/skills/launch-folder-skill/SKILL.md",
+ scope: "repo",
+ enabled: true,
+ },
+ ],
+ {
+ workspaceSnapshots: [
{
- name: "docs",
- path: "/home/me/.claude/plugins/cache/acme/docs/skills/docs/SKILL.md",
- enabled: true,
+ cwd: "/work/t3",
+ checkedAt: "2026-10-10T00:00:00.000Z",
+ slashCommands: [],
+ skills: codexSkills,
},
- ]),
- provider("cursor", [], { enabled: false }),
- ],
- null,
- );
+ ],
+ },
+ ),
+ provider("cursor", [], { enabled: false }),
+ ];
+
+ it("merges one skill across providers and folders, grouped by its most specific location", () => {
expect(
- rows.map((row) => [row.name, row.group, row.paths.length, row.providers.length]),
+ collectSkillRows(providers, "/work/t3").map((row) => [
+ row.name,
+ row.group,
+ row.paths.length,
+ row.providers.length,
+ ]),
).toEqual([
["release", "project", 1, 1],
["test-t3-app", "project", 1, 1],
@@ -89,6 +116,19 @@ describe("collectSkillRows", () => {
]);
});
+ it("shows project skills only from a scan of the picked checkout", () => {
+ // No project picked: the launch folder's skills belong to no project here.
+ expect(collectSkillRows(providers, null).map((row) => row.name)).toEqual([
+ "frontend-design",
+ "docs",
+ ]);
+ // Before the checkout's scan arrives, nothing stands in for it.
+ expect(collectSkillRows(providers, "/work/elsewhere").map((row) => row.name)).toEqual([
+ "frontend-design",
+ "docs",
+ ]);
+ });
+
it("shows a skill as switched off by the provider only when every provider has it off", () => {
const skill = (enabled: boolean) => ({
name: "grill-me",
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 0105c60d9f3c7..abc1ed05b99f6 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -10,10 +10,7 @@ import {
type ServerProviderSkill,
type SkillFolderInfo,
} from "@t3tools/contracts";
-import {
- resolveProviderSkillSourceKind,
- resolveProviderSkillsForCwd,
-} from "@t3tools/client-runtime/providerSkills";
+import { resolveProviderSkillSourceKind } from "@t3tools/client-runtime/providerSkills";
export type ToolsTab = "skills" | "mcp";
@@ -96,8 +93,9 @@ const isFilePath = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.t
/**
* The skills every enabled provider instance on one environment discovers,
- * for the checkout at `cwd` when one is given (falling back to each
- * provider's own launch directory until its snapshot for `cwd` arrives).
+ * for the checkout at `cwd` when one is given. A provider's own list is read
+ * in the folder it was launched from, so its project skills belong to no
+ * project picked here: they show only from a scan of `cwd`.
* A skill reached from a project folder by any provider counts as a project
* skill, so the group follows the most specific location.
*/
@@ -118,11 +116,15 @@ export function collectSkillRows(
>();
for (const provider of providers) {
if (!provider.enabled) continue;
- const skills = cwd === null ? provider.skills : resolveProviderSkillsForCwd(provider, cwd);
- for (const skill of skills) {
+ const snapshot =
+ cwd === null
+ ? undefined
+ : provider.workspaceSnapshots?.find((candidate) => candidate.cwd === cwd);
+ for (const skill of snapshot?.skills ?? provider.skills) {
const key = skill.name.trim().toLowerCase();
if (key.length === 0) continue;
const group = skillGroup(skill);
+ if (group === "project" && snapshot === undefined) continue;
const ref: SkillProviderRef = {
instanceId: provider.instanceId,
driver: provider.driver,
From 17163abaf8195041f2189e185970c012badfecfe Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 21:33:51 -0700
Subject: [PATCH 22/35] fix(web): mark skill packs with a heading band instead
of an indent
A pack's skills now line up with every other row. Its From heading
is a slim tinted band whose switch and chevron sit in the rows' columns.
Co-Authored-By: Claude Opus 5.5
---
.../web/src/components/settings/SkillList.tsx | 53 +++++++++----------
1 file changed, 24 insertions(+), 29 deletions(-)
diff --git a/apps/web/src/components/settings/SkillList.tsx b/apps/web/src/components/settings/SkillList.tsx
index bd7a454bb6df4..2b6ae82d3a0d9 100644
--- a/apps/web/src/components/settings/SkillList.tsx
+++ b/apps/web/src/components/settings/SkillList.tsx
@@ -1,4 +1,4 @@
-import { ChevronRightIcon, PackageIcon } from "lucide-react";
+import { ChevronDownIcon, ChevronRightIcon, PackageIcon } from "lucide-react";
import { memo, useState, type MouseEvent } from "react";
import { cn } from "../../lib/utils";
@@ -43,12 +43,11 @@ interface RowHandlers {
const SkillListItem = memo(function SkillListItem({
item,
- nested,
agents,
canWrite,
onToggle,
onOpen,
-}: RowHandlers & { item: SkillListRow; nested: boolean }) {
+}: RowHandlers & { item: SkillListRow }) {
const { row, details, disabled, overridden } = item;
const lockedOff = row.disabledByProvider;
const warning = skillAttention(row, details, agents);
@@ -56,11 +55,7 @@ const SkillListItem = memo(function SkillListItem({
onOpen(row.name)}
- className={cn(
- "flex cursor-pointer items-center gap-3 py-2 pr-3 hover:bg-muted/40 sm:pr-4",
- // Nested rows start where their pack's name does: past its chevron and icon.
- nested ? "pl-15 sm:pl-16" : "pl-3 sm:pl-4",
- )}
+ className="flex cursor-pointer items-center gap-3 px-3 py-2 hover:bg-muted/40 sm:px-4"
>
setOpen((value) => !value)}
- className="flex cursor-pointer items-center gap-2 px-3 py-2 hover:bg-muted/40 sm:px-4"
+ className="flex cursor-pointer items-center gap-3 bg-muted/25 px-3 py-1.5 hover:bg-muted/40 sm:px-4"
>
-
{github ? (
-
+
) : (
-
+
)}
- From {source}
+
+ From {source}
+
{items.length}
@@ -170,21 +164,24 @@ function SourceGroup({
}
/>
- {/* The width of a row's chevron, so this switch sits over the rows' switches. */}
-
+
{open
- ? shown.map((item) => (
-
- ))
+ ? shown.map((item) => )
: null}
{open && items.length > SOURCE_GROUP_PREVIEW ? (
setShowAll((value) => !value)}
- className="w-full cursor-pointer py-2 pr-3 pl-15 text-left text-xs text-muted-foreground outline-none hover:bg-muted/40 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:pr-4 sm:pl-16"
+ className="w-full cursor-pointer px-3 py-2 text-left text-xs text-muted-foreground outline-none hover:bg-muted/40 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:px-4"
>
{hidden > 0 ? `${hidden} more` : "Show fewer"}
@@ -229,9 +226,7 @@ export function SkillListSection({
{groups.map(({ source, rows }) =>
source === null ? (
- rows.map((item) => (
-
- ))
+ rows.map((item) => )
) : (
),
From 2ea06517565d689243b10c6e7229f4aa3cf98549 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 21:43:40 -0700
Subject: [PATCH 23/35] fix(web): put the Tools tabs on one row with each tab's
controls
The tabs, search and buttons took three rows above the list. Each tab now puts
the tabs at the start of its own toolbar: search, the attention filter,
rescan and Add skills on Skills; Add server on MCP servers.
Needs attention becomes a warning icon with its count, shown only when
something needs a look, and its tooltip says what that means.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/settings/ToolsSettings.tsx | 95 +++++++++++--------
.../settings/toolsSettings.logic.ts | 2 +-
2 files changed, 58 insertions(+), 39 deletions(-)
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index 71f696f227f9e..0b8d203e05230 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -18,8 +18,8 @@ import {
skillsDisabledPatch,
} from "@t3tools/shared/agentTools";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
-import { MoreHorizontalIcon, PlusIcon, SearchIcon } from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { AlertTriangleIcon, MoreHorizontalIcon, PlusIcon, SearchIcon } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useAfterDelay } from "../../hooks/useAfterDelay";
import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
@@ -182,27 +182,27 @@ export function ToolsSettings({
readonly onTabChange: (tab: ToolsTab) => void;
readonly onOpenSkill: (name: string | null) => void;
}) {
- const selectTab = onTabChange;
+ // Each tab puts these at the start of its own toolbar row.
+ const tabs = (
+ {
+ const value = next[0];
+ if (value === "skills" || value === "mcp") onTabChange(value);
+ }}
+ >
+ Skills
+ MCP servers
+
+ );
return (
-
- {
- const value = next[0];
- if (value === "skills" || value === "mcp") selectTab(value);
- }}
- >
- Skills
- MCP servers
-
-
{tab === "mcp" ? (
-
+
) : (
-
+
)}
);
@@ -211,9 +211,11 @@ export function ToolsSettings({
// ── Skills ───────────────────────────────────────────────────────────
function SkillsPanel({
+ tabs,
openName,
onOpen,
}: {
+ tabs: ReactNode;
openName: string | null;
onOpen: (name: string | null) => void;
}) {
@@ -442,7 +444,8 @@ function SkillsPanel({
className="px-3 sm:px-4"
>
-
+ {tabs}
+
@@ -454,15 +457,28 @@ function SkillsPanel({
aria-label="Search skills"
/>
- {rows.length > 0 ? (
- setOnlyAttention((value) => !value)}
- >
- Needs attention ({attentionNames.size})
-
+ {attentionNames.size > 0 || onlyAttention ? (
+
+ setOnlyAttention((value) => !value)}
+ />
+ }
+ >
+
+ {attentionNames.size}
+
+
+ {onlyAttention
+ ? "Show all skills."
+ : "Show only skills that need a look: one name used by different skills, or a skill some of your agents don't load."}
+
+
) : null}
+
+ {tabs}
+ {canEditServers ? (
+
setEditor({ mode: "add" })}>
+
+ Add server
+
+ ) : null}
+
setEditor({ mode: "add" })}>
-
- Add server
-
- ) : null
- }
+ hideTitle={!isProjectScope}
>
{ownRows.length === 0 ? (
Date: Sat, 10 Oct 2026 21:48:46 -0700
Subject: [PATCH 24/35] fix(web): flag only skills that share a name, not ones
some agents skip
Not available to Claude gave nothing to act on: the agent chips already show
who loads a skill, and nothing in T3 makes another agent load it. Only a name
used by different skills needs a look now, and its message says what to do.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/settings/SkillDetail.tsx | 10 +++---
.../web/src/components/settings/SkillList.tsx | 8 ++---
.../src/components/settings/ToolsSettings.tsx | 12 +++----
.../settings/toolsSettings.logic.test.ts | 18 +++++-----
.../settings/toolsSettings.logic.ts | 34 ++++---------------
docs/user/tools.md | 3 +-
6 files changed, 33 insertions(+), 52 deletions(-)
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
index e9fe0b0cd0819..9cfcf83e52267 100644
--- a/apps/web/src/components/settings/SkillDetail.tsx
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -12,7 +12,7 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SkillAgentIcon } from "./SkillAgents";
import {
- skillAttention,
+ skillConflict,
type SkillAgent,
type SkillRow,
type SkillRowDetails,
@@ -72,7 +72,7 @@ export function SkillDetail({
}) {
useEscapeToList(onBack);
const loads = new Set(row.providers.map((provider) => provider.instanceId));
- const warning = skillAttention(row, details, agents);
+ const conflict = skillConflict(row, details);
// A name can be several folders (a conflict, or a project copy over a global one).
const [folderPath, setFolderPath] = useState(details.folder?.folder ?? null);
const folder =
@@ -150,16 +150,14 @@ export function SkillDetail({
) : null}
- {warning !== null || scripts.length > 0 || details.installed !== null ? (
+ {conflict !== null || scripts.length > 0 || details.installed !== null ? (
{details.installed !== null ? (
From {details.installed.source}
) : null}
- {warning !== null ? (
-
{warning.detail}
- ) : null}
+ {conflict !== null ?
{conflict} : null}
{scripts.length > 0 ? (
) : null}
- {warning?.kind === "conflict" ? (
+ {conflict !== null ? (
}>
@@ -89,7 +89,7 @@ const SkillListItem = memo(function SkillListItem({
- {warning.detail}
+ {conflict}
) : null}
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index 0b8d203e05230..ac466840e8177 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -61,7 +61,7 @@ import {
SKILL_GROUP_HINTS,
SKILL_GROUP_LABELS,
skillAgents,
- skillAttention,
+ skillConflict,
type SkillGroupKind,
type SkillRow,
skillRowDetails,
@@ -352,11 +352,11 @@ function SkillsPanel({
rows
.filter((row) => {
const details = detailsByName.get(row.name);
- return details !== undefined && skillAttention(row, details, agents) !== null;
+ return details !== undefined && skillConflict(row, details) !== null;
})
.map((row) => row.name),
),
- [agents, detailsByName, rows],
+ [detailsByName, rows],
);
const visibleRows = useMemo(
() =>
@@ -465,7 +465,7 @@ function SkillsPanel({
size="sm"
variant={onlyAttention ? "secondary" : "outline"}
aria-pressed={onlyAttention}
- aria-label={`Show only skills that need a look (${attentionNames.size})`}
+ aria-label={`Show only skills whose name is used more than once (${attentionNames.size})`}
onClick={() => setOnlyAttention((value) => !value)}
/>
}
@@ -476,7 +476,7 @@ function SkillsPanel({
{onlyAttention
? "Show all skills."
- : "Show only skills that need a look: one name used by different skills, or a skill some of your agents don't load."}
+ : "Show only skills whose name is used by different skills. One switch turns all of them on or off."}
) : null}
@@ -520,7 +520,7 @@ function SkillsPanel({
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index 8143e52cdf734..f0ca84016c628 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -15,8 +15,8 @@ import {
parseMcpServerJson,
formatArgs,
skillAgents,
- skillAttention,
skillAvailability,
+ skillConflict,
skillBody,
skillRowDetails,
splitRowsBySource,
@@ -256,13 +256,15 @@ describe("skill availability and attention", () => {
]);
});
- it("flags a skill some agents miss, but not a plugin or built-in one", () => {
- expect(skillAttention(row("personal", ["codex"]), noDetails, agents)?.detail).toBe(
- "Not available to Claude.",
- );
- expect(skillAttention(row("plugin", ["codex"]), noDetails, agents)).toBeNull();
- expect(skillAttention(row("system", ["codex"]), noDetails, agents)).toBeNull();
- expect(skillAttention(row("project", ["claudeAgent", "codex"]), noDetails, agents)).toBeNull();
+ it("flags only a name used by different skills, not one some agents don't load", () => {
+ expect(skillConflict(row("personal", ["codex"]), noDetails)).toBeNull();
+ expect(
+ skillConflict(row("personal", ["codex"]), {
+ ...noDetails,
+ copies: [noDetails.folder, noDetails.folder].filter((copy) => copy !== null),
+ conflict: true,
+ }),
+ ).toMatch(/^Different skills are named “review”/);
});
it("strips SKILL.md's header for the rendered view", () => {
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index fdcd5c29aef9c..d8b23a26135a2 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -308,34 +308,14 @@ export function availabilityNote(value: SkillAvailability): string {
}
/**
- * Why a skill needs a look, in one plain sentence, or null. Only a conflict
- * marks the row itself; the rest show in the list's attention filter and on
- * the skill's page.
+ * What to do about a skill that needs a look, or null. Only a name used by
+ * different skills does: its one switch can't tell them apart, and removing
+ * or renaming a copy fixes it. Which agents load a skill is shown, not flagged.
*/
-export interface SkillAttention {
- readonly kind: "conflict" | "missing";
- readonly detail: string;
-}
-
-export function skillAttention(
- row: SkillRow,
- details: SkillRowDetails,
- agents: ReadonlyArray,
-): SkillAttention | null {
- if (details.conflict) {
- return {
- kind: "conflict",
- detail: `Different skills are named “${row.name}”. Its switch turns all of them on or off.`,
- };
- }
- // A plugin or built-in skill belongs to its agent; others never load it.
- if (row.group !== "project" && row.group !== "personal") return null;
- const availability = skillAvailability(row, agents);
- if (availability.missing.length === 0) return null;
- return {
- kind: "missing",
- detail: `Not available to ${joinNames(availability.missing.map((agent) => agent.displayName))}.`,
- };
+export function skillConflict(row: SkillRow, details: SkillRowDetails): string | null {
+ return details.conflict
+ ? `Different skills are named “${row.name}”, and its switch turns them all on or off. Remove or rename the copy you don't want.`
+ : null;
}
/** Rows with no recorded source show first; a pack collapses past this many rows. */
diff --git a/docs/user/tools.md b/docs/user/tools.md
index 83384521a7aad..e1f22bdfff30a 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -20,7 +20,8 @@ With a project selected, a switch overrides the environment for that project onl
skill off for one project, or back on where the environment has it off.
A **Conflict** mark means two different skills share a name. The switch turns both of them on or
-off. **View files** in a skill's menu shows what is in its folder; a skill marked **Includes
+off, so remove or rename the copy you don't want; the warning button beside the search lists every
+conflict. **View files** in a skill's menu shows what is in its folder; a skill marked **Includes
scripts** has files an agent could run.
### Adding skills
From 88b1ea3305da6be4892f9fbc4f8f543ab99ddf53 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 21:53:04 -0700
Subject: [PATCH 25/35] fix(web): pick skills to add from dense rows, with
select all and a filter
Each skill in the Add skills picker took three lines, so a big source showed
three at a time. Rows now match the Skills list: name and one-line
description, a script mark, and the file count on the right. A header box
selects or clears every skill shown, and a source with many skills gets a
filter.
Co-Authored-By: Claude Opus 5.5
---
.../components/settings/AddSkillsDialog.tsx | 152 +++++++++++++-----
1 file changed, 113 insertions(+), 39 deletions(-)
diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx
index f51e3b3f1f337..9b41e1159534f 100644
--- a/apps/web/src/components/settings/AddSkillsDialog.tsx
+++ b/apps/web/src/components/settings/AddSkillsDialog.tsx
@@ -4,12 +4,12 @@ import {
type SkillInstallTarget,
type SkillPreviewItem,
} from "@t3tools/contracts";
-import { useId, useState } from "react";
+import { AlertTriangleIcon, SearchIcon } from "lucide-react";
+import { useId, useMemo, useState } from "react";
import { serverEnvironment } from "../../state/server";
import { formatEnvironmentQueryError } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
-import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
import {
@@ -22,12 +22,18 @@ import {
DialogTitle,
} from "../ui/dialog";
import { Input } from "../ui/input";
+import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
import { Label } from "../ui/label";
import { Spinner } from "../ui/spinner";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+
+/** A source this big gets a filter above its list. */
+const FILTER_FROM = 8;
/**
* Install skills from a source, as `npx skills add` does: paste the source,
* pick from the skills it holds, install for every agent at the current scope.
+ * The picker uses the Skills list's dense one-line rows.
*/
export function AddSkillsDialog({
open,
@@ -54,6 +60,7 @@ export function AddSkillsDialog({
readonly skills: ReadonlyArray;
} | null>(null);
const [selected, setSelected] = useState>(new Set());
+ const [filter, setFilter] = useState("");
const [busy, setBusy] = useState<"finding" | "installing" | null>(null);
const [error, setError] = useState(null);
@@ -70,6 +77,7 @@ export function AddSkillsDialog({
return;
}
setFound({ source: trimmed, skills: result.value.skills });
+ setFilter("");
// Everything is ticked, up to what one install takes.
setSelected(
new Set(result.value.skills.slice(0, MAX_SKILLS_PER_INSTALL).map((skill) => skill.name)),
@@ -111,6 +119,28 @@ export function AddSkillsDialog({
return next;
});
const full = selected.size >= MAX_SKILLS_PER_INSTALL;
+ const shown = useMemo(() => {
+ const needle = filter.trim().toLowerCase();
+ if (found === null || needle.length === 0) return found?.skills ?? [];
+ return found.skills.filter(
+ (skill) =>
+ skill.folder.toLowerCase().includes(needle) ||
+ skill.name.toLowerCase().includes(needle) ||
+ (skill.description ?? "").toLowerCase().includes(needle),
+ );
+ }, [filter, found]);
+ // The header box acts on the rows shown, so a filter can pick a subset.
+ const shownSelected = shown.filter((skill) => selected.has(skill.name)).length;
+ const allShown = shown.length > 0 && shownSelected === shown.length;
+ const selectShown = (checked: boolean) =>
+ setSelected((current) => {
+ const next = new Set(current);
+ for (const skill of shown) {
+ if (!checked) next.delete(skill.name);
+ else if (next.size < MAX_SKILLS_PER_INSTALL) next.add(skill.name);
+ }
+ return next;
+ });
return (
-
+
Add skills
@@ -166,43 +196,82 @@ export function AddSkillsDialog({
{found !== null ? (
-
-
- {found.skills.length === 1 ? "1 skill" : `${found.skills.length} skills`}
-
-
- {found.skills.map((skill) => (
-
- toggle(skill.name, checked === true)}
- />
-
-
- {skill.folder}
+
+ Skills in {found.source}
+ {found.skills.length >= FILTER_FROM ? (
+
+
+
+
+ setFilter(event.target.value)}
+ aria-label="Filter skills"
+ />
+
+ ) : null}
+
+
+ 0 && !allShown}
+ disabled={shown.length === 0}
+ onCheckedChange={(checked) => selectShown(checked === true)}
+ />
+
+ {filter.trim() === "" ? "Select all" : "Select all shown"}
+
+
+ {selected.size} of {found.skills.length} selected
+
+
+
+ {shown.length === 0 ? (
+
+ No skills match “{filter.trim()}”.
+
+ ) : null}
+ {shown.map((skill) => (
+
+
+ toggle(skill.name, checked === true)}
+ />
+
+
+ {skill.folder}
+
+
+ {skill.description || "No description."}
+
+
{skill.scripts ? (
-
- Includes scripts
-
+
+
+ }
+ >
+
+
+ Includes scripts
+
) : null}
-
- {skill.description ? (
-
- {skill.description}
+
+ {skill.files.length === 1 ? "1 file" : `${skill.files.length} files`}
+ {skill.filesTruncated ? "+" : ""}
- ) : null}
-
- {skill.files.length === 1 ? "1 file" : `${skill.files.length} files`}
- {skill.filesTruncated ? " or more" : ""}
-
-
-
- ))}
+
+
+ ))}
+
{found.skills.length > MAX_SKILLS_PER_INSTALL ? (
@@ -210,8 +279,13 @@ export function AddSkillsDialog({
afterwards.
) : null}
-
- Skills can tell agents to run their scripts. Install only sources you trust.
+
+
+ marks skills with scripts agents can be told to run. Install only sources you
+ trust.
) : null}
From 4ae47262708e8602f544bad013ed4c73195bf65a Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 21:57:12 -0700
Subject: [PATCH 26/35] fix(web): show a skill's whole description when its
line is cut off
Hovering a description that ends in an ellipsis, in the Skills list or the
Add skills picker, shows the full text. The fit is checked as the tooltip
opens, so a line that fits shows none and the lists measure nothing until
hovered.
Co-Authored-By: Claude Opus 5.5
---
.../components/settings/AddSkillsDialog.tsx | 8 +++--
.../web/src/components/settings/SkillList.tsx | 14 ++++++---
.../src/components/settings/TruncatedText.tsx | 31 +++++++++++++++++++
3 files changed, 45 insertions(+), 8 deletions(-)
create mode 100644 apps/web/src/components/settings/TruncatedText.tsx
diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx
index 9b41e1159534f..4614c4cb43395 100644
--- a/apps/web/src/components/settings/AddSkillsDialog.tsx
+++ b/apps/web/src/components/settings/AddSkillsDialog.tsx
@@ -26,6 +26,7 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"
import { Label } from "../ui/label";
import { Spinner } from "../ui/spinner";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { TruncatedText } from "./TruncatedText";
/** A source this big gets a filter above its list. */
const FILTER_FROM = 8;
@@ -245,9 +246,10 @@ export function AddSkillsDialog({
{skill.folder}
-
- {skill.description || "No description."}
-
+
{skill.scripts ? (
diff --git a/apps/web/src/components/settings/SkillList.tsx b/apps/web/src/components/settings/SkillList.tsx
index 9f71d1b8e30d2..69c900075a988 100644
--- a/apps/web/src/components/settings/SkillList.tsx
+++ b/apps/web/src/components/settings/SkillList.tsx
@@ -8,6 +8,7 @@ import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SettingsGroup } from "./SettingsGroup";
import { SkillAgents } from "./SkillAgents";
+import { TruncatedText } from "./TruncatedText";
import {
SOURCE_GROUP_PREVIEW,
skillAvailability,
@@ -69,11 +70,14 @@ const SkillListItem = memo(function SkillListItem({
>
{row.name}
-
- {lockedOff
- ? "Turned off in the agent's own settings."
- : row.description || "No description yet."}
-
+
{overridden ? (
diff --git a/apps/web/src/components/settings/TruncatedText.tsx b/apps/web/src/components/settings/TruncatedText.tsx
new file mode 100644
index 0000000000000..ae0172484dbd4
--- /dev/null
+++ b/apps/web/src/components/settings/TruncatedText.tsx
@@ -0,0 +1,31 @@
+import { useRef } from "react";
+
+import { cn } from "../../lib/utils";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+
+/**
+ * One line of text that ends in an ellipsis when it doesn't fit, with the
+ * whole text in a tooltip on hover. The fit is checked as the tooltip opens,
+ * so a line that fits never shows one and long lists measure nothing until
+ * hovered.
+ */
+export function TruncatedText({ text, className }: { text: string; className?: string }) {
+ const ref = useRef(null);
+ return (
+ {
+ const element = ref.current;
+ if (open && element !== null && element.scrollWidth <= element.clientWidth) {
+ details.cancel();
+ }
+ }}
+ >
+ }>
+ {text}
+
+
+ {text}
+
+
+ );
+}
From 57758db86de64d1e43005b693c63d6445006fc3e Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 22:34:59 -0700
Subject: [PATCH 27/35] feat: remove any skill in the agents' own skill folders
Remove only reached skills the skills CLI had installed, so most of a
skill folder could be switched off but not deleted. A skill's menu now has
Remove for any copy an agent finds directly in its own skill folders, at
home or in the project. One the CLI installed still goes through the CLI;
another is deleted from each folder an agent reports for it, links first,
along with the folder a link points to when that is one of the user's own.
Plugin and built-in skills stay switch-only.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/mcp/toolkits/tools/tools.ts | 2 +-
apps/server/src/skills/SkillLibrary.test.ts | 61 ++++++++++++
apps/server/src/skills/SkillLibrary.ts | 97 +++++++++++++++++--
.../src/components/settings/ToolsSettings.tsx | 28 ++++--
.../settings/toolsSettings.logic.test.ts | 1 +
.../settings/toolsSettings.logic.ts | 13 ++-
docs/user/tools.md | 4 +-
packages/contracts/src/skills.ts | 16 ++-
.../src/server/AgentSkillFolders.ts | 13 +++
9 files changed, 217 insertions(+), 18 deletions(-)
diff --git a/apps/server/src/mcp/toolkits/tools/tools.ts b/apps/server/src/mcp/toolkits/tools/tools.ts
index ffcef1d376bd9..0a8c8a608fd97 100644
--- a/apps/server/src/mcp/toolkits/tools/tools.ts
+++ b/apps/server/src/mcp/toolkits/tools/tools.ts
@@ -89,7 +89,7 @@ const SkillsInstallTool = Tool.make("t3_skills_install", {
const SkillsRemoveTool = Tool.make("t3_skills_remove", {
...shared,
description:
- "Remove a skill installed from a source (with t3_skills_install, the Tools page, or `npx skills`), with every agent's link to it. Requires a live full-access/default calling thread.",
+ "Remove a skill from the agents' own skill folders for this environment or one project, with every agent's link to it: one installed from a source (with t3_skills_install, the Tools page, or `npx skills`) or put there by hand. Plugin and built-in skills can only be switched off with t3_tools_update. Requires a live full-access/default calling thread.",
parameters: Schema.Struct({ ...Scope, name: InstalledSkillName }),
success: Schema.Struct({}),
}).annotate(Tool.Destructive, true);
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index ec5736236cd6e..5294f3ccd7038 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -267,6 +267,67 @@ it.effect(
60_000,
);
+it.effect(
+ "removes a skill put in an agent folder by hand, and only from the agents' own folders",
+ () =>
+ withLibrary(({ library, home, providers }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ // A hand-made skill in ~/.agents/skills, linked into ~/.claude/skills
+ // the way other installers do, plus one only in a plugin's folder.
+ const own = path.join(home, ".agents", "skills", "handmade");
+ const link = path.join(home, ".claude", "skills", "handmade");
+ const plugin = path.join(home, ".claude", "plugins", "acme", "skills", "handmade");
+ yield* fileSystem.makeDirectory(own, { recursive: true });
+ yield* fileSystem.writeFileString(path.join(own, "SKILL.md"), SKILL("handmade", "Mine."));
+ yield* fileSystem.makeDirectory(path.dirname(link), { recursive: true });
+ yield* fileSystem.symlink(own, link);
+ yield* fileSystem.makeDirectory(plugin, { recursive: true });
+ yield* fileSystem.writeFileString(
+ path.join(plugin, "SKILL.md"),
+ SKILL("handmade", "A plugin's."),
+ );
+ const reported = (skillPath: string) => ({
+ name: "handmade",
+ path: skillPath,
+ scope: "user",
+ enabled: true,
+ });
+ yield* Ref.set(providers, [
+ {
+ ...claude,
+ skills: [
+ reported(path.join(link, "SKILL.md")),
+ reported(path.join(plugin, "SKILL.md")),
+ ],
+ },
+ ]);
+
+ const inspected = yield* library.inspect({});
+ assert.deepEqual(
+ inspected.folders.map((folder) => [folder.path, folder.location?.kind, folder.installed]),
+ [
+ [path.join(link, "SKILL.md"), "environment", undefined],
+ [path.join(plugin, "SKILL.md"), undefined, undefined],
+ ],
+ );
+
+ yield* library.remove({ name: "handmade", target: { kind: "environment" } });
+ assert.isFalse(yield* fileSystem.exists(own));
+ assert.isFalse(
+ yield* fileSystem.readLink(link).pipe(
+ Effect.as(true),
+ Effect.orElseSucceed(() => false),
+ ),
+ );
+ // The plugin's copy isn't the user's to remove.
+ assert.isTrue(yield* fileSystem.exists(path.join(plugin, "SKILL.md")));
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 60_000,
+);
+
it.effect(
"fails a removal the CLI couldn't finish, which it reports with a zero exit",
() =>
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index 5bc5ad581d16b..088f9c7cad9ba 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -7,8 +7,9 @@
* their own folder. The CLI's lock files (`~/.agents/.skill-lock.json`, or
* `$XDG_STATE_HOME/skills/.skill-lock.json`, and a project's
* `skills-lock.json`) record where each install came from; this module reads
- * them to group skills by source and to update or remove only what the CLI
- * installed. Turning skills on or off stays in settings.
+ * them to group skills by source and to update only what the CLI installed.
+ * Remove takes any skill in the agents' own skill folders, through the CLI
+ * when it installed the skill. Turning skills on or off stays in settings.
*
* @module SkillLibrary
*/
@@ -29,6 +30,7 @@ import {
} from "@t3tools/contracts";
import {
STANDARD_SKILL_FOLDER,
+ agentSkillFolderRoots,
skillsCliInstallAgents,
} from "@t3tools/provider-core/server/AgentSkillFolders";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
@@ -65,7 +67,10 @@ export class SkillLibrary extends Context.Service<
readonly update: (
input: InstalledSkillInput,
) => Effect.Effect;
- /** Remove a skill the CLI installed, with every agent's link to it. */
+ /**
+ * Remove a skill from the agents' skill folders at one level: through the
+ * CLI when it installed the skill, else each folder's copy of that name.
+ */
readonly remove: (input: InstalledSkillInput) => Effect.Effect;
}
>()("t3/skills/SkillLibrary") {}
@@ -314,6 +319,15 @@ const make = Effect.gen(function* () {
const hasScripts = (files: ReadonlyArray) => files.some((file) => file.script);
+ /** The agents' skill folders at a level, as written and after links. */
+ const skillRoots = (target: SkillInstallTarget) =>
+ Effect.forEach(
+ agentSkillFolderRoots(target.kind === "environment" ? "home" : "project").map((folder) =>
+ path.join(targetPaths(target).root, folder),
+ ),
+ (folder) => realPath(folder).pipe(Effect.map((real) => [folder, real])),
+ ).pipe(Effect.map((pairs) => [...new Set(pairs.flat())]));
+
const sha256 = (text: string) =>
crypto.digest("SHA-256", new TextEncoder().encode(text)).pipe(
Effect.map(Hex.encode),
@@ -347,6 +361,7 @@ const make = Effect.gen(function* () {
target,
folder: yield* realPath(paths.folder),
lock: yield* readLock(paths.lock),
+ roots: yield* skillRoots(target),
};
}),
);
@@ -359,8 +374,16 @@ const make = Effect.gen(function* () {
.readFileString(skillPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (contents === undefined) return undefined;
- const folder = yield* realPath(path.dirname(skillPath));
+ const reportedFolder = path.dirname(skillPath);
+ const folder = yield* realPath(reportedFolder);
const name = path.basename(folder);
+ // Where the agent found it, before links: `~/.claude/skills/x` can
+ // link to `~/.agents/skills/x`, and either makes it the user's own.
+ const parent = path.dirname(reportedFolder);
+ const location = installs.find(
+ (candidate) =>
+ candidate.roots.includes(parent) || candidate.roots.includes(path.dirname(folder)),
+ )?.target;
const install = installs.find(
(candidate) =>
path.dirname(folder) === candidate.folder &&
@@ -376,6 +399,7 @@ const make = Effect.gen(function* () {
files,
filesTruncated: truncated,
scripts: hasScripts(files),
+ ...(location === undefined ? {} : { location }),
...(install === undefined || entry === undefined
? {}
: { installed: { target: install.target, source: entry.source } }),
@@ -513,7 +537,7 @@ const make = Effect.gen(function* () {
? Effect.fail(
new SkillLibraryError({
reason: "notInstalled",
- message: "Only skills installed from a source can be updated or removed here.",
+ message: "Only skills installed from a source can be updated here.",
}),
)
: Effect.succeed(found);
@@ -551,7 +575,9 @@ const make = Effect.gen(function* () {
const removeLocked = (target: SkillInstallTarget, name: string) =>
Effect.gen(function* () {
- const { key } = yield* lockedEntry(target, name);
+ const locked = lockEntryFor(yield* readLock(targetPaths(target).lock), name);
+ if (locked === undefined) return yield* removeUnlocked(target, name);
+ const { key } = locked;
const paths = targetPaths(target);
yield* cli
.remove({
@@ -577,6 +603,65 @@ const make = Effect.gen(function* () {
}
});
+ /**
+ * A skill no lock records, put in place by hand or by another tool: delete
+ * each folder an enabled agent reports for that name directly inside one of
+ * the level's agent skill folders, links first. Only reported folders count,
+ * so a name can't reach anything else.
+ */
+ const removeUnlocked = (target: SkillInstallTarget, name: string) =>
+ Effect.gen(function* () {
+ const roots = yield* skillRoots(target);
+ const wanted = name.trim().toLowerCase();
+ const reported = new Set();
+ for (const provider of yield* enabledProviders) {
+ const lists = [
+ ...(target.kind === "environment" ? [provider.skills] : []),
+ ...(provider.workspaceSnapshots ?? [])
+ .filter((snapshot) => target.kind === "environment" || snapshot.cwd === target.cwd)
+ .map((snapshot) => snapshot.skills),
+ ];
+ for (const skill of lists.flat()) {
+ if (skill.name.trim().toLowerCase() !== wanted || !path.isAbsolute(skill.path)) continue;
+ const folder = path.dirname(skill.path);
+ if (!roots.includes(path.dirname(folder))) continue;
+ reported.add(folder);
+ // A link's folder goes too when it is one of the user's own.
+ const real = yield* realPath(folder);
+ if (roots.includes(path.dirname(real))) reported.add(real);
+ }
+ }
+ if (reported.size === 0) {
+ return yield* new SkillLibraryError({
+ reason: "notInstalled",
+ message: `No skill named ${name} is in the agents' skill folders here.`,
+ });
+ }
+ // Links go first, so none is left pointing at a deleted folder.
+ const isLink = (folder: string) =>
+ fileSystem.readLink(folder).pipe(
+ Effect.as(true),
+ Effect.orElseSucceed(() => false),
+ );
+ const links = yield* Effect.filter([...reported], isLink);
+ const folders = [...links, ...[...reported].filter((folder) => !links.includes(folder))];
+ yield* Effect.forEach(
+ folders,
+ (folder) =>
+ fileSystem
+ .remove(folder, { recursive: true })
+ .pipe(
+ Effect.mapError(() =>
+ cliFailed(
+ `Couldn't remove ${name}. Check the permissions of ${path.dirname(folder)}.`,
+ ),
+ ),
+ ),
+ { discard: true },
+ );
+ yield* refreshAgents(target);
+ });
+
return SkillLibrary.of({ inspect, preview, install, update, remove });
});
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index ac466840e8177..687b762d10708 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -256,6 +256,8 @@ function SkillsPanel({
const [removingSkill, setRemovingSkill] = useState<{
readonly name: string;
readonly target: SkillInstallTarget;
+ /** The `skills` CLI installed it, so its lock entry goes too. */
+ readonly installed: boolean;
} | null>(null);
const [skillActionError, setSkillActionError] = useState(null);
const inspected = useEnvironmentQuery(
@@ -402,10 +404,11 @@ function SkillsPanel({
: () => void runSkillAction("update", { name: row.name, target: installed.target });
};
const removeOf = (row: SkillRow) => {
- const installed = detailsOf(row).installed;
- return installed === null || !canInstall
+ const { installed, removable } = detailsOf(row);
+ return removable === null || !canInstall
? null
- : () => setRemovingSkill({ name: row.name, target: installed.target });
+ : () =>
+ setRemovingSkill({ name: row.name, target: removable, installed: installed !== null });
};
const opened = openName === null ? null : (rows.find((row) => row.name === openName) ?? null);
@@ -568,8 +571,18 @@ function SkillsPanel({
Remove {removingSkill?.name}?
- Deletes the skill's folder and every agent's link to it, as{" "}
- npx skills remove does.
+ {removingSkill?.installed ? (
+ <>
+ Deletes the skill's folder and every agent's link to it, as{" "}
+ npx skills remove does.
+ >
+ ) : (
+ `Deletes ${removingSkill?.name ?? "the skill"} from every agent's skill folder ${
+ removingSkill?.target.kind === "project"
+ ? "in this project"
+ : "on this environment"
+ }. It wasn't installed from a source, so it can't be added back from here.`
+ )}
@@ -578,7 +591,10 @@ function SkillsPanel({
variant="destructive"
onClick={() => {
if (removingSkill) {
- void runSkillAction("remove", removingSkill);
+ void runSkillAction("remove", {
+ name: removingSkill.name,
+ target: removingSkill.target,
+ });
if (removingSkill.name === openName) onOpen(null);
}
setRemovingSkill(null);
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index f0ca84016c628..03644a2557f01 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -200,6 +200,7 @@ describe("skill row details", () => {
scripts: false,
conflict: false,
installed: null,
+ removable: null,
});
});
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index d8b23a26135a2..8b302f3a7875d 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -199,8 +199,14 @@ export interface SkillRowDetails {
readonly scripts: boolean;
/** Two copies of the name have different SKILL.md text. */
readonly conflict: boolean;
- /** Set when the `skills` CLI installed the row's skill, so it can be updated or removed. */
+ /** Set when the `skills` CLI installed the row's skill, so it can be updated. */
readonly installed: NonNullable | null;
+ /**
+ * The level to remove the skill from: where the CLI installed it, else
+ * where a copy sits in the agents' own skill folders. Null for a plugin's
+ * or an agent's built-in skill.
+ */
+ readonly removable: NonNullable | null;
}
const NO_DETAILS: SkillRowDetails = {
@@ -209,6 +215,7 @@ const NO_DETAILS: SkillRowDetails = {
scripts: false,
conflict: false,
installed: null,
+ removable: null,
};
export function skillRowDetails(
@@ -225,12 +232,14 @@ export function skillRowDetails(
const copies = [...byFolder.values()].toSorted(
(left, right) => Number(right.installed !== undefined) - Number(left.installed !== undefined),
);
+ const installed = copies.find((info) => info.installed !== undefined)?.installed ?? null;
return {
folder: copies[0] ?? null,
copies,
scripts: copies.some((info) => info.scripts),
conflict: new Set(copies.map((info) => info.hash)).size > 1,
- installed: copies.find((info) => info.installed !== undefined)?.installed ?? null,
+ installed,
+ removable: installed?.target ?? copies.find((info) => info.location)?.location ?? null,
};
}
diff --git a/docs/user/tools.md b/docs/user/tools.md
index e1f22bdfff30a..d82673ee7a82f 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -36,7 +36,9 @@ for every project. Agents that only read their own folder, such as Claude, get a
Skills installed this way, here or with `npx skills` in a terminal, are grouped by where they came
from, with one switch for the group. Their menu has **Update**, which installs the latest version
-from the same source, and **Remove**. Installing runs the open-source
+from the same source, and **Remove**. Other skills in your own skill folders, such as
+`~/.claude/skills` or a project's `.agents/skills`, can be removed from a skill's menu too; skills
+from plugins and the ones agents ship with can only be switched off. Installing runs the open-source
[`skills`](https://github.com/vercel-labs/skills) installer built into T3 Code, with its telemetry
off. Installing, updating and removing skills needs permission to manage providers.
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
index 64e62bee23279..d7b8f4db8bde4 100644
--- a/packages/contracts/src/skills.ts
+++ b/packages/contracts/src/skills.ts
@@ -84,7 +84,10 @@ export const SkillInstallInput = Schema.Struct({
});
export type SkillInstallInput = typeof SkillInstallInput.Type;
-/** One skill an `installed` lock entry names, to update or remove. */
+/**
+ * One skill at a level, by the name agents know it by: to update one the CLI
+ * installed, or to remove one from the agents' skill folders there.
+ */
export const InstalledSkillInput = Schema.Struct({
name: InstalledSkillName,
target: SkillInstallTarget,
@@ -122,6 +125,12 @@ export const SkillFolderInfo = Schema.Struct({
files: Schema.Array(SkillFileEntry),
filesTruncated: Schema.Boolean,
scripts: Schema.Boolean,
+ /**
+ * The level this copy belongs to when the agent found it directly in one of
+ * the agents' skill folders, at home or in the project, so it can be
+ * removed. Absent for a plugin's or an agent's built-in skills.
+ */
+ location: Schema.optional(SkillInstallTarget),
/** Set when the `skills` CLI installed this folder: its lock names the source. */
installed: Schema.optional(
Schema.Struct({
@@ -146,7 +155,10 @@ export class SkillLibraryError extends Schema.TaggedError()(
"noSkills",
/** The project isn't one of this environment's projects. */
"projectNotRegistered",
- /** Only skills the CLI installed (with a lock entry) can be updated or removed. */
+ /**
+ * Nothing to change: update needs a skill the CLI installed (with a lock
+ * entry), and remove a skill in the agents' skill folders at that level.
+ */
"notInstalled",
]),
message: Schema.String,
diff --git a/packages/provider-core/src/server/AgentSkillFolders.ts b/packages/provider-core/src/server/AgentSkillFolders.ts
index 3635267470e54..d315ea26ad633 100644
--- a/packages/provider-core/src/server/AgentSkillFolders.ts
+++ b/packages/provider-core/src/server/AgentSkillFolders.ts
@@ -75,6 +75,19 @@ const AGENT_SKILL_FOLDERS: Readonly> = {
const agentSkillFolders = (driver: ProviderDriverKind): AgentSkillFolders | undefined =>
AGENT_SKILL_FOLDERS[driver];
+/**
+ * Every folder some agent reads skills from at a level. A skill directly in
+ * one is the user's own, as opposed to a plugin's or an agent's built-in one.
+ */
+export function agentSkillFolderRoots(level: "home" | "project"): ReadonlyArray {
+ return [
+ ...new Set([
+ STANDARD_SKILL_FOLDER,
+ ...Object.values(AGENT_SKILL_FOLDERS).flatMap((folders) => folders[level]),
+ ]),
+ ];
+}
+
/**
* The `skills` CLI agents an install names so every listed driver can use the
* skill: `universal` writes `.agents/skills`, and each driver that doesn't read
From 8ddae4a09f0c77556661bb42c02d22d12eec1f2d Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 22:40:04 -0700
Subject: [PATCH 28/35] fix(web): copy a skill's path from a button beside it
Copy path sat in the skill's menu, away from the path it copies. It is now
an icon button after the folder path, for whichever copy is shown, and turns
into a check once copied. The menu keeps Update and Remove.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/settings/SkillDetail.tsx | 42 +++++++++----------
1 file changed, 21 insertions(+), 21 deletions(-)
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
index 9cfcf83e52267..92b9b586f37b7 100644
--- a/apps/web/src/components/settings/SkillDetail.tsx
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -1,13 +1,14 @@
import type { EnvironmentId } from "@t3tools/contracts";
+import { Check, Copy } from "lucide";
import { AlertTriangleIcon, MoreHorizontalIcon } from "lucide-react";
import { lazy, Suspense, useEffect, useEffectEvent, useState } from "react";
-import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
+import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
+import { MorphIcon } from "../MorphIcon";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Skeleton } from "../ui/skeleton";
-import { toastManager } from "../ui/toast";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SkillAgentIcon } from "./SkillAgents";
@@ -79,20 +80,7 @@ export function SkillDetail({
details.copies.find((copy) => copy.folder === folderPath) ?? details.folder ?? null;
const scripts = folder?.files.filter((file) => file.script).map((file) => file.path) ?? [];
- const copyPath = (path: string) => {
- void writeTextToClipboard(path, "skill path").then(
- (copied) => {
- if (copied) toastManager.add({ type: "success", title: "Path copied", description: path });
- },
- (error: unknown) => {
- toastManager.add({
- type: "error",
- title: "Failed to copy path",
- description: error instanceof Error ? error.message : "An error occurred.",
- });
- },
- );
- };
+ const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 1500, target: "skill path" });
return (
@@ -129,7 +117,7 @@ export function SkillDetail({
);
})}
- {folder !== null || onUpdate !== null || onRemove !== null ? (
+ {onUpdate !== null || onRemove !== null ? (
}
@@ -137,9 +125,6 @@ export function SkillDetail({
- {folder !== null ? (
- copyPath(folder.folder)}>Copy path
- ) : null}
{onUpdate !== null ? Update : null}
{onRemove !== null ? (
@@ -200,9 +185,24 @@ export function SkillDetail({
))}
) : null}
-
+
{folder.folder}
+
+ copyToClipboard(folder.folder, undefined)}
+ />
+ }
+ >
+
+
+ {isCopied ? "Copied" : "Copy path"}
+
) : null}
{folder === null ? (
From 93548e8821a39fc416fc9dbd94c07d5c67b83ac5 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 22:43:24 -0700
Subject: [PATCH 29/35] fix(web): show a skill's Update and Remove as buttons,
not a menu
With Copy path beside the path, the skill's menu held one or two items. They
are now buttons on the skill's page: Update for a skill installed from a
source, and Remove.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/settings/SkillDetail.tsx | 28 +++++++------------
docs/user/tools.md | 4 +--
2 files changed, 12 insertions(+), 20 deletions(-)
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
index 92b9b586f37b7..7847d89c7cc89 100644
--- a/apps/web/src/components/settings/SkillDetail.tsx
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -1,13 +1,12 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { Check, Copy } from "lucide";
-import { AlertTriangleIcon, MoreHorizontalIcon } from "lucide-react";
+import { AlertTriangleIcon } from "lucide-react";
import { lazy, Suspense, useEffect, useEffectEvent, useState } from "react";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { MorphIcon } from "../MorphIcon";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
-import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Skeleton } from "../ui/skeleton";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -117,22 +116,15 @@ export function SkillDetail({
);
})}
- {onUpdate !== null || onRemove !== null ? (
-
- }
- >
-
-
-
- {onUpdate !== null ? Update : null}
- {onRemove !== null ? (
-
- Remove
-
- ) : null}
-
-
+ {onUpdate !== null ? (
+
+ Update
+
+ ) : null}
+ {onRemove !== null ? (
+
+ Remove
+
) : null}
{conflict !== null || scripts.length > 0 || details.installed !== null ? (
diff --git a/docs/user/tools.md b/docs/user/tools.md
index d82673ee7a82f..6e755ef53d2a7 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -35,9 +35,9 @@ With a project selected, skills go into the project's `.agents/skills` folder an
for every project. Agents that only read their own folder, such as Claude, get a link to the skill.
Skills installed this way, here or with `npx skills` in a terminal, are grouped by where they came
-from, with one switch for the group. Their menu has **Update**, which installs the latest version
+from, with one switch for the group. Their page has **Update**, which installs the latest version
from the same source, and **Remove**. Other skills in your own skill folders, such as
-`~/.claude/skills` or a project's `.agents/skills`, can be removed from a skill's menu too; skills
+`~/.claude/skills` or a project's `.agents/skills`, can be removed from a skill's page too; skills
from plugins and the ones agents ship with can only be switched off. Installing runs the open-source
[`skills`](https://github.com/vercel-labs/skills) installer built into T3 Code, with its telemetry
off. Installing, updating and removing skills needs permission to manage providers.
From b6fe2fa677859f94e7e773e094d401cbe0406da4 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 22:43:38 -0700
Subject: [PATCH 30/35] docs: a skill's page shows its files, there is no View
files menu item
Co-Authored-By: Claude Opus 5.5
---
docs/user/tools.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/user/tools.md b/docs/user/tools.md
index 6e755ef53d2a7..726f4dc07dffd 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -21,7 +21,7 @@ skill off for one project, or back on where the environment has it off.
A **Conflict** mark means two different skills share a name. The switch turns both of them on or
off, so remove or rename the copy you don't want; the warning button beside the search lists every
-conflict. **View files** in a skill's menu shows what is in its folder; a skill marked **Includes
+conflict. Opening a skill shows the files in its folder; a skill marked **Includes
scripts** has files an agent could run.
### Adding skills
From 57ce0cfff39cfe21afcc26e2a9c6a90afc7c518f Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 22:58:38 -0700
Subject: [PATCH 31/35] fix(web): list T3 Code's own MCP server, always on
Every agent session gets the t3-code server, but the MCP servers tab only
listed servers added there, so it looked like T3's tools weren't given at
all. It now heads the list as a built-in server with a switch that is on and
locked, since nothing turns it off.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/settings/ToolsSettings.tsx | 30 +++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index 687b762d10708..43cabbf353841 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -754,6 +754,7 @@ function McpServersPanel({ tabs }: { tabs: ReactNode }) {
title={isProjectScope ? "This project" : "MCP servers"}
hideTitle={!isProjectScope}
>
+ {isProjectScope ? null : }
{ownRows.length === 0 ? (
+ t3-code
+
+ Built in
+
+
+ }
+ description="T3 Code's own tools: threads, tasks, the browser and devices."
+ control={
+
+ }>
+
+
+ Every agent session gets this server.
+
+ }
+ />
+ );
+}
+
function McpServerSettingsRow({
row,
canSwitch,
From d2758ad7f49a62d7bd9916a76cdd2ea66f725555 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sat, 10 Oct 2026 23:35:59 -0700
Subject: [PATCH 32/35] feat: show which environments have each skill, and copy
one to the rest
With several environments in scope, the Skills tab read only the primary
environment, so a skill on one machine but not another looked the same.
It now reads every environment in scope and merges their skills by name.
A row shows the machines that have the skill, or one fleet mark when they
all do; its page lists them and can copy the skill to the ones missing it.
A copy goes through two new RPCs. skills.export packs the folder an agent
reports for the skill (bounded at 4 MiB and 500 files). skills.import
reinstalls from the skill's remote source when the CLI recorded one, so the
copy can be updated, and otherwise writes the files into .agents/skills
with links for agents that read their own folder. Update and Remove on a
skill's page now reach every environment in scope that has it.
Co-Authored-By: Claude Opus 5.5
---
apps/server/src/auth/RpcAuthorization.ts | 2 +
.../src/observability/RpcInstrumentation.ts | 2 +
apps/server/src/skills/SkillLibrary.test.ts | 84 +++++
apps/server/src/skills/SkillLibrary.ts | 193 +++++++++-
apps/server/src/ws.ts | 2 +
.../src/components/settings/SkillDetail.tsx | 62 ++-
.../components/settings/SkillEnvironments.tsx | 144 +++++++
.../web/src/components/settings/SkillList.tsx | 13 +-
.../src/components/settings/ToolsSettings.tsx | 356 ++++++++++++++----
.../settings/toolsSettings.logic.test.ts | 30 ++
.../settings/toolsSettings.logic.ts | 56 +++
docs/user/tools.md | 5 +
packages/client-runtime/src/state/server.ts | 9 +
.../contracts/src/clientRpcPermissions.ts | 1 +
packages/contracts/src/rpc.ts | 19 +
packages/contracts/src/skills.ts | 52 +++
.../src/server/AgentSkillFolders.ts | 26 ++
17 files changed, 971 insertions(+), 85 deletions(-)
create mode 100644 apps/web/src/components/settings/SkillEnvironments.tsx
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 9d32a456c8d4a..1446b240d52cb 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -146,6 +146,8 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.skillsInspect]: AuthFilesystemReadScope,
// A preview unpacks a source into a temp folder and deletes it.
[WS_METHODS.skillsPreview]: AuthFilesystemReadScope,
+ // Packs a folder an agent reports for that skill, nothing a client names.
+ [WS_METHODS.skillsExport]: AuthFilesystemReadScope,
[WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
[WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 0447400994fa9..f5b637eecc1c3 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -38,6 +38,8 @@ const RPC_AGGREGATES = {
[WS_METHODS.skillsInstall]: "skills",
[WS_METHODS.skillsUpdate]: "skills",
[WS_METHODS.skillsRemove]: "skills",
+ [WS_METHODS.skillsExport]: "skills",
+ [WS_METHODS.skillsImport]: "skills",
[WS_METHODS.serverUpdateProvider]: "server",
[WS_METHODS.providerAuthStart]: "provider",
[WS_METHODS.providerConsumeResetCredit]: "provider",
diff --git a/apps/server/src/skills/SkillLibrary.test.ts b/apps/server/src/skills/SkillLibrary.test.ts
index 5294f3ccd7038..b6c9d2c3faa88 100644
--- a/apps/server/src/skills/SkillLibrary.test.ts
+++ b/apps/server/src/skills/SkillLibrary.test.ts
@@ -328,6 +328,90 @@ it.effect(
60_000,
);
+it.effect(
+ "copies a skill to another environment as files, with links for agents that need them",
+ () =>
+ withLibrary(({ library, home, project, providers }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ // On the first environment: a project skill with a script.
+ const folder = path.join(project, ".agents", "skills", "lint");
+ yield* fileSystem.makeDirectory(path.join(folder, "bin"), { recursive: true });
+ yield* fileSystem.writeFileString(path.join(folder, "SKILL.md"), SKILL("lint", "Lint."));
+ yield* fileSystem.writeFileString(path.join(folder, "bin", "run"), "#!/bin/sh\n");
+ yield* fileSystem.chmod(path.join(folder, "bin", "run"), 0o755);
+ yield* Ref.set(providers, [
+ {
+ ...claude,
+ workspaceSnapshots: [
+ {
+ cwd: project,
+ checkedAt: "2026-10-10T00:00:00Z",
+ slashCommands: [],
+ skills: [
+ {
+ name: "lint",
+ path: path.join(folder, "SKILL.md"),
+ scope: "project",
+ enabled: true,
+ },
+ ],
+ },
+ ],
+ },
+ ]);
+ const bundle = yield* library.exportSkill({
+ name: "lint",
+ target: { kind: "project", cwd: project },
+ });
+ assert.deepEqual(
+ bundle.files.map((file) => [file.path, file.executable]),
+ [
+ ["SKILL.md", false],
+ ["bin/run", true],
+ ],
+ );
+
+ // On the second environment (the same service here): a global copy.
+ yield* library.importSkill({ bundle, target: { kind: "environment" } });
+ const copied = path.join(home, ".agents", "skills", "lint");
+ assert.equal(
+ yield* fileSystem.readFileString(path.join(copied, "SKILL.md")),
+ SKILL("lint", "Lint."),
+ );
+ assert.equal(
+ ((yield* fileSystem.stat(path.join(copied, "bin", "run"))).mode & 0o111) !== 0,
+ true,
+ );
+ // Claude reads only `.claude/skills`, so it gets a link, as an install gives it.
+ assert.equal(
+ yield* fileSystem.readLink(path.join(home, ".claude", "skills", "lint")),
+ copied,
+ );
+
+ const again = yield* library
+ .importSkill({ bundle, target: { kind: "environment" } })
+ .pipe(Effect.flip);
+ assert.equal(again.reason, "exists");
+
+ const escape = yield* library
+ .importSkill({
+ bundle: {
+ folder: "evil",
+ files: [{ path: "../../outside", contents: "", executable: false }],
+ },
+ target: { kind: "environment" },
+ })
+ .pipe(Effect.flip);
+ assert.equal(escape.reason, "cliFailed");
+ assert.isFalse(yield* fileSystem.exists(path.join(home, ".agents", "outside")));
+ assert.isFalse(yield* fileSystem.exists(path.join(home, ".agents", "skills", "evil")));
+ }).pipe(Effect.provide(NodeServices.layer)),
+ ),
+ 60_000,
+);
+
it.effect(
"fails a removal the CLI couldn't finish, which it reports with a zero exit",
() =>
diff --git a/apps/server/src/skills/SkillLibrary.ts b/apps/server/src/skills/SkillLibrary.ts
index 088f9c7cad9ba..7eab8bb5bfabe 100644
--- a/apps/server/src/skills/SkillLibrary.ts
+++ b/apps/server/src/skills/SkillLibrary.ts
@@ -15,10 +15,15 @@
*/
import {
type InstalledSkillInput,
+ MAX_SKILL_BUNDLE_BYTES,
+ MAX_SKILL_BUNDLE_FILES,
type ProviderDriverKind,
type ServerProvider,
type SkillFileEntry,
+ type SkillBundle,
+ type SkillExportInput,
type SkillFolderInfo,
+ type SkillImportInput,
type SkillInspectInput,
type SkillInspectResult,
type SkillInstallInput,
@@ -31,6 +36,7 @@ import {
import {
STANDARD_SKILL_FOLDER,
agentSkillFolderRoots,
+ skillLinkFolders,
skillsCliInstallAgents,
} from "@t3tools/provider-core/server/AgentSkillFolders";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
@@ -38,6 +44,7 @@ import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
+import * as Base64 from "effect/encoding/Base64";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -72,6 +79,17 @@ export class SkillLibrary extends Context.Service<
* CLI when it installed the skill, else each folder's copy of that name.
*/
readonly remove: (input: InstalledSkillInput) => Effect.Effect;
+ /** Pack the folder an agent reports for a skill, to copy it to another environment. */
+ readonly exportSkill: (
+ input: SkillExportInput,
+ ) => Effect.Effect;
+ /**
+ * Put a copied skill in place. One the CLI installed from a remote source
+ * is installed from there again, so it can be updated; otherwise, or when
+ * that fails, its files go into `.agents/skills` with links for the agents
+ * that read their own folder, as an install would make.
+ */
+ readonly importSkill: (input: SkillImportInput) => Effect.Effect;
}
>()("t3/skills/SkillLibrary") {}
@@ -662,7 +680,180 @@ const make = Effect.gen(function* () {
yield* refreshAgents(target);
});
- return SkillLibrary.of({ inspect, preview, install, update, remove });
+ /**
+ * The folder an enabled agent reports for a skill in one of the level's
+ * agent skill folders, after links. Plugin and built-in skills aren't there.
+ */
+ const reportedFolder = (target: SkillInstallTarget, name: string) =>
+ Effect.gen(function* () {
+ const wanted = name.trim().toLowerCase();
+ const roots = yield* skillRoots(target);
+ for (const provider of yield* enabledProviders) {
+ const skills =
+ target.kind === "environment"
+ ? provider.skills
+ : (provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === target.cwd)
+ ?.skills ?? []);
+ for (const skill of skills) {
+ if (skill.name.trim().toLowerCase() !== wanted) continue;
+ if (!path.isAbsolute(skill.path) || path.basename(skill.path) !== "SKILL.md") continue;
+ const folder = path.dirname(skill.path);
+ const real = yield* realPath(folder);
+ if (roots.includes(path.dirname(folder)) || roots.includes(path.dirname(real)))
+ return real;
+ }
+ }
+ return yield* new SkillLibraryError({
+ reason: "notInstalled",
+ message: `No agent here reports a skill named ${name}.`,
+ });
+ });
+
+ const tooLarge = (message: string) => new SkillLibraryError({ reason: "tooLarge", message });
+
+ const exportSkill: SkillLibrary["Service"]["exportSkill"] = Effect.fn("SkillLibrary.exportSkill")(
+ function* (input) {
+ const target = yield* resolveTarget(input.target);
+ const folder = yield* reportedFolder(target, input.name);
+ const { files, truncated } = yield* listFiles(folder);
+ if (truncated || files.length > MAX_SKILL_BUNDLE_FILES) {
+ return yield* tooLarge(`${input.name} has too many files to copy.`);
+ }
+ let bytes = 0;
+ const bundled = yield* Effect.forEach(files, (file) =>
+ Effect.gen(function* () {
+ bytes += file.size;
+ if (bytes > MAX_SKILL_BUNDLE_BYTES) {
+ return yield* tooLarge(`${input.name} is too large to copy between environments.`);
+ }
+ const contents = yield* fileSystem
+ .readFile(path.join(folder, file.path))
+ .pipe(Effect.mapError(() => tooLarge(`Couldn't read ${file.path} in ${input.name}.`)));
+ return {
+ path: file.path,
+ contents: Base64.encode(contents),
+ executable: file.executable,
+ };
+ }),
+ );
+ // Links aren't followed by the walk, so a folder of only links has nothing to copy.
+ if (!bundled.some((file) => file.path === "SKILL.md")) {
+ return yield* tooLarge(`${input.name} has no SKILL.md to copy.`);
+ }
+ // A remote source the CLI recorded here lets the target install it properly.
+ const paths = targetPaths(target);
+ const locked =
+ path.dirname(folder) === (yield* realPath(paths.folder))
+ ? lockEntryFor(yield* readLock(paths.lock), path.basename(folder))
+ : undefined;
+ const remote =
+ locked !== undefined &&
+ locked.entry.sourceType !== "local" &&
+ locked.entry.sourceType !== "node_modules"
+ ? lockedInstallSource(locked.entry, target.kind === "environment" ? "home" : "project")
+ : null;
+ return {
+ folder: skillFolderName(path.basename(folder)),
+ files: bundled,
+ ...(remote === null || locked === undefined
+ ? {}
+ : { install: { source: remote.source, skill: locked.key, fullDepth: remote.fullDepth } }),
+ };
+ },
+ );
+
+ const importSkill: SkillLibrary["Service"]["importSkill"] = Effect.fn("SkillLibrary.importSkill")(
+ function* (input) {
+ const target = yield* resolveTarget(input.target);
+ yield* importLocked(target, input.bundle).pipe(changes.withPermits(1));
+ },
+ );
+
+ const importLocked = (target: SkillInstallTarget, bundle: SkillBundle) =>
+ Effect.gen(function* () {
+ const paths = targetPaths(target);
+ const folderName = skillFolderName(bundle.folder);
+ const destination = path.join(paths.folder, folderName);
+ const drivers = (yield* enabledProviders).map((provider) => provider.driver);
+ const links = skillLinkFolders(
+ drivers,
+ target.kind === "environment" ? "home" : "project",
+ ).map((folder) => path.join(paths.root, folder, folderName));
+ const taken = yield* Effect.filter([destination, ...links], (candidate) =>
+ fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false)),
+ );
+ if (taken.length > 0) {
+ return yield* new SkillLibraryError({
+ reason: "exists",
+ message: `A skill named ${bundle.folder} is already at ${taken[0]}.`,
+ });
+ }
+ if (bundle.install !== undefined) {
+ const installed = yield* installInto(
+ target,
+ bundle.install.source,
+ [bundle.install.skill],
+ bundle.install.fullDepth,
+ ).pipe(
+ Effect.map(
+ (result) =>
+ result.outcomes.length > 0 &&
+ result.outcomes.every((outcome) => outcome.status === "installed"),
+ ),
+ Effect.orElseSucceed(() => false),
+ );
+ if (installed) return;
+ // The source may be private or offline from here: the files still work.
+ yield* fileSystem.remove(destination, { recursive: true }).pipe(Effect.ignore);
+ }
+ const failed = (message: string) => cliFailed(message);
+ const write = Effect.gen(function* () {
+ let bytes = 0;
+ for (const file of bundle.files) {
+ // Bundles come from another environment: keep every path inside the folder.
+ const relative = path.normalize(file.path);
+ const absolute = path.resolve(destination, relative);
+ if (path.isAbsolute(relative) || !absolute.startsWith(destination + path.sep)) {
+ return yield* failed(`${file.path} isn't a path inside the skill.`);
+ }
+ const contents = Base64.decode(file.contents);
+ if (contents._tag === "Failure") return yield* failed(`${file.path} isn't valid base64.`);
+ bytes += contents.success.byteLength;
+ if (bytes > MAX_SKILL_BUNDLE_BYTES)
+ return yield* tooLarge(`${bundle.folder} is too large.`);
+ yield* fileSystem.makeDirectory(path.dirname(absolute), { recursive: true });
+ yield* fileSystem.writeFile(absolute, contents.success);
+ if (file.executable) yield* fileSystem.chmod(absolute, 0o755);
+ }
+ for (const link of links) {
+ yield* fileSystem.makeDirectory(path.dirname(link), { recursive: true });
+ yield* fileSystem.symlink(destination, link);
+ }
+ }).pipe(
+ Effect.catchTags({
+ PlatformError: (error) =>
+ Effect.fail(failed(`Couldn't write ${bundle.folder}: ${error.message}`)),
+ }),
+ // A half-written skill is worse than none.
+ Effect.onError(() =>
+ Effect.forEach([...links, destination], (leftover) =>
+ fileSystem.remove(leftover, { recursive: true }).pipe(Effect.ignore),
+ ),
+ ),
+ );
+ yield* write;
+ yield* refreshAgents(target);
+ });
+
+ return SkillLibrary.of({
+ inspect,
+ preview,
+ install,
+ update,
+ remove,
+ exportSkill,
+ importSkill,
+ });
});
export const layer = Layer.effect(SkillLibrary, make).pipe(Layer.provide(SkillsCli.layer));
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 5619ed6a8c099..5dc69c38fb1c3 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -2649,6 +2649,8 @@ const layerWsRpc = (
[WS_METHODS.skillsInstall]: (input) => skillLibrary.install(input),
[WS_METHODS.skillsUpdate]: (input) => skillLibrary.update(input),
[WS_METHODS.skillsRemove]: (input) => skillLibrary.remove(input).pipe(Effect.as({})),
+ [WS_METHODS.skillsExport]: (input) => skillLibrary.exportSkill(input),
+ [WS_METHODS.skillsImport]: (input) => skillLibrary.importSkill(input).pipe(Effect.as({})),
[WS_METHODS.projectsReadFile]: (input) =>
workspaceFileSystem.readFile(input).pipe(
Effect.mapError(
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
index 7847d89c7cc89..50f8f6f9ac41d 100644
--- a/apps/web/src/components/settings/SkillDetail.tsx
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -1,16 +1,19 @@
-import type { EnvironmentId } from "@t3tools/contracts";
+import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";
import { Check, Copy } from "lucide";
import { AlertTriangleIcon } from "lucide-react";
import { lazy, Suspense, useEffect, useEffectEvent, useState } from "react";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { MorphIcon } from "../MorphIcon";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
+import { Spinner } from "../ui/spinner";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SkillAgentIcon } from "./SkillAgents";
+import type { SkillEnvironment } from "./SkillEnvironments";
import {
skillConflict,
type SkillAgent,
@@ -58,17 +61,30 @@ export function SkillDetail({
details,
agents,
environmentId,
+ fleet,
onBack,
onUpdate,
onRemove,
+ onSync,
+ syncing,
}: {
row: SkillRow;
details: SkillRowDetails;
+ /** The agents on the environment whose copy is shown. */
agents: ReadonlyArray;
environmentId: EnvironmentId;
+ /** With several environments in scope: which have the skill, and whose copy shows. */
+ fleet?: {
+ readonly on: ReadonlyArray;
+ readonly environments: ReadonlyArray;
+ readonly shownFrom: EnvironmentId;
+ };
onBack: () => void;
onUpdate: (() => void) | null;
onRemove: (() => void) | null;
+ /** Copy the skill to the environments in scope that lack it. */
+ onSync: (() => void) | null;
+ syncing: boolean;
}) {
useEscapeToList(onBack);
const loads = new Set(row.providers.map((provider) => provider.instanceId));
@@ -127,6 +143,50 @@ export function SkillDetail({
) : null}
+ {fleet !== undefined ? (
+
+ On
+ {fleet.environments.map((environment) => {
+ const has = fleet.on.includes(environment.environmentId);
+ return (
+
+
+ }
+ >
+
+
+
+ {environment.label}
+
+
+ {!has
+ ? `${environment.label} doesn't have this skill.`
+ : environment.environmentId === fleet.shownFrom
+ ? `Showing ${environment.label}'s copy.`
+ : `${environment.label} has this skill.`}
+
+
+ );
+ })}
+
+ {onSync !== null || syncing ? (
+
+ {syncing ? : null}
+ Copy to{" "}
+ {fleet.environments
+ .filter((environment) => !fleet.on.includes(environment.environmentId))
+ .map((environment) => environment.label)
+ .join(", ")}
+
+ ) : null}
+
+ ) : null}
{conflict !== null || scripts.length > 0 || details.installed !== null ? (
{details.installed !== null ? (
diff --git a/apps/web/src/components/settings/SkillEnvironments.tsx b/apps/web/src/components/settings/SkillEnvironments.tsx
new file mode 100644
index 0000000000000..0ae024defb53d
--- /dev/null
+++ b/apps/web/src/components/settings/SkillEnvironments.tsx
@@ -0,0 +1,144 @@
+import {
+ type EnvironmentId,
+ resolveEnvironmentMachineKind,
+ type ServerConfig,
+ type SkillFolderInfo,
+} from "@t3tools/contracts";
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
+import { NetworkIcon } from "lucide-react";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/reactivity";
+import { useCallback, useContext, useMemo } from "react";
+
+import { serverEnvironment } from "../../state/server";
+import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+
+/** A connected environment the Skills tab reads, in the order rows prefer them. */
+export interface SkillEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly label: string;
+ readonly serverConfig: ServerConfig | null;
+ /** The project's checkout there, at project scope. */
+ readonly cwd: string | null;
+}
+
+const EMPTY: ReadonlyArray
= [];
+
+/**
+ * Each environment's provider list, read together. The lists already stream
+ * to the client with each environment's config, so this adds no requests.
+ * Keyed by the ids alone: they decide which atoms are read.
+ */
+const providersByEnvironment = Atom.family((key: string) =>
+ Atom.make((get) =>
+ (key === "" ? [] : (key.split(",") as EnvironmentId[])).map((environmentId) => ({
+ environmentId,
+ providers: get(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY,
+ })),
+ ).pipe(Atom.withLabel(`web:skill-environment-providers:${key}`)),
+);
+
+export function useEnvironmentProviders(environments: ReadonlyArray) {
+ return useAtomValue(
+ providersByEnvironment(environments.map((environment) => environment.environmentId).join(",")),
+ );
+}
+
+/** An environment and the checkout to inspect there, as a family key. */
+const folderKey = (environment: SkillEnvironment) =>
+ JSON.stringify([environment.environmentId, environment.cwd]);
+
+const inspectAtom = (key: string) => {
+ const [environmentId, cwd] = JSON.parse(key) as [EnvironmentId, string | null];
+ return serverEnvironment.inspectSkills({
+ environmentId,
+ input: cwd === null ? {} : { cwd },
+ });
+};
+
+const foldersByEnvironment = Atom.family((keys: string) =>
+ Atom.make((get) =>
+ (JSON.parse(keys) as string[]).map((key) => ({
+ environmentId: (JSON.parse(key) as [EnvironmentId])[0],
+ result: get(inspectAtom(key)),
+ })),
+ ).pipe(Atom.withLabel(`web:skill-environment-folders:${keys}`)),
+);
+
+/**
+ * Each environment's inspected skill folders, by the SKILL.md path its agents
+ * reported. Paths are per machine (two Macs share `/Users/me`), so they stay
+ * keyed by environment.
+ */
+export function useEnvironmentSkillFolders(environments: ReadonlyArray) {
+ const keys = JSON.stringify(environments.map(folderKey));
+ const results = useAtomValue(foldersByEnvironment(keys));
+ const registry = useContext(RegistryContext);
+ const refresh = useCallback(() => {
+ for (const key of JSON.parse(keys) as string[]) registry.refresh(inspectAtom(key));
+ }, [keys, registry]);
+ const folders = useMemo(
+ () =>
+ new Map(
+ results.map(({ environmentId, result }) => [
+ environmentId,
+ new Map(
+ (Option.getOrNull(AsyncResult.value(result))?.folders ?? []).map((folder) => [
+ folder.path,
+ folder,
+ ]),
+ ),
+ ]),
+ ),
+ [results],
+ );
+ return { folders, refresh };
+}
+
+/**
+ * Where a skill is, at a glance: a fleet mark when every environment listed
+ * has it, otherwise the machines that do.
+ */
+export function SkillEnvironmentMarks({
+ on,
+ environments,
+}: {
+ on: ReadonlyArray;
+ environments: ReadonlyArray;
+}) {
+ const present = environments.filter((environment) => on.includes(environment.environmentId));
+ const missing = environments.filter((environment) => !on.includes(environment.environmentId));
+ const label =
+ missing.length === 0
+ ? `On all ${environments.length} environments`
+ : `On ${present.map((environment) => environment.label).join(", ")}; not on ${missing
+ .map((environment) => environment.label)
+ .join(", ")}`;
+ return (
+
+
+ }
+ >
+ {missing.length === 0 ? (
+
+ ) : (
+ present.map((environment) => (
+
+ ))
+ )}
+
+ {label}
+
+ );
+}
diff --git a/apps/web/src/components/settings/SkillList.tsx b/apps/web/src/components/settings/SkillList.tsx
index 69c900075a988..fdfc1e661a4da 100644
--- a/apps/web/src/components/settings/SkillList.tsx
+++ b/apps/web/src/components/settings/SkillList.tsx
@@ -8,7 +8,9 @@ import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SettingsGroup } from "./SettingsGroup";
import { SkillAgents } from "./SkillAgents";
+import { type SkillEnvironment, SkillEnvironmentMarks } from "./SkillEnvironments";
import { TruncatedText } from "./TruncatedText";
+import type { EnvironmentId } from "@t3tools/contracts";
import {
SOURCE_GROUP_PREVIEW,
skillAvailability,
@@ -33,10 +35,14 @@ export interface SkillListRow {
readonly disabled: boolean;
/** The project switch differs from the environment's. */
readonly overridden: boolean;
+ /** With several environments in scope, the ones that have this skill. */
+ readonly on?: ReadonlyArray;
}
interface RowHandlers {
readonly agents: ReadonlyArray;
+ /** The environments in scope, when there are several. */
+ readonly environments: ReadonlyArray;
readonly canWrite: boolean;
readonly onToggle: (rows: ReadonlyArray, enabled: boolean) => void;
readonly onOpen: (name: string) => void;
@@ -45,6 +51,7 @@ interface RowHandlers {
const SkillListItem = memo(function SkillListItem({
item,
agents,
+ environments,
canWrite,
onToggle,
onOpen,
@@ -98,7 +105,11 @@ const SkillListItem = memo(function SkillListItem({
) : null}
-
+ {item.on !== undefined && environments.length > 1 ? (
+
+ ) : (
+
+ )}
= [];
+const EMPTY_FOLDERS: ReadonlyMap = new Map();
/** A scan that finishes sooner than this shows no placeholder at all. */
const SKELETON_DELAY_MS = 150;
@@ -219,12 +228,37 @@ function SkillsPanel({
openName: string | null;
onOpen: (name: string | null) => void;
}) {
- const { scope, target } = useSettingsScope();
+ const { scope, target, connectedEnvironments } = useSettingsScope();
const environmentId = target?.environmentId ?? null;
const targets = useToolsTargets();
const cwd = targets.find((candidate) => candidate.environmentId === environmentId)?.cwd ?? null;
+ // Every environment the scope covers, the representative one first: rows
+ // show its copy of a skill when it has one.
+ const environments = useMemo((): ReadonlyArray => {
+ const ordered = [
+ ...targets.filter((candidate) => candidate.environmentId === environmentId),
+ ...targets.filter((candidate) => candidate.environmentId !== environmentId),
+ ];
+ return ordered.flatMap((candidate) => {
+ const connected = connectedEnvironments.find(
+ (environment) => environment.environmentId === candidate.environmentId,
+ );
+ return connected === undefined
+ ? []
+ : [
+ {
+ environmentId: candidate.environmentId,
+ label: connected.label,
+ serverConfig: connected.serverConfig,
+ cwd: candidate.cwd,
+ },
+ ];
+ });
+ }, [connectedEnvironments, environmentId, targets]);
+ const fleet = environments.length > 1;
+ const environmentProviders = useEnvironmentProviders(environments);
const providers =
- useAtomValue(serverEnvironment.providersValueAtom(environmentId ?? ("" as EnvironmentId))) ??
+ environmentProviders.find((entry) => entry.environmentId === environmentId)?.providers ??
EMPTY_PROVIDERS;
const disabledSkills = useScopedSettings((settings) => settings.disabledSkills);
const canWrite = useScopedSettingsWriteAllowed();
@@ -235,10 +269,6 @@ function SkillsPanel({
const [query, setQuery] = useState("");
const [onlyAttention, setOnlyAttention] = useState(false);
const [refreshing, setRefreshing] = useState(false);
- const enabledProviders = useMemo(
- () => providers.filter((provider) => provider.enabled),
- [providers],
- );
const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
// Installs go to the checkout shown, or to the environment's home folders.
const installTarget: SkillInstallTarget | null =
@@ -250,28 +280,27 @@ function SkillsPanel({
: { kind: "project", cwd }
: { kind: "environment" };
const canInstall = useAtomValue(serverEnvironment.installSkills.permissionAtom(environmentId));
+ const installers = useEnvironmentsWithScope(environments, AuthProvidersManageScope);
+ const exportSkill = useAtomCommand(serverEnvironment.exportSkill, { reportFailure: false });
+ const importSkill = useAtomCommand(serverEnvironment.importSkill, { reportFailure: false });
+ const [syncing, setSyncing] = useState>(new Set());
const updateSkill = useAtomCommand(serverEnvironment.updateSkill, { reportFailure: false });
const removeSkill = useAtomCommand(serverEnvironment.removeSkill, { reportFailure: false });
const [adding, setAdding] = useState(false);
const [removingSkill, setRemovingSkill] = useState<{
readonly name: string;
- readonly target: SkillInstallTarget;
- /** The `skills` CLI installed it, so its lock entry goes too. */
+ /** Each environment's copy to remove. */
+ readonly inputs: ReadonlyArray<{
+ readonly environmentId: EnvironmentId;
+ readonly name: string;
+ readonly target: SkillInstallTarget;
+ }>;
+ /** The `skills` CLI installed the shown copy, so its lock entry goes too. */
readonly installed: boolean;
} | null>(null);
const [skillActionError, setSkillActionError] = useState(null);
- const inspected = useEnvironmentQuery(
- environmentId === null
- ? null
- : serverEnvironment.inspectSkills({
- environmentId,
- input: cwd === null ? {} : { cwd },
- }),
- );
- const foldersByPath = useMemo(
- () => new Map((inspected.data?.folders ?? []).map((folder) => [folder.path, folder])),
- [inspected.data],
- );
+ const inspected = useEnvironmentSkillFolders(environments);
+ const foldersOf = (id: EnvironmentId) => inspected.folders.get(id) ?? EMPTY_FOLDERS;
const scopeLabel = isProjectScope
? scope.kind === "project" || scope.kind === "checkout"
? scope.group.displayName
@@ -280,20 +309,29 @@ function SkillsPanel({
? scope.label
: "this environment";
+ // Rescans every environment in scope; a project's checkout is only scanned
+ // when asked, as the composer does before showing its skill menu.
const refresh = async (fresh: boolean) => {
- if (environmentId === null) return;
+ if (environments.length === 0) return;
setRefreshing(true);
try {
await Promise.all(
- enabledProviders.map((provider) =>
- refreshProviders({
- environmentId,
- input: {
- instanceId: provider.instanceId,
- ...(cwd === null ? {} : { cwd }),
- ...(fresh ? { fresh: true } : {}),
- },
- }),
+ environments.flatMap((environment) =>
+ (
+ environmentProviders.find((entry) => entry.environmentId === environment.environmentId)
+ ?.providers ?? EMPTY_PROVIDERS
+ )
+ .filter((provider) => provider.enabled)
+ .map((provider) =>
+ refreshProviders({
+ environmentId: environment.environmentId,
+ input: {
+ instanceId: provider.instanceId,
+ ...(environment.cwd === null ? {} : { cwd: environment.cwd }),
+ ...(fresh ? { fresh: true } : {}),
+ },
+ }),
+ ),
),
);
} finally {
@@ -306,48 +344,106 @@ function SkillsPanel({
inspected.refresh();
};
+ /** A skill's level on one environment: where it lives there, to update or remove it. */
+ type SkillAction = {
+ readonly environmentId: EnvironmentId;
+ readonly name: string;
+ readonly target: SkillInstallTarget;
+ };
+
const runSkillAction = async (
action: "update" | "remove",
- input: { readonly name: string; readonly target: SkillInstallTarget },
+ inputs: ReadonlyArray,
) => {
- if (environmentId === null) return;
setSkillActionError(null);
- const failure = async () => {
- if (action === "remove") {
- const result = await removeSkill({ environmentId, input });
- return result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null;
- }
- const result = await updateSkill({ environmentId, input });
- if (result._tag === "Failure") return formatEnvironmentQueryError(result.cause);
- // The CLI reports a skill it couldn't reinstall as a result, not an error.
- const failed = result.value.outcomes.find((outcome) => outcome.status !== "installed");
- return failed === undefined ? null : (failed.error ?? failed.status);
- };
- const message = await failure();
+ const failures = await Promise.all(
+ inputs.map(async ({ environmentId: id, ...input }) => {
+ const label = environmentLabel(id);
+ if (action === "remove") {
+ const result = await removeSkill({ environmentId: id, input });
+ return result._tag === "Failure"
+ ? `${label}: ${formatEnvironmentQueryError(result.cause)}`
+ : null;
+ }
+ const result = await updateSkill({ environmentId: id, input });
+ if (result._tag === "Failure")
+ return `${label}: ${formatEnvironmentQueryError(result.cause)}`;
+ // The CLI reports a skill it couldn't reinstall as a result, not an error.
+ const failed = result.value.outcomes.find((outcome) => outcome.status !== "installed");
+ return failed === undefined ? null : `${label}: ${failed.error ?? failed.status}`;
+ }),
+ );
afterSkillChange();
- if (message !== null) setSkillActionError(`Couldn't ${action} ${input.name}: ${message}`);
+ const messages = failures.filter((message) => message !== null);
+ if (messages.length > 0) {
+ setSkillActionError(
+ `Couldn't ${action} ${inputs[0]?.name ?? "the skill"}. ${messages.join(" ")}`,
+ );
+ }
};
- // A project's skills live in its checkout, which each provider only scans
- // when asked; the composer does the same before showing its skill menu.
- // Keyed on the checkout and provider set, not on every status push, which
- // would rescan each time the scan's own result arrives.
- const scanKey = `${environmentId}:${cwd}:${enabledProviders.map((provider) => provider.instanceId).join(",")}`;
+ const scanKey = `${environments.map((environment) => `${environment.environmentId}:${environment.cwd ?? ""}`).join(",")}:${environmentProviders
+ .flatMap((entry) => entry.providers.filter((provider) => provider.enabled))
+ .map((provider) => provider.instanceId)
+ .join(",")}`;
const scannedKeyRef = useRef(null);
useEffect(() => {
- if (cwd === null || scannedKeyRef.current === scanKey) return;
+ if (!environments.some((environment) => environment.cwd !== null)) return;
+ if (scannedKeyRef.current === scanKey) return;
scannedKeyRef.current = scanKey;
void refresh(false);
- }, [cwd, refresh, scanKey]);
+ }, [environments, refresh, scanKey]);
+
+ const environmentLabel = (id: EnvironmentId) =>
+ environments.find((environment) => environment.environmentId === id)?.label ?? "Environment";
- const rows = useMemo(() => collectSkillRows(providers, cwd), [cwd, providers]);
+ // Each environment's rows, merged by name: a row shows the first copy found.
+ const fleetRows = useMemo(
+ () =>
+ mergeEnvironmentSkillRows(
+ environments.map((environment) => ({
+ environmentId: environment.environmentId,
+ rows: collectSkillRows(
+ environmentProviders.find((entry) => entry.environmentId === environment.environmentId)
+ ?.providers ?? EMPTY_PROVIDERS,
+ environment.cwd,
+ ),
+ })),
+ ),
+ [environmentProviders, environments],
+ );
+ const fleetByName = useMemo(
+ () => new Map(fleetRows.map((entry) => [entry.row.name, entry])),
+ [fleetRows],
+ );
+ const rows = useMemo(() => fleetRows.map((entry) => entry.row), [fleetRows]);
+ // Agents on the environment whose copy a row shows.
+ const agentsByEnvironment = useMemo(
+ () =>
+ new Map(
+ environmentProviders.map((entry) => [entry.environmentId, skillAgents(entry.providers)]),
+ ),
+ [environmentProviders],
+ );
const agents = useMemo(() => skillAgents(providers), [providers]);
+ const fleetOf = (row: SkillRow): FleetSkillRow =>
+ fleetByName.get(row.name) ?? {
+ row,
+ environmentId: environmentId ?? ("" as EnvironmentId),
+ on: [],
+ };
const detailsByName = useMemo(
- () => new Map(rows.map((row) => [row.name, skillRowDetails(row, foldersByPath)])),
- [foldersByPath, rows],
+ () =>
+ new Map(
+ fleetRows.map((entry) => [
+ entry.row.name,
+ skillRowDetails(entry.row, inspected.folders.get(entry.environmentId) ?? EMPTY_FOLDERS),
+ ]),
+ ),
+ [fleetRows, inspected.folders],
);
const detailsOf = (row: SkillRow) =>
- detailsByName.get(row.name) ?? skillRowDetails(row, foldersByPath);
+ detailsByName.get(row.name) ?? skillRowDetails(row, foldersOf(fleetOf(row).environmentId));
const attentionNames = useMemo(
() =>
new Set(
@@ -391,25 +487,108 @@ function SkillsPanel({
name,
),
);
+
+ /**
+ * The environments in scope that lack a skill and can take a copy of it:
+ * the user's own skills only, onto environments that let this client
+ * manage providers.
+ */
+ const syncTargetsOf = (row: SkillRow) => {
+ if (!fleet || (row.group !== "project" && row.group !== "personal")) return [];
+ const { on } = fleetOf(row);
+ return environments.filter(
+ (environment) =>
+ !on.includes(environment.environmentId) &&
+ installers.has(environment.environmentId) &&
+ (row.group === "personal" || environment.cwd !== null),
+ );
+ };
+ const syncOf = (row: SkillRow) => {
+ const missing = syncTargetsOf(row);
+ const { environmentId: from } = fleetOf(row);
+ const removable = detailsOf(row).removable;
+ if (missing.length === 0 || removable === null || syncing.has(row.name)) return null;
+ return () => void syncSkill(row.name, from, removable, missing);
+ };
+ const syncSkill = async (
+ name: string,
+ from: EnvironmentId,
+ level: SkillInstallTarget,
+ to: ReadonlyArray,
+ ) => {
+ setSkillActionError(null);
+ setSyncing((current) => new Set([...current, name]));
+ try {
+ const bundle = await exportSkill({ environmentId: from, input: { name, target: level } });
+ if (bundle._tag === "Failure") {
+ setSkillActionError(
+ `Couldn't copy ${name} from ${environmentLabel(from)}: ${formatEnvironmentQueryError(bundle.cause)}`,
+ );
+ return;
+ }
+ const failures = await Promise.all(
+ to.map(async (environment) => {
+ const result = await importSkill({
+ environmentId: environment.environmentId,
+ input: {
+ bundle: bundle.value,
+ // Project skills go into the project's checkout on each environment.
+ target:
+ level.kind === "project" && environment.cwd !== null
+ ? { kind: "project", cwd: environment.cwd }
+ : { kind: "environment" },
+ },
+ });
+ return result._tag === "Failure"
+ ? `${environment.label}: ${formatEnvironmentQueryError(result.cause)}`
+ : null;
+ }),
+ );
+ const messages = failures.filter((message) => message !== null);
+ if (messages.length > 0) setSkillActionError(`Couldn't copy ${name}. ${messages.join(" ")}`);
+ } finally {
+ setSyncing((current) => {
+ const next = new Set(current);
+ next.delete(name);
+ return next;
+ });
+ afterSkillChange();
+ }
+ };
+
+ /** Update and remove reach every environment in scope that has the skill. */
+ const actionTargetsOf = (row: SkillRow, kind: "update" | "remove"): ReadonlyArray =>
+ fleetOf(row).on.flatMap((id) => {
+ if (!installers.has(id)) return [];
+ const environmentRow = collectSkillRows(
+ environmentProviders.find((entry) => entry.environmentId === id)?.providers ??
+ EMPTY_PROVIDERS,
+ environments.find((environment) => environment.environmentId === id)?.cwd ?? null,
+ ).find((candidate) => candidate.name.toLowerCase() === row.name.toLowerCase());
+ if (environmentRow === undefined) return [];
+ const details = skillRowDetails(environmentRow, foldersOf(id));
+ const level = kind === "update" ? details.installed?.target : details.removable;
+ return level === undefined || level === null
+ ? []
+ : [{ environmentId: id, name: environmentRow.name, target: level }];
+ });
+ const updateOf = (row: SkillRow) => {
+ const inputs = actionTargetsOf(row, "update");
+ return inputs.length === 0 ? null : () => void runSkillAction("update", inputs);
+ };
+ const removeOf = (row: SkillRow) => {
+ const inputs = actionTargetsOf(row, "remove");
+ if (inputs.length === 0) return null;
+ const installed = detailsOf(row).installed !== null;
+ return () => setRemovingSkill({ name: row.name, inputs, installed });
+ };
const listItem = (row: SkillRow): SkillListRow => ({
row,
details: detailsOf(row),
disabled: isSkillDisabled(disabledSkills, row.name),
overridden: projectOverrides(row.name),
+ ...(fleet ? { on: fleetOf(row).on } : {}),
});
- const updateOf = (row: SkillRow) => {
- const installed = detailsOf(row).installed;
- return installed === null || !canInstall
- ? null
- : () => void runSkillAction("update", { name: row.name, target: installed.target });
- };
- const removeOf = (row: SkillRow) => {
- const { installed, removable } = detailsOf(row);
- return removable === null || !canInstall
- ? null
- : () =>
- setRemovingSkill({ name: row.name, target: removable, installed: installed !== null });
- };
const opened = openName === null ? null : (rows.find((row) => row.name === openName) ?? null);
const showSkeleton = useAfterDelay(rows.length === 0 && refreshing, SKELETON_DELAY_MS);
@@ -421,11 +600,22 @@ function SkillsPanel({
key={opened.name}
row={opened}
details={detailsOf(opened)}
- agents={agents}
- environmentId={environmentId}
+ agents={agentsByEnvironment.get(fleetOf(opened).environmentId) ?? agents}
+ environmentId={fleetOf(opened).environmentId}
+ {...(fleet
+ ? {
+ fleet: {
+ on: fleetOf(opened).on,
+ environments,
+ shownFrom: fleetOf(opened).environmentId,
+ },
+ }
+ : {})}
onBack={() => onOpen(null)}
onUpdate={updateOf(opened)}
onRemove={removeOf(opened)}
+ onSync={syncOf(opened)}
+ syncing={syncing.has(opened.name)}
/>
) : openName !== null ? (
// A link or Back to a skill that isn't here (yet, or any more).
@@ -541,6 +731,7 @@ function SkillsPanel({
)}
emptyText="No matching skills."
agents={agents}
+ environments={environments}
canWrite={canWrite}
onToggle={(skillRows, enabled) => setSkillsDisabled(skillRows, !enabled)}
onOpen={onOpen}
@@ -574,15 +765,19 @@ function SkillsPanel({
{removingSkill?.installed ? (
<>
Deletes the skill's folder and every agent's link to it, as{" "}
- npx skills remove does.
+ npx skills remove does
>
) : (
- `Deletes ${removingSkill?.name ?? "the skill"} from every agent's skill folder ${
- removingSkill?.target.kind === "project"
- ? "in this project"
- : "on this environment"
- }. It wasn't installed from a source, so it can't be added back from here.`
+ `Deletes ${removingSkill?.name ?? "the skill"} from every agent's skill folder`
)}
+ {removingSkill !== null && removingSkill.inputs.length > 1
+ ? ` on ${removingSkill.inputs.map((input) => environmentLabel(input.environmentId)).join(", ")}.`
+ : removingSkill?.inputs[0]?.target.kind === "project"
+ ? " in this project."
+ : " on this environment."}
+ {removingSkill?.installed
+ ? ""
+ : " It wasn't installed from a source, so it can't be added back from here."}
@@ -591,10 +786,7 @@ function SkillsPanel({
variant="destructive"
onClick={() => {
if (removingSkill) {
- void runSkillAction("remove", {
- name: removingSkill.name,
- target: removingSkill.target,
- });
+ void runSkillAction("remove", removingSkill.inputs);
if (removingSkill.name === openName) onOpen(null);
}
setRemovingSkill(null);
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index 03644a2557f01..ba8a32a18bf48 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -1,4 +1,5 @@
import {
+ EnvironmentId,
ProviderDriverKind,
ProviderInstanceId,
type McpServerConfig,
@@ -9,6 +10,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
collectSkillRows,
listMcpServerRows,
+ mergeEnvironmentSkillRows,
mcpServerDraftFrom,
mcpServerFromDraft,
parseArgs,
@@ -146,6 +148,34 @@ describe("collectSkillRows", () => {
});
});
+describe("mergeEnvironmentSkillRows", () => {
+ const skillRow = (name: string, group: SkillRow["group"] = "personal"): SkillRow => ({
+ name,
+ description: undefined,
+ group,
+ paths: [`/h/.agents/skills/${name}/SKILL.md`],
+ providers: [],
+ disabledByProvider: false,
+ });
+ const mac = EnvironmentId.make("mac");
+ const nucbox = EnvironmentId.make("nucbox");
+
+ it("lists each skill once, shown from the first environment that has it", () => {
+ const merged = mergeEnvironmentSkillRows([
+ { environmentId: mac, rows: [skillRow("review"), skillRow("Notes")] },
+ {
+ environmentId: nucbox,
+ rows: [skillRow("notes"), skillRow("deploy"), skillRow("docs", "plugin")],
+ },
+ ]);
+ expect(merged.map((entry) => [entry.row.name, entry.environmentId, entry.on])).toEqual([
+ ["deploy", nucbox, [nucbox]],
+ ["Notes", mac, [mac, nucbox]],
+ ["review", mac, [mac]],
+ ]);
+ });
+});
+
describe("skill row details", () => {
const row = (paths: ReadonlyArray): SkillRow => ({
name: "review",
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 8b302f3a7875d..1d6dab1fbc08c 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -1,4 +1,5 @@
import {
+ type EnvironmentId,
isValidMcpServerName,
type McpServerConfig,
type McpServerProjectOverride,
@@ -170,6 +171,61 @@ export function collectSkillRows(
);
}
+/** One environment's skill rows, from that environment's providers and checkout. */
+export interface EnvironmentSkillRows {
+ readonly environmentId: EnvironmentId;
+ readonly rows: ReadonlyArray;
+}
+
+/** A skill row across environments: shown from one of them, present on some. */
+export interface FleetSkillRow {
+ readonly row: SkillRow;
+ /** The environment whose copy the row, its details and its page show. */
+ readonly environmentId: EnvironmentId;
+ /** Every listed environment that has a skill by this name, in list order. */
+ readonly on: ReadonlyArray;
+}
+
+/**
+ * Merge each environment's rows by skill name. A row shows the copy on the
+ * first environment listed that has it, so the primary environment goes
+ * first; `on` says where else the name is. Plugin and built-in skills belong
+ * to their agents, so only the first environment's are kept.
+ */
+export function mergeEnvironmentSkillRows(
+ environments: ReadonlyArray,
+): ReadonlyArray {
+ const byName = new Map<
+ string,
+ { row: SkillRow; environmentId: EnvironmentId; on: EnvironmentId[] }
+ >();
+ for (const [index, { environmentId, rows }] of environments.entries()) {
+ for (const row of rows) {
+ const own = row.group === "project" || row.group === "personal";
+ if (!own && index > 0) continue;
+ const key = row.name.toLowerCase();
+ const existing = byName.get(key);
+ if (existing === undefined) {
+ byName.set(key, { row, environmentId, on: [environmentId] });
+ } else if (!existing.on.includes(environmentId)) {
+ existing.on.push(environmentId);
+ }
+ }
+ }
+ const order = environments.map((environment) => environment.environmentId);
+ return [...byName.values()]
+ .map(({ row, environmentId, on }) => ({
+ row,
+ environmentId,
+ on: on.toSorted((left, right) => order.indexOf(left) - order.indexOf(right)),
+ }))
+ .toSorted(
+ (left, right) =>
+ GROUP_ORDER.indexOf(left.row.group) - GROUP_ORDER.indexOf(right.row.group) ||
+ left.row.name.localeCompare(right.row.name),
+ );
+}
+
export function groupSkillRows(
rows: ReadonlyArray,
): ReadonlyArray<{ readonly group: SkillGroupKind; readonly rows: ReadonlyArray }> {
diff --git a/docs/user/tools.md b/docs/user/tools.md
index 726f4dc07dffd..c779cdc22a57d 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -34,6 +34,11 @@ With a project selected, skills go into the project's `.agents/skills` folder an
`skills-lock.json`, which you can commit for your team. Otherwise they go into `~/.agents/skills`
for every project. Agents that only read their own folder, such as Claude, get a link to the skill.
+With **All environments** selected, the list shows the skills on every connected environment. Each
+row shows the machines that have the skill, or one mark when they all do, and a skill's page can
+**Copy to** the environments missing it. A copy reinstalls from the skill's source when it has one
+the other machine can reach, so it can be updated there too, and otherwise copies the files.
+
Skills installed this way, here or with `npx skills` in a terminal, are grouped by where they came
from, with one switch for the group. Their page has **Update**, which installs the latest version
from the same source, and **Remove**. Other skills in your own skill folders, such as
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index aabc46cf1be1d..ac7fa8b781482 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1202,6 +1202,15 @@ export function createServerEnvironmentAtoms(
tag: WS_METHODS.skillsRemove,
concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
}),
+ exportSkill: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:skills:export",
+ tag: WS_METHODS.skillsExport,
+ }),
+ importSkill: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:skills:import",
+ tag: WS_METHODS.skillsImport,
+ concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
+ }),
updateProvider: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:update-provider",
tag: WS_METHODS.serverUpdateProvider,
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 90fb22d6b1e20..cf9b6c01c4035 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -40,6 +40,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.skillsInstall]: AuthProvidersManageScope,
[WS_METHODS.skillsUpdate]: AuthProvidersManageScope,
[WS_METHODS.skillsRemove]: AuthProvidersManageScope,
+ [WS_METHODS.skillsImport]: AuthProvidersManageScope,
[WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope,
[WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 6002cebbdcafe..b8b5989659668 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -150,6 +150,9 @@ import {
import { KeybindingsConfigError } from "./keybindings.ts";
import {
InstalledSkillInput,
+ SkillBundle,
+ SkillExportInput,
+ SkillImportInput,
SkillInspectInput,
SkillInspectResult,
SkillInstallInput,
@@ -477,6 +480,8 @@ export const WS_METHODS = {
skillsInstall: "skills.install",
skillsUpdate: "skills.update",
skillsRemove: "skills.remove",
+ skillsExport: "skills.export",
+ skillsImport: "skills.import",
serverUpdateProvider: "server.updateProvider",
serverUpdateServer: "server.updateServer",
serverUpdateServerWithProgress: "server.updateServerWithProgress",
@@ -630,6 +635,18 @@ const WsSkillsRemoveRpc = Rpc.make(WS_METHODS.skillsRemove, {
error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
});
+const WsSkillsExportRpc = Rpc.make(WS_METHODS.skillsExport, {
+ payload: SkillExportInput,
+ success: SkillBundle,
+ error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
+});
+
+const WsSkillsImportRpc = Rpc.make(WS_METHODS.skillsImport, {
+ payload: SkillImportInput,
+ success: Schema.Struct({}),
+ error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
+});
+
const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {
payload: Schema.Struct({}),
success: ServerConfig,
@@ -1862,6 +1879,8 @@ export const WsRpcGroup = RpcGroup.make(
WsSkillsInstallRpc,
WsSkillsUpdateRpc,
WsSkillsRemoveRpc,
+ WsSkillsExportRpc,
+ WsSkillsImportRpc,
WsServerUpdateProviderRpc,
WsProviderConsumeResetCreditRpc,
WsProviderAuthStartRpc,
diff --git a/packages/contracts/src/skills.ts b/packages/contracts/src/skills.ts
index d7b8f4db8bde4..657b979634f1b 100644
--- a/packages/contracts/src/skills.ts
+++ b/packages/contracts/src/skills.ts
@@ -104,6 +104,54 @@ export type SkillInstallOutcome = typeof SkillInstallOutcome.Type;
export const SkillInstallResult = Schema.Struct({ outcomes: Schema.Array(SkillInstallOutcome) });
export type SkillInstallResult = typeof SkillInstallResult.Type;
+/**
+ * Copying a skill to another environment: the source environment packs the
+ * folder an agent found it in, the client hands the bundle to each target.
+ * Bounded, since the bundle crosses the WebSocket whole.
+ */
+export const MAX_SKILL_BUNDLE_BYTES = 4 * 1024 * 1024;
+export const MAX_SKILL_BUNDLE_FILES = 500;
+
+export const SkillBundleFile = Schema.Struct({
+ /** Relative to the skill's folder, with `/` separators. */
+ path: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)),
+ /** The file's bytes as base64. */
+ contents: Schema.String,
+ executable: Schema.Boolean,
+});
+export type SkillBundleFile = typeof SkillBundleFile.Type;
+
+export const SkillBundle = Schema.Struct({
+ /** The folder name the skill is invoked by. */
+ folder: InstalledSkillName,
+ files: Schema.Array(SkillBundleFile).check(
+ Schema.isMinLength(1),
+ Schema.isMaxLength(MAX_SKILL_BUNDLE_FILES),
+ ),
+ /**
+ * Set when the `skills` CLI installed the skill from a remote source: the
+ * target reinstalls from there, so the copy can be updated too, and falls
+ * back to the files when that fails.
+ */
+ install: Schema.optional(
+ Schema.Struct({ source: SkillSource, skill: InstalledSkillName, fullDepth: Schema.Boolean }),
+ ),
+});
+export type SkillBundle = typeof SkillBundle.Type;
+
+/** A skill an agent reports on this environment, by name, at the level it lives. */
+export const SkillExportInput = Schema.Struct({
+ name: InstalledSkillName,
+ target: SkillInstallTarget,
+});
+export type SkillExportInput = typeof SkillExportInput.Type;
+
+export const SkillImportInput = Schema.Struct({
+ bundle: SkillBundle,
+ target: SkillInstallTarget,
+});
+export type SkillImportInput = typeof SkillImportInput.Type;
+
export const SkillInspectInput = Schema.Struct({
/** A project checkout whose skills are inspected besides the environment's. */
cwd: Schema.optional(TrimmedNonEmptyString),
@@ -160,6 +208,10 @@ export class SkillLibraryError extends Schema.TaggedError()(
* entry), and remove a skill in the agents' skill folders at that level.
*/
"notInstalled",
+ /** A skill to copy is bigger than a bundle may be, or its folder can't be read. */
+ "tooLarge",
+ /** A skill with that name is already at the target. */
+ "exists",
]),
message: Schema.String,
},
diff --git a/packages/provider-core/src/server/AgentSkillFolders.ts b/packages/provider-core/src/server/AgentSkillFolders.ts
index d315ea26ad633..26a350d100409 100644
--- a/packages/provider-core/src/server/AgentSkillFolders.ts
+++ b/packages/provider-core/src/server/AgentSkillFolders.ts
@@ -88,6 +88,32 @@ export function agentSkillFolderRoots(level: "home" | "project"): ReadonlyArray<
];
}
+/**
+ * Where each `skills` CLI agent links an install, by level, as its
+ * `src/agents.ts` does; `universal` writes `.agents/skills` itself.
+ */
+const CLI_AGENT_LINK_FOLDERS: Readonly<
+ Record
+> = {
+ "claude-code": { home: ".claude/skills", project: ".claude/skills" },
+ grok: { project: ".grok/skills" },
+ "antigravity-cli": { home: ".gemini/antigravity-cli/skills" },
+};
+
+/**
+ * The folders a skill copied into `.agents/skills` by hand needs links in, so
+ * every listed driver sees it: the ones a `skills` CLI install would link.
+ */
+export function skillLinkFolders(
+ drivers: ReadonlyArray,
+ level: "home" | "project",
+): ReadonlyArray {
+ return skillsCliInstallAgents(drivers, level).flatMap((agent) => {
+ const folder = CLI_AGENT_LINK_FOLDERS[agent]?.[level];
+ return folder === undefined ? [] : [folder];
+ });
+}
+
/**
* The `skills` CLI agents an install names so every listed driver can use the
* skill: `universal` writes `.agents/skills`, and each driver that doesn't read
From 6a482469bed0071fcb949008fb83ad1be2828b28 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sun, 11 Oct 2026 02:04:32 -0700
Subject: [PATCH 33/35] =?UTF-8?q?feat(server):=20list=20an=20MCP=20server'?=
=?UTF-8?q?s=20tools=20from=20Settings=20=E2=86=92=20Tools?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Settings → Tools listed MCP servers but couldn't show what each one offers.
`mcpServers.listTools` starts the named server the way an agent session
would, with the project's overrides and the stored secrets, asks it for
`tools/list` (following cursors), and stops it again, within 30 seconds.
Command servers run in the project's checkout with the host environment
under their own variables; URL servers fall back to SSE on a 404/405.
Failures come back as a typed McpServerToolsError with a plain message.
T3's own `t3-code` server is described from the toolkits `/mcp` registers,
without starting anything; a registration test keeps that list in step.
Listing runs the server's command with its secrets, so it needs
`providers:manage`, the scope that gates adding that command.
Co-Authored-By: Claude Opus 5.5
---
apps/server/package.json | 2 +-
apps/server/src/auth/RpcAuthorization.ts | 4 +
apps/server/src/mcp/McpHttpServer.ts | 22 ++
.../toolkits/worktree/registration.test.ts | 8 +
.../src/mcpServers/McpServerTools.test.ts | 203 ++++++++++
apps/server/src/mcpServers/McpServerTools.ts | 354 ++++++++++++++++++
.../testFixtures/two-tool-mcp-server.mjs | 72 ++++
.../src/observability/RpcInstrumentation.ts | 1 +
apps/server/src/server.ts | 2 +
apps/server/src/ws.ts | 3 +
packages/client-runtime/src/state/server.ts | 7 +
packages/contracts/src/agentTools.ts | 91 ++++-
packages/contracts/src/rpc.ts | 9 +
pnpm-lock.yaml | 6 +-
14 files changed, 778 insertions(+), 6 deletions(-)
create mode 100644 apps/server/src/mcpServers/McpServerTools.test.ts
create mode 100644 apps/server/src/mcpServers/McpServerTools.ts
create mode 100644 apps/server/src/mcpServers/testFixtures/two-tool-mcp-server.mjs
diff --git a/apps/server/package.json b/apps/server/package.json
index b3dbc1f9a157b..7e8f6c5d337cf 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -34,6 +34,7 @@
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
"@ff-labs/fff-node": "0.9.4",
+ "@modelcontextprotocol/sdk": "1.29.0",
"@muse-code/sdk": "1.4.2",
"@napi-rs/keyring": "^1.3.0",
"@opencode-ai/sdk": "^1.3.15",
@@ -59,7 +60,6 @@
},
"devDependencies": {
"@effect/vitest": "catalog:",
- "@modelcontextprotocol/sdk": "1.29.0",
"@t3tools/contracts": "workspace:*",
"@t3tools/provider-testing": "workspace:*",
"@t3tools/shared": "workspace:*",
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 1446b240d52cb..139041c006cc5 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -148,6 +148,10 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.skillsPreview]: AuthFilesystemReadScope,
// Packs a folder an agent reports for that skill, nothing a client names.
[WS_METHODS.skillsExport]: AuthFilesystemReadScope,
+ // Listing a server's tools runs its command with its stored secrets, which
+ // only a connection allowed to add that command may do. A read the client
+ // caches as a query, so the client checks the scope itself (no guard entry).
+ [WS_METHODS.mcpServersListTools]: AuthProvidersManageScope,
[WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
[WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts
index d22a48d0e6b6e..3a4223b827567 100644
--- a/apps/server/src/mcp/McpHttpServer.ts
+++ b/apps/server/src/mcp/McpHttpServer.ts
@@ -854,6 +854,28 @@ export const layerMcpTransport = McpServer.layerHttp({
protocols: [McpProtocol.v2025_06_18],
}).pipe(Layer.provide(layerMcpAuthMiddleware));
+/**
+ * Every tool `layer` registers, for describing `t3-code` without a session
+ * (Settings → Tools). Add a toolkit here when you register one below.
+ */
+export const T3_MCP_TOOLKITS: ReadonlyArray = [
+ PreviewStandardToolkit,
+ PreviewSnapshotToolkit,
+ OrchestratorToolkit,
+ ThreadToolkit,
+ AttachmentToolkit,
+ ProjectToolkit,
+ EnvironmentToolkit,
+ ToolsToolkit,
+ PreviewControlsToolkit,
+ WorktreeToolkit,
+ PullRequestsToolkit,
+ DeviceStandardToolkit,
+ DeviceScreenshotToolkit,
+ HtmlRenderToolkit,
+ HtmlPreviewToolkit,
+];
+
export const layer = Layer.mergeAll(
layerPreviewToolkit,
layerOrchestratorToolkit,
diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts
index 588d11d9c7152..0bdea8c4755b8 100644
--- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts
+++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts
@@ -127,6 +127,14 @@ it.effect("production mcp layer lists worktree tools over http", () =>
// than replacing them.
expect(toolNames).toContain("preview_status");
expect(toolNames).toContain("delegate_task");
+ // Settings → Tools describes t3-code from this list without a session.
+ expect(
+ new Set(
+ McpHttpServer.T3_MCP_TOOLKITS.flatMap((toolkit) =>
+ Object.values(toolkit.tools).map((tool) => tool.name),
+ ),
+ ),
+ ).toEqual(new Set(toolNames));
// The handoff tool mutates thread state, reaches the network (origin
// fetch), and runs project setup scripts, so its MCP hints must not
diff --git a/apps/server/src/mcpServers/McpServerTools.test.ts b/apps/server/src/mcpServers/McpServerTools.test.ts
new file mode 100644
index 0000000000000..eb428d720c495
--- /dev/null
+++ b/apps/server/src/mcpServers/McpServerTools.test.ts
@@ -0,0 +1,203 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, expect, it } from "@effect/vitest";
+import { type McpServerConfig, ProjectId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+
+import * as ProjectService from "../project/ProjectService.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as McpServerTools from "./McpServerTools.ts";
+
+const fixture = new URL("./testFixtures/two-tool-mcp-server.mjs", import.meta.url).pathname;
+
+const stdioServer = (
+ args: ReadonlyArray,
+ env: ReadonlyArray<{ readonly name: string; readonly value: string }> = [],
+): McpServerConfig => ({
+ enabled: true,
+ transport: {
+ type: "stdio",
+ command: process.execPath,
+ args: [...args],
+ env: env.map((variable) => ({ ...variable, sensitive: false })),
+ },
+});
+
+/** One registered project, checked out at `projectRoot`. */
+const projects = (projectRoot: string | null) =>
+ Layer.mock(ProjectService.ProjectService)({
+ getByWorkspaceRoot: (root: string) =>
+ Effect.succeed(
+ root === projectRoot
+ ? Option.some({
+ id: ProjectId.make("project"),
+ title: "Project",
+ workspaceRoot: projectRoot,
+ } as never)
+ : Option.none(),
+ ),
+ });
+
+const listTools = (
+ settings: Parameters[0],
+ input: Parameters[0],
+ projectRoot: string | null = null,
+) =>
+ McpServerTools.McpServerTools.pipe(
+ Effect.flatMap((service) => service.listTools(input)),
+ Effect.provide(
+ McpServerTools.layer.pipe(
+ Layer.provide(ServerSettings.layerTest(settings)),
+ Layer.provide(projects(projectRoot)),
+ ),
+ ),
+ );
+
+/** Whether a process with this pid is still running. */
+const isRunning = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+it.live("lists a stdio server's tools across pages, then stops it", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-tools-" });
+ const pidFile = path.join(directory, "pid");
+
+ const result = yield* listTools(
+ {
+ mcpServers: {
+ fixture: stdioServer(
+ [fixture],
+ [
+ { name: "MCP_FIXTURE_PID_FILE", value: pidFile },
+ { name: "MCP_FIXTURE_GREETING", value: "Hello from env." },
+ ],
+ ),
+ },
+ },
+ { name: "fixture" },
+ );
+
+ expect(result.serverInfo).toEqual({ name: "two-tool-fixture", version: "1.2.3" });
+ expect(result.tools).toEqual([
+ {
+ name: "echo",
+ title: "Echo",
+ description: "Repeats text back. Hello from env.",
+ parameters: [
+ { name: "text", type: "string", description: "What to repeat", required: true },
+ { name: "times", type: "integer", description: "How many times", required: false },
+ ],
+ },
+ {
+ name: "pick",
+ description: "Picks a color.",
+ parameters: [
+ { name: "color", type: '"red" | "green"', required: true },
+ { name: "tags", type: "string[]", required: false },
+ ],
+ },
+ ]);
+
+ const pid = Number(yield* fileSystem.readFileString(pidFile));
+ expect(isRunning(pid)).toBe(false);
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.live("lists a project's server that is switched off, started in the checkout", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const projectRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-project-" });
+ // A relative path, which only resolves from the project's checkout.
+ yield* fileSystem.copyFile(fixture, `${projectRoot}/server.mjs`);
+ const result = yield* listTools(
+ {
+ projectSettingsOverrides: {
+ [ProjectId.make("project")]: {
+ mcpServers: { local: { ...stdioServer(["server.mjs"]), enabled: false } },
+ },
+ },
+ },
+ { name: "local", cwd: projectRoot },
+ projectRoot,
+ );
+ expect(result.tools.map((tool) => tool.name)).toEqual(["echo", "pick"]);
+
+ // The environment doesn't have the project's server.
+ const outside = yield* listTools({}, { name: "local" }, projectRoot).pipe(Effect.flip);
+ assert(outside._tag === "McpServerToolsError");
+ expect(outside.reason).toBe("not-found");
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.live("fails with a typed error when the command can't run or exits", () =>
+ Effect.gen(function* () {
+ const missing = yield* listTools(
+ {
+ mcpServers: {
+ broken: {
+ enabled: true,
+ transport: {
+ type: "stdio",
+ command: "/definitely/not/a/command",
+ args: [],
+ env: [],
+ },
+ },
+ },
+ },
+ { name: "broken" },
+ ).pipe(Effect.flip);
+ assert(missing._tag === "McpServerToolsError");
+ expect(missing.reason).toBe("spawn-failed");
+
+ const exits = yield* listTools(
+ { mcpServers: { exits: stdioServer(["-e", "process.exit(3)"]) } },
+ { name: "exits" },
+ ).pipe(Effect.flip);
+ assert(exits._tag === "McpServerToolsError");
+ expect(exits.reason).toBe("exited");
+ }).pipe(Effect.provide(NodeServices.layer)),
+);
+
+it.effect("reports a server or project that isn't there", () =>
+ Effect.gen(function* () {
+ const unknown = yield* listTools({}, { name: "nope" }).pipe(Effect.flip);
+ assert(unknown._tag === "McpServerToolsError");
+ expect(unknown.reason).toBe("not-found");
+
+ const project = yield* listTools({}, { name: "nope", cwd: "/elsewhere" }).pipe(Effect.flip);
+ assert(project._tag === "McpServerToolsError");
+ expect(project.reason).toBe("unknown-project");
+ }),
+);
+
+it.effect("lists T3 Code's own tools without starting anything", () =>
+ Effect.gen(function* () {
+ const result = yield* listTools({}, { name: "t3-code" });
+ expect(result.serverInfo?.name).toBe("T3 Code");
+ const names = result.tools.map((tool) => tool.name);
+ expect(names).toEqual(
+ expect.arrayContaining([
+ "t3_thread_launch",
+ "delegate_task",
+ "preview_snapshot",
+ "html_render",
+ ]),
+ );
+ expect(new Set(names).size).toBe(names.length);
+ const launch = result.tools.find((tool) => tool.name === "t3_thread_launch");
+ expect(launch?.description).toBeTruthy();
+ expect(launch?.parameters.some((parameter) => parameter.name === "title")).toBe(true);
+ }),
+);
diff --git a/apps/server/src/mcpServers/McpServerTools.ts b/apps/server/src/mcpServers/McpServerTools.ts
new file mode 100644
index 0000000000000..12ac73bf09179
--- /dev/null
+++ b/apps/server/src/mcpServers/McpServerTools.ts
@@ -0,0 +1,354 @@
+/**
+ * A Settings → Tools server's tools, read by starting the server the way an
+ * agent session would: the same settings, project overrides and secrets, then
+ * `initialize` and `tools/list`, then shut down. T3's own `t3-code` server is
+ * read from its toolkits without starting anything.
+ */
+import {
+ type McpServerTool,
+ type McpServerToolParameter,
+ McpServerToolsError,
+ type McpServerToolsInput,
+ type McpServerToolsResult,
+ type McpServerTransport,
+ mcpServerVariableRecord,
+ type ServerSettingsError,
+ T3_MCP_SERVER_NAME,
+} from "@t3tools/contracts";
+import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
+import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
+import * as Context from "effect/Context";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { Tool } from "effect/ai";
+
+import { T3_MCP_TOOLKITS } from "../mcp/McpHttpServer.ts";
+import * as ProjectService from "../project/ProjectService.ts";
+import * as ServerSettings from "../serverSettings.ts";
+
+/** Long enough for `npx -y` to fetch a package on a first run. */
+const LIST_TOOLS_TIMEOUT = Duration.seconds(30);
+/** A server that pages forever stops being read here. */
+const MAX_TOOL_PAGES = 50;
+
+export class McpServerTools extends Context.Service<
+ McpServerTools,
+ {
+ /** The named server's tools, as an agent in the project at `cwd` (or on the environment) gets it. */
+ readonly listTools: (
+ input: McpServerToolsInput,
+ ) => Effect.Effect;
+ }
+>()("t3/mcpServers/McpServerTools") {}
+
+// ── Tool descriptions ────────────────────────────────────────────────
+
+type JsonObject = Readonly>;
+
+const isObject = (value: unknown): value is JsonObject =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const nonEmpty = (value: unknown): string | undefined =>
+ typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
+
+/** A short reading of a JSON Schema's type: `string`, `number[]`, `"a" | "b"`, `object`. */
+function schemaTypeLabel(schema: unknown, depth = 0): string | undefined {
+ if (!isObject(schema) || depth > 3) return undefined;
+ if ("const" in schema) return JSON.stringify(schema.const);
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
+ const shown = schema.enum.slice(0, 6).map((value) => JSON.stringify(value));
+ return schema.enum.length > shown.length ? `${shown.join(" | ")} | …` : shown.join(" | ");
+ }
+ const type = schema.type;
+ if (Array.isArray(type)) {
+ const names = type.filter((entry): entry is string => typeof entry === "string");
+ return names.length === 0 ? undefined : names.join(" | ");
+ }
+ if (type === "array") {
+ const item = schemaTypeLabel(schema.items, depth + 1);
+ return item === undefined ? "array" : item.includes(" ") ? `(${item})[]` : `${item}[]`;
+ }
+ if (typeof type === "string") return type;
+ for (const key of ["anyOf", "oneOf"] as const) {
+ const options = schema[key];
+ if (!Array.isArray(options)) continue;
+ const labels = [
+ ...new Set(
+ options
+ .map((option) => schemaTypeLabel(option, depth + 1))
+ .filter((label): label is string => label !== undefined),
+ ),
+ ];
+ if (labels.length > 0) return labels.join(" | ");
+ }
+ return isObject(schema.properties) ? "object" : undefined;
+}
+
+/** The top-level properties of a tool's input schema, required ones first. */
+function summarizeToolParameters(inputSchema: unknown): ReadonlyArray {
+ if (!isObject(inputSchema) || !isObject(inputSchema.properties)) return [];
+ const required = new Set(
+ Array.isArray(inputSchema.required)
+ ? inputSchema.required.filter((name): name is string => typeof name === "string")
+ : [],
+ );
+ const parameters = Object.entries(inputSchema.properties).map(([name, schema]) => {
+ const type = schemaTypeLabel(schema);
+ const description = isObject(schema) ? nonEmpty(schema.description) : undefined;
+ return {
+ name,
+ required: required.has(name),
+ ...(type === undefined ? {} : { type }),
+ ...(description === undefined ? {} : { description }),
+ } satisfies McpServerToolParameter;
+ });
+ // A stable sort, so each half keeps the server's order.
+ return parameters.toSorted((left, right) => Number(right.required) - Number(left.required));
+}
+
+function describeTool(tool: {
+ readonly name: string;
+ readonly title?: string | undefined;
+ readonly description?: string | undefined;
+ readonly annotations?: { readonly title?: string | undefined } | undefined;
+ readonly inputSchema?: unknown;
+}): McpServerTool {
+ const title = nonEmpty(tool.title) ?? nonEmpty(tool.annotations?.title);
+ const description = nonEmpty(tool.description);
+ return {
+ name: tool.name,
+ ...(title === undefined ? {} : { title }),
+ ...(description === undefined ? {} : { description }),
+ parameters: summarizeToolParameters(tool.inputSchema),
+ };
+}
+
+/**
+ * T3's own tools, from the toolkits `/mcp` registers. A session only gets the
+ * ones its access allows (browser and device tools follow their settings), but
+ * every one is listed here.
+ */
+function t3CodeTools(): McpServerToolsResult {
+ const tools = new Map();
+ for (const toolkit of T3_MCP_TOOLKITS) {
+ for (const tool of Object.values(toolkit.tools)) {
+ if (tools.has(tool.name)) continue;
+ tools.set(
+ tool.name,
+ describeTool({
+ name: tool.name,
+ title: Option.getOrUndefined(Context.getOption(tool.annotations, Tool.Title)),
+ description: Tool.getDescription(tool),
+ inputSchema: Tool.getJsonSchema(tool),
+ }),
+ );
+ }
+ }
+ return {
+ serverInfo: { name: "T3 Code" },
+ tools: [...tools.values()].toSorted((left, right) => left.name.localeCompare(right.name)),
+ };
+}
+
+// ── Talking to a server ──────────────────────────────────────────────
+
+/** Loaded on first use, so the server doesn't load the MCP client and its validators at startup. */
+const loadSdk = () =>
+ Promise.all([
+ import("@modelcontextprotocol/sdk/client/index.js"),
+ import("@modelcontextprotocol/sdk/client/stdio.js"),
+ import("@modelcontextprotocol/sdk/client/streamableHttp.js"),
+ import("@modelcontextprotocol/sdk/client/sse.js"),
+ import("@modelcontextprotocol/sdk/client/auth.js"),
+ import("@modelcontextprotocol/sdk/types.js"),
+ ]).then(([client, stdio, streamableHttp, sse, auth, types]) => ({
+ Client: client.Client,
+ StdioClientTransport: stdio.StdioClientTransport,
+ StreamableHTTPClientTransport: streamableHttp.StreamableHTTPClientTransport,
+ StreamableHTTPError: streamableHttp.StreamableHTTPError,
+ SSEClientTransport: sse.SSEClientTransport,
+ SseError: sse.SseError,
+ UnauthorizedError: auth.UnauthorizedError,
+ McpError: types.McpError,
+ connectionClosed: types.ErrorCode.ConnectionClosed,
+ }));
+type Sdk = Awaited>;
+
+/** Why a server couldn't be listed, from what the SDK and Node throw. */
+function failureReason(
+ sdk: Sdk,
+ transport: McpServerTransport,
+ cause: unknown,
+ stage: "connect" | "list",
+): McpServerToolsError["reason"] {
+ const gone = transport.type === "stdio" ? "exited" : "unreachable";
+ if (cause instanceof sdk.UnauthorizedError) return "unauthorized";
+ if (cause instanceof sdk.McpError) {
+ // The SDK's own code for a process or socket that went away.
+ return cause.code === sdk.connectionClosed ? gone : "request-failed";
+ }
+ if (cause instanceof sdk.StreamableHTTPError || cause instanceof sdk.SseError) {
+ const status = cause.code;
+ if (status === 401 || status === 403) return "unauthorized";
+ return typeof status === "number" && status >= 400 && status < 500 ? "request-failed" : gone;
+ }
+ // Node's spawn error (ENOENT, EACCES) rejects the transport's start.
+ if (transport.type === "stdio" && stage === "connect") return "spawn-failed";
+ return gone;
+}
+
+/** A 404 or 405 for the first POST: an older server that only speaks SSE. */
+const wantsSseFallback = (sdk: Sdk, cause: unknown) =>
+ cause instanceof sdk.StreamableHTTPError && (cause.code === 404 || cause.code === 405);
+
+const make = Effect.gen(function* () {
+ const settingsService = yield* ServerSettings.ServerSettingsService;
+ const projects = yield* ProjectService.ProjectService;
+ let t3CodeListing: McpServerToolsResult | undefined;
+
+ /** The server as agents in this scope get it: project overrides applied, secrets filled in. */
+ const resolveServer = Effect.fn("McpServerTools.resolveServer")(function* (
+ input: McpServerToolsInput,
+ ) {
+ let projectId = null;
+ let cwd: string | undefined;
+ if (input.cwd !== undefined) {
+ const project = yield* projects.getByWorkspaceRoot(input.cwd).pipe(
+ Effect.map(Option.getOrUndefined),
+ Effect.orElseSucceed(() => undefined),
+ );
+ if (project === undefined) {
+ return yield* new McpServerToolsError({ server: input.name, reason: "unknown-project" });
+ }
+ projectId = project.id;
+ cwd = project.workspaceRoot;
+ }
+ const settings = yield* settingsService.getSettings;
+ const servers = resolveProjectSettings(settings, projectId).settings.mcpServers;
+ const server = Object.hasOwn(servers, input.name) ? servers[input.name] : undefined;
+ if (server === undefined) {
+ return yield* new McpServerToolsError({ server: input.name, reason: "not-found" });
+ }
+ // A server switched off is still inspected: its definition is what's asked about.
+ return { transport: server.transport, cwd };
+ });
+
+ const listServerTools = Effect.fn("McpServerTools.listServerTools")(function* (
+ name: string,
+ transport: McpServerTransport,
+ cwd: string | undefined,
+ ) {
+ yield* Effect.annotateCurrentSpan({ "mcp.server.transport": transport.type });
+ const hostEnvironment = yield* HostProcessEnvironment;
+ const sdk = yield* Effect.promise(loadSdk);
+ const fail = (reason: McpServerToolsError["reason"], cause?: unknown) =>
+ new McpServerToolsError({ server: name, reason, ...(cause === undefined ? {} : { cause }) });
+
+ const makeTransport = (kind: "streamable" | "sse") => {
+ if (transport.type === "stdio") {
+ // The host environment with the server's variables over it, as providers
+ // start their servers; the SDK's default would keep only a few names.
+ const env: Record = {};
+ for (const [key, value] of Object.entries(hostEnvironment)) {
+ if (value !== undefined) env[key] = value;
+ }
+ return new sdk.StdioClientTransport({
+ command: transport.command,
+ args: [...transport.args],
+ env: { ...env, ...mcpServerVariableRecord(transport.env) },
+ // A project's agents run in its checkout, where a relative path resolves.
+ ...(cwd === undefined ? {} : { cwd }),
+ stderr: "ignore",
+ });
+ }
+ const url = new URL(transport.url);
+ const requestInit = { headers: mcpServerVariableRecord(transport.headers) };
+ return kind === "sse"
+ ? new sdk.SSEClientTransport(url, { requestInit })
+ : new sdk.StreamableHTTPClientTransport(url, { requestInit });
+ };
+
+ /** Connects and initializes; the client and its process close with the scope. */
+ const connect = (kind: "streamable" | "sse") =>
+ Effect.acquireRelease(
+ Effect.sync(() => ({
+ client: new sdk.Client({ name: "t3-code", version: "1.0.0" }, { capabilities: {} }),
+ connection: makeTransport(kind),
+ })),
+ // Closing a stdio transport ends stdin, then sends SIGTERM and SIGKILL
+ // until the process has exited, and resolves only once it has.
+ ({ client, connection }) =>
+ Effect.promise(() => client.close().then(() => connection.close())).pipe(Effect.ignore),
+ ).pipe(
+ Effect.tap(({ client, connection }) =>
+ Effect.tryPromise({
+ // The SDK declares `sessionId?: string`, which its own HTTP transport's
+ // `string | undefined` getter misses under exactOptionalPropertyTypes.
+ try: () => client.connect(connection as Transport),
+ catch: (cause) => fail(failureReason(sdk, transport, cause, "connect"), cause),
+ }),
+ ),
+ );
+
+ const listPages = (client: InstanceType) =>
+ Effect.gen(function* () {
+ const tools: McpServerTool[] = [];
+ let cursor: string | undefined;
+ for (let page = 0; page < MAX_TOOL_PAGES; page += 1) {
+ const result = yield* Effect.tryPromise({
+ try: () => client.listTools(cursor === undefined ? undefined : { cursor }),
+ catch: (cause) => fail(failureReason(sdk, transport, cause, "list"), cause),
+ });
+ tools.push(...result.tools.map(describeTool));
+ cursor = result.nextCursor;
+ if (cursor === undefined) break;
+ }
+ return tools;
+ });
+
+ return yield* Effect.scoped(
+ Effect.gen(function* () {
+ const { client } = yield* connect("streamable").pipe(
+ Effect.catchIf(
+ (error) => transport.type === "http" && wantsSseFallback(sdk, error.cause),
+ () => connect("sse"),
+ ),
+ );
+ const tools = yield* listPages(client);
+ const info = client.getServerVersion();
+ const serverName = nonEmpty(info?.name);
+ const version = nonEmpty(info?.version);
+ return {
+ ...(serverName === undefined
+ ? {}
+ : { serverInfo: { name: serverName, ...(version === undefined ? {} : { version }) } }),
+ tools,
+ } satisfies McpServerToolsResult;
+ }),
+ ).pipe(
+ // The timeout interrupts the scope, which still waits for the process to exit.
+ Effect.timeoutOrElse({
+ duration: LIST_TOOLS_TIMEOUT,
+ orElse: () => Effect.fail(fail("timed-out")),
+ }),
+ );
+ });
+
+ const listTools: McpServerTools["Service"]["listTools"] = Effect.fn("McpServerTools.listTools")(
+ function* (input) {
+ if (input.name === T3_MCP_SERVER_NAME) {
+ t3CodeListing ??= t3CodeTools();
+ return t3CodeListing;
+ }
+ const server = yield* resolveServer(input);
+ return yield* listServerTools(input.name, server.transport, server.cwd);
+ },
+ );
+
+ return McpServerTools.of({ listTools });
+});
+
+export const layer = Layer.effect(McpServerTools, make);
diff --git a/apps/server/src/mcpServers/testFixtures/two-tool-mcp-server.mjs b/apps/server/src/mcpServers/testFixtures/two-tool-mcp-server.mjs
new file mode 100644
index 0000000000000..2ccc66f1b7981
--- /dev/null
+++ b/apps/server/src/mcpServers/testFixtures/two-tool-mcp-server.mjs
@@ -0,0 +1,72 @@
+// A stdio MCP server with two tools, one per `tools/list` page, for
+// McpServerTools.test.ts. It writes its pid to MCP_FIXTURE_PID_FILE so the
+// test can check that it was stopped, and puts MCP_FIXTURE_GREETING in a tool
+// description so the test can check that the server's variables reached it.
+import * as NodeFS from "node:fs";
+import * as NodeReadline from "node:readline";
+
+if (process.env.MCP_FIXTURE_PID_FILE) {
+ NodeFS.writeFileSync(process.env.MCP_FIXTURE_PID_FILE, String(process.pid));
+}
+
+const echo = {
+ name: "echo",
+ title: "Echo",
+ description: `Repeats text back. ${process.env.MCP_FIXTURE_GREETING ?? ""}`.trim(),
+ inputSchema: {
+ type: "object",
+ properties: {
+ times: { type: "integer", description: "How many times" },
+ text: { type: "string", description: "What to repeat" },
+ },
+ required: ["text"],
+ },
+};
+const pick = {
+ name: "pick",
+ description: "Picks a color.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ color: { type: "string", enum: ["red", "green"] },
+ tags: { type: "array", items: { type: "string" } },
+ },
+ required: ["color"],
+ },
+};
+
+const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
+
+for await (const line of NodeReadline.createInterface({ input: process.stdin })) {
+ const request = JSON.parse(line);
+ if (request.id === undefined) continue;
+ switch (request.method) {
+ case "initialize":
+ write({
+ jsonrpc: "2.0",
+ id: request.id,
+ result: {
+ protocolVersion: request.params.protocolVersion,
+ capabilities: { tools: {} },
+ serverInfo: { name: "two-tool-fixture", version: "1.2.3" },
+ },
+ });
+ break;
+ case "tools/list":
+ write({
+ jsonrpc: "2.0",
+ id: request.id,
+ result:
+ request.params?.cursor === "page-2"
+ ? { tools: [pick] }
+ : { tools: [echo], nextCursor: "page-2" },
+ });
+ break;
+ default:
+ write({
+ jsonrpc: "2.0",
+ id: request.id,
+ error: { code: -32601, message: "Method not found" },
+ });
+ }
+}
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index f5b637eecc1c3..7c3db517b22e4 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -40,6 +40,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.skillsRemove]: "skills",
[WS_METHODS.skillsExport]: "skills",
[WS_METHODS.skillsImport]: "skills",
+ [WS_METHODS.mcpServersListTools]: "mcpServers",
[WS_METHODS.serverUpdateProvider]: "server",
[WS_METHODS.providerAuthStart]: "provider",
[WS_METHODS.providerConsumeResetCredit]: "provider",
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index f032fa74ff85a..1cc46f0c80db7 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -62,6 +62,7 @@ import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceR
import * as TerminalManager from "./terminal/Manager.ts";
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
+import * as McpServerTools from "./mcpServers/McpServerTools.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as DeviceService from "./device/DeviceService.ts";
import * as DeviceHubProxy from "./device/DeviceHubProxy.ts";
@@ -591,6 +592,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
layerProviderInstallationRefresh,
ReplayMarkers.layer,
SkillLibrary.layer.pipe(Layer.provide(ProcessRunner.layer)),
+ McpServerTools.layer,
).pipe(
// Core Services
Layer.provideMerge(layerOrchestrationApplication),
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 5dc69c38fb1c3..426520461806e 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -190,6 +190,7 @@ import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/Atta
import * as PortScanner from "./preview/PortScanner.ts";
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
+import * as McpServerTools from "./mcpServers/McpServerTools.ts";
import * as SkillLibrary from "./skills/SkillLibrary.ts";
import { readWorkflowScript } from "./orchestration-v2/workflowScriptQuery.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
@@ -1288,6 +1289,7 @@ const layerWsRpc = (
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const skillLibrary = yield* SkillLibrary.SkillLibrary;
+ const mcpServerTools = yield* McpServerTools.McpServerTools;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const rpcClientIds = yield* Ref.make(new Set());
@@ -2651,6 +2653,7 @@ const layerWsRpc = (
[WS_METHODS.skillsRemove]: (input) => skillLibrary.remove(input).pipe(Effect.as({})),
[WS_METHODS.skillsExport]: (input) => skillLibrary.exportSkill(input),
[WS_METHODS.skillsImport]: (input) => skillLibrary.importSkill(input).pipe(Effect.as({})),
+ [WS_METHODS.mcpServersListTools]: (input) => mcpServerTools.listTools(input),
[WS_METHODS.projectsReadFile]: (input) =>
workspaceFileSystem.readFile(input).pipe(
Effect.mapError(
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index ac7fa8b781482..f84f5b3020933 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1183,6 +1183,13 @@ export function createServerEnvironmentAtoms(
staleTimeMs: 30_000,
idleTtlMs: 5 * 60_000,
}),
+ // An MCP server's tools, read by starting it; needs `providers:manage`.
+ listMcpServerTools: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:mcp-servers:list-tools",
+ tag: WS_METHODS.mcpServersListTools,
+ staleTimeMs: 5 * 60_000,
+ idleTtlMs: 5 * 60_000,
+ }),
previewSkills: createEnvironmentRpcCommand(runtime, {
label: "environment-data:skills:preview",
tag: WS_METHODS.skillsPreview,
diff --git a/packages/contracts/src/agentTools.ts b/packages/contracts/src/agentTools.ts
index aa478cbf05e5a..6abdf211affae 100644
--- a/packages/contracts/src/agentTools.ts
+++ b/packages/contracts/src/agentTools.ts
@@ -18,8 +18,9 @@ import { ForwardCompatibleArray, TrimmedNonEmptyString } from "./baseSchemas.ts"
*/
const MCP_SERVER_NAME_PATTERN = /^[a-z][a-z0-9_-]*$/;
const MCP_SERVER_NAME_MAX_CHARS = 48;
-/** Reserved for T3's own server, which every session already gets. */
-const RESERVED_MCP_SERVER_NAMES: ReadonlySet = new Set(["t3-code"]);
+/** T3's own server, which every session already gets. */
+export const T3_MCP_SERVER_NAME = "t3-code";
+const RESERVED_MCP_SERVER_NAMES: ReadonlySet = new Set([T3_MCP_SERVER_NAME]);
export const McpServerName = TrimmedNonEmptyString.check(
Schema.isMaxLength(MCP_SERVER_NAME_MAX_CHARS),
@@ -133,3 +134,89 @@ export function mcpServerTransportSummary(transport: McpServerTransport): string
? [transport.command, ...transport.args].join(" ")
: transport.url;
}
+
+// ── A server's tools ─────────────────────────────────────────────────
+
+export const McpServerToolsInput = Schema.Struct({
+ /** A server from Settings → Tools, or `t3-code` for T3's own. */
+ name: TrimmedNonEmptyString.check(Schema.isMaxLength(MCP_SERVER_NAME_MAX_CHARS)),
+ /** A project's checkout: the server as that project's agents get it. */
+ cwd: Schema.optional(TrimmedNonEmptyString),
+});
+export type McpServerToolsInput = typeof McpServerToolsInput.Type;
+
+/** One top-level property of a tool's input schema. */
+export const McpServerToolParameter = Schema.Struct({
+ name: Schema.String,
+ /** A short reading of its JSON Schema type, such as `string`, `number[]` or `"a" | "b"`. */
+ type: Schema.optionalKey(Schema.String),
+ description: Schema.optionalKey(Schema.String),
+ required: Schema.Boolean,
+});
+export type McpServerToolParameter = typeof McpServerToolParameter.Type;
+
+export const McpServerTool = Schema.Struct({
+ name: Schema.String,
+ title: Schema.optionalKey(Schema.String),
+ description: Schema.optionalKey(Schema.String),
+ parameters: Schema.Array(McpServerToolParameter),
+});
+export type McpServerTool = typeof McpServerTool.Type;
+
+export const McpServerToolsResult = Schema.Struct({
+ /** What the server called itself when it started, if it said. */
+ serverInfo: Schema.optionalKey(
+ Schema.Struct({ name: Schema.String, version: Schema.optionalKey(Schema.String) }),
+ ),
+ tools: Schema.Array(McpServerTool),
+});
+export type McpServerToolsResult = typeof McpServerToolsResult.Type;
+
+export const McpServerToolsErrorReason = Schema.Literals([
+ /** No server of that name at this scope. */
+ "not-found",
+ /** The folder isn't one of this environment's projects. */
+ "unknown-project",
+ /** The command couldn't be run at all. */
+ "spawn-failed",
+ /** The command ran but stopped before it listed its tools. */
+ "exited",
+ /** The URL couldn't be reached. */
+ "unreachable",
+ /** The URL answered 401 or 403: it wants a sign-in T3 can't do here. */
+ "unauthorized",
+ /** The server answered, with an error. */
+ "request-failed",
+ "timed-out",
+]);
+export type McpServerToolsErrorReason = typeof McpServerToolsErrorReason.Type;
+
+export class McpServerToolsError extends Schema.TaggedError()(
+ "McpServerToolsError",
+ {
+ server: Schema.String,
+ reason: McpServerToolsErrorReason,
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ switch (this.reason) {
+ case "not-found":
+ return `There's no MCP server named "${this.server}" here.`;
+ case "unknown-project":
+ return "That folder isn't a project on this environment.";
+ case "spawn-failed":
+ return "The server's command couldn't be run. Check that it's installed on this environment.";
+ case "exited":
+ return "The server stopped before it listed its tools. Check its command, arguments and environment variables.";
+ case "unreachable":
+ return "The server's URL couldn't be reached.";
+ case "unauthorized":
+ return "The server wants a sign-in, which listing its tools can't do here. Add an access token as a header, or sign in from an agent.";
+ case "request-failed":
+ return "The server returned an error when asked for its tools.";
+ case "timed-out":
+ return "The server didn't list its tools within 30 seconds.";
+ }
+ }
+}
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index b8b5989659668..ae83136adc2fa 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -161,6 +161,7 @@ import {
SkillPreviewInput,
SkillPreviewResult,
} from "./skills.ts";
+import { McpServerToolsError, McpServerToolsInput, McpServerToolsResult } from "./agentTools.ts";
import {
OrchestrationSearchThreadsError,
OrchestrationSearchThreadsInput,
@@ -482,6 +483,7 @@ export const WS_METHODS = {
skillsRemove: "skills.remove",
skillsExport: "skills.export",
skillsImport: "skills.import",
+ mcpServersListTools: "mcpServers.listTools",
serverUpdateProvider: "server.updateProvider",
serverUpdateServer: "server.updateServer",
serverUpdateServerWithProgress: "server.updateServerWithProgress",
@@ -647,6 +649,12 @@ const WsSkillsImportRpc = Rpc.make(WS_METHODS.skillsImport, {
error: Schema.Union([SkillLibraryError, EnvironmentAuthorizationError]),
});
+const WsMcpServersListToolsRpc = Rpc.make(WS_METHODS.mcpServersListTools, {
+ payload: McpServerToolsInput,
+ success: McpServerToolsResult,
+ error: Schema.Union([McpServerToolsError, ServerSettingsError, EnvironmentAuthorizationError]),
+});
+
const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {
payload: Schema.Struct({}),
success: ServerConfig,
@@ -1881,6 +1889,7 @@ export const WsRpcGroup = RpcGroup.make(
WsSkillsRemoveRpc,
WsSkillsExportRpc,
WsSkillsImportRpc,
+ WsMcpServersListToolsRpc,
WsServerUpdateProviderRpc,
WsProviderConsumeResetCreditRpc,
WsProviderAuthStartRpc,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 13ae026c4e7d9..8cd0cd141f96b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -594,6 +594,9 @@ importers:
'@ff-labs/fff-node':
specifier: 0.9.4
version: 0.9.4(patch_hash=c4e3cc2420ceb9dc650f9d189e9c24baf7e83f342998bacda5f459a4ce7927a8)
+ '@modelcontextprotocol/sdk':
+ specifier: 1.29.0
+ version: 1.29.0(zod@4.6.5)
'@muse-code/sdk':
specifier: 1.4.2
version: 1.4.2(@types/node@24.12.4)
@@ -664,9 +667,6 @@ importers:
'@effect/vitest':
specifier: 4.0.1
version: 4.0.1(patch_hash=359f6fb2f7b3ec145bb72208edb9034f02489791aa2491a55cdbd69bd56ee0d2)(@types/node@24.12.4)(@vitest/ui@5.0.1)(bufferutil@4.1.0)(effect@4.0.1(patch_hash=a33cba07c41f32374c2aaa86ea4a84d3ab9a872a78c94b65e929b19f8361856f))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(msw@2.12.11(@types/node@24.12.4)(typescript@7.0.2))(terser@5.48.0)(typescript@7.0.2)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)
- '@modelcontextprotocol/sdk':
- specifier: 1.29.0
- version: 1.29.0(zod@4.6.5)
'@t3tools/contracts':
specifier: workspace:*
version: link:../../packages/contracts
From 25a7af8aeb46365e0b05e64c6c8fdbd6e6850c8f Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sun, 11 Oct 2026 02:13:53 -0700
Subject: [PATCH 34/35] =?UTF-8?q?feat(web):=20open=20an=20MCP=20server=20i?=
=?UTF-8?q?n=20Settings=20=E2=86=92=20Tools=20to=20see=20its=20tools?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Clicking a server on the MCP servers tab, including the built-in t3-code
row, opens its page in place of the list, the way a skill opens: the
header reads Settings / Tools / , and the Tools crumb or Escape
goes back. The page shows the transport and command or URL, the switch,
Edit and Remove as buttons, then the server's tools in dense rows that
open to their parameters (name, type, required, description).
Tools load through `mcpServers.listTools`, with a delayed skeleton, an
error with Retry, and a refresh; an edit while the page is open lists
them again. A server that is switched off can still be inspected. The
row's switch, Reset and menu keep their clicks to themselves.
Co-Authored-By: Claude Opus 5.5
---
.../components/settings/McpServerDetail.tsx | 331 ++++++++++++++++++
.../settings/SettingsBreadcrumb.tsx | 12 +-
.../src/components/settings/SkillDetail.tsx | 30 +-
.../web/src/components/settings/SkillList.tsx | 2 +-
.../src/components/settings/ToolsSettings.tsx | 265 +++++++++-----
.../settings/toolsSettings.logic.test.ts | 15 +
.../settings/toolsSettings.logic.ts | 11 +-
.../components/settings/useEscapeToList.ts | 29 ++
apps/web/src/routes/settings.tools.tsx | 14 +-
docs/user/tools.md | 5 +
10 files changed, 597 insertions(+), 117 deletions(-)
create mode 100644 apps/web/src/components/settings/McpServerDetail.tsx
create mode 100644 apps/web/src/components/settings/useEscapeToList.ts
diff --git a/apps/web/src/components/settings/McpServerDetail.tsx b/apps/web/src/components/settings/McpServerDetail.tsx
new file mode 100644
index 0000000000000..191eefa432fae
--- /dev/null
+++ b/apps/web/src/components/settings/McpServerDetail.tsx
@@ -0,0 +1,331 @@
+import {
+ AuthProvidersManageScope,
+ type EnvironmentId,
+ mcpServerTransportSummary,
+ type McpServerTool,
+} from "@t3tools/contracts";
+import { ChevronDownIcon } from "lucide-react";
+import { memo, useEffect, useRef, useState } from "react";
+
+import { useAfterDelay } from "../../hooks/useAfterDelay";
+import { cn } from "../../lib/utils";
+import { useEnvironmentQuery } from "../../state/query";
+import { serverEnvironment } from "../../state/server";
+import { useEnvironmentScope } from "../../state/session";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { RefreshIcon } from "../ui/refresh-icon";
+import { Skeleton } from "../ui/skeleton";
+import { Switch } from "../ui/switch";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { SettingsGroup } from "./SettingsGroup";
+import { TruncatedText } from "./TruncatedText";
+import type { McpServerRow } from "./toolsSettings.logic";
+import { useEscapeToList } from "./useEscapeToList";
+
+/** A start that finishes sooner than this shows no placeholder at all. */
+const SKELETON_DELAY_MS = 150;
+
+/**
+ * One MCP server: what it is, its switch and actions, then the tools it
+ * offers, read by starting it as an agent would. The settings header names
+ * it and leads back to the list. `row` is null for T3 Code's own server.
+ */
+export function McpServerDetail({
+ name,
+ row,
+ environmentId,
+ cwd,
+ canSwitch,
+ onEnabledChange,
+ onEdit,
+ onRemove,
+ onReset,
+ onBack,
+}: {
+ name: string;
+ row: McpServerRow | null;
+ environmentId: EnvironmentId;
+ /** The project checkout whose settings apply, or null for the environment's. */
+ cwd: string | null;
+ canSwitch: boolean;
+ onEnabledChange: (enabled: boolean) => void;
+ onEdit: (() => void) | null;
+ onRemove: (() => void) | null;
+ onReset: (() => void) | null;
+ onBack: () => void;
+}) {
+ useEscapeToList(onBack);
+ const canList = useEnvironmentScope(environmentId, AuthProvidersManageScope);
+ const query = useEnvironmentQuery(
+ canList
+ ? serverEnvironment.listMcpServerTools({
+ environmentId,
+ input: { name, ...(cwd === null ? {} : { cwd }) },
+ })
+ : null,
+ );
+ // An edit while the page is open lists the server again as it now starts.
+ const transportKey = row === null ? "" : JSON.stringify(row.config.transport);
+ const listedFor = useRef(transportKey);
+ const { refresh } = query;
+ useEffect(() => {
+ if (listedFor.current === transportKey) return;
+ listedFor.current = transportKey;
+ refresh();
+ }, [refresh, transportKey]);
+
+ const tools = query.data?.tools ?? null;
+ const showSkeleton = useAfterDelay(
+ canList && tools === null && query.error === null,
+ SKELETON_DELAY_MS,
+ );
+ const serverInfo = query.data?.serverInfo;
+ const enabled = row?.config.enabled ?? true;
+
+ return (
+
+
+
+
+
+ {name}
+
+ {row === null
+ ? "Built in"
+ : row.config.transport.type === "stdio"
+ ? "Command"
+ : "URL"}
+
+ {row?.replacesEnvironment ? (
+
+ Replaces environment's
+
+ ) : null}
+ {row?.origin === "project-switch" ? (
+
+ {enabled ? "On" : "Off"} for this project
+
+ ) : null}
+
+ {row === null ? (
+
+ T3 Code's own tools: threads, tasks, the browser and devices. Every agent session
+ gets this server; browser and device tools follow their settings.
+
+ ) : (
+
+ {mcpServerTransportSummary(row.config.transport)}
+
+ )}
+
+ {row === null ? (
+
+ }>
+
+
+ Every agent session gets this server.
+
+ ) : (
+
+ )}
+
+ {onReset !== null || onEdit !== null || onRemove !== null ? (
+
+ {onReset !== null ? (
+
+ Reset
+
+ ) : null}
+ {onEdit !== null ? (
+
+ Edit
+
+ ) : null}
+ {onRemove !== null ? (
+
+ Remove
+
+ ) : null}
+
+ ) : null}
+
+
+
+
+
+ Tools{tools === null ? "" : ` · ${tools.length}`}
+
+ {serverInfo !== undefined ? (
+
+ {serverInfo.name}
+ {serverInfo.version === undefined ? "" : ` ${serverInfo.version}`}
+
+ ) : null}
+
+ {row !== null && canList ? (
+
+
+ }
+ >
+
+
+ Start the server again and list its tools
+
+ ) : null}
+
+ {!canList ? (
+
+
+ Listing a server's tools starts it, which needs permission to manage providers on this
+ environment.
+
+
+ ) : query.error !== null ? (
+
+
+
+ {tools === null
+ ? "Couldn't list this server's tools. "
+ : "Couldn't list them again. "}
+ {query.error}
+
+
+ Retry
+
+
+
+ ) : null}
+ {tools !== null ? (
+
+ {tools.length === 0 ? (
+
+ This server offers no tools.
+
+ ) : (
+
+ {tools.map((tool) => (
+
+ ))}
+
+ )}
+
+ ) : showSkeleton ? (
+
+ ) : null}
+
+
+ );
+}
+
+/** A tool on one dense line; it opens to its full description and parameters. */
+const McpToolItem = memo(function McpToolItem({ tool }: { tool: McpServerTool }) {
+ const [open, setOpen] = useState(false);
+ const count = tool.parameters.length;
+ return (
+
+ setOpen((value) => !value)}
+ className="flex w-full cursor-pointer items-center gap-3 px-3 py-2 text-left outline-none hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:px-4"
+ >
+
+
+ {tool.name}
+ {tool.title !== undefined && tool.title !== tool.name ? (
+ {tool.title}
+ ) : null}
+
+ {open ? null : (
+
+ )}
+
+
+ {count === 0 ? "No parameters" : count === 1 ? "1 parameter" : `${count} parameters`}
+
+
+
+ {open ? (
+
+
+ {tool.description ?? "No description."}
+
+ {count === 0 ? (
+
Takes no parameters.
+ ) : (
+
+ {tool.parameters.map((parameter) => (
+
+
+
+ {parameter.name}
+
+ {parameter.required ? (
+
+ Required
+
+ ) : null}
+
+
+ {parameter.type !== undefined ? (
+ {parameter.type}
+ ) : null}
+ {parameter.type !== undefined && parameter.description !== undefined
+ ? " · "
+ : null}
+ {parameter.description}
+
+
+ ))}
+
+ )}
+
+ ) : null}
+
+ );
+});
+
+/** Placeholder rows while the server starts, laid out like the list they stand in for. */
+function ToolsSkeleton() {
+ return (
+
+
+ {[0, 1, 2, 3].map((row) => (
+
+
+
+
+
+
+
+ ))}
+
+
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsBreadcrumb.tsx b/apps/web/src/components/settings/SettingsBreadcrumb.tsx
index dd68e3ae92d16..e1f2bee351b0d 100644
--- a/apps/web/src/components/settings/SettingsBreadcrumb.tsx
+++ b/apps/web/src/components/settings/SettingsBreadcrumb.tsx
@@ -19,14 +19,17 @@ function settingsBreadcrumbLabel(pathname: string): string | null {
}
/**
- * `Settings / Section`, or `Settings / Tools / skill` on a skill's page, where
- * Tools leads back to the list. The scope a change applies to lives at the top
- * of the page content, see `SettingsScopeSentence`.
+ * `Settings / Section`, or `Settings / Tools / name` on a skill's or MCP
+ * server's page, where Tools leads back to the list it came from. The scope a
+ * change applies to lives at the top of the page content, see
+ * `SettingsScopeSentence`.
*/
export function SettingsBreadcrumb({ pathname }: { pathname: string }) {
const sectionLabel = settingsBreadcrumbLabel(pathname);
const skill = useSearch({ strict: false, select: (search) => search.skill });
- const page = pathname === "/settings/tools" ? skill : undefined;
+ const server = useSearch({ strict: false, select: (search) => search.server });
+ const onTools = pathname === "/settings/tools";
+ const page = onTools ? (skill ?? server) : undefined;
return (
@@ -42,6 +45,7 @@ export function SettingsBreadcrumb({ pathname }: { pathname: string }) {
{/* The settings route keeps the scope on a link without search. */}
diff --git a/apps/web/src/components/settings/SkillDetail.tsx b/apps/web/src/components/settings/SkillDetail.tsx
index 50f8f6f9ac41d..cf096e9c348af 100644
--- a/apps/web/src/components/settings/SkillDetail.tsx
+++ b/apps/web/src/components/settings/SkillDetail.tsx
@@ -1,7 +1,7 @@
import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";
import { Check, Copy } from "lucide";
import { AlertTriangleIcon } from "lucide-react";
-import { lazy, Suspense, useEffect, useEffectEvent, useState } from "react";
+import { lazy, Suspense, useState } from "react";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
@@ -14,6 +14,7 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SkillAgentIcon } from "./SkillAgents";
import type { SkillEnvironment } from "./SkillEnvironments";
+import { useEscapeToList } from "./useEscapeToList";
import {
skillConflict,
type SkillAgent,
@@ -24,33 +25,6 @@ import {
// The tree and the viewer pull in the file-tree and highlighter code.
const SkillFiles = lazy(() => import("./SkillFiles"));
-/**
- * Escape goes from a skill back to the list. Settings leaves the page on
- * Escape from its own window listener, so this one runs first, in the capture
- * phase. Escape inside a field, dialog or menu belongs to that control.
- */
-function useEscapeToList(onBack: () => void) {
- const goBack = useEffectEvent((event: KeyboardEvent) => {
- if (event.key !== "Escape" || event.defaultPrevented || event.repeat || event.isComposing)
- return;
- if (
- event.target instanceof Element &&
- event.target.closest(
- 'input,textarea,select,[contenteditable],[role="dialog"],[role="alertdialog"],[role="menu"]',
- )
- )
- return;
- event.preventDefault();
- event.stopImmediatePropagation();
- onBack();
- });
- useEffect(() => {
- const onKeyDown = (event: KeyboardEvent) => goBack(event);
- window.addEventListener("keydown", onKeyDown, { capture: true });
- return () => window.removeEventListener("keydown", onKeyDown, { capture: true });
- }, []);
-}
-
/**
* One skill: what it says, which agents load it, and its files. The settings
* header names it and leads back to the list. Adapted from the skill page in
diff --git a/apps/web/src/components/settings/SkillList.tsx b/apps/web/src/components/settings/SkillList.tsx
index fdfc1e661a4da..6e68cfe1e641c 100644
--- a/apps/web/src/components/settings/SkillList.tsx
+++ b/apps/web/src/components/settings/SkillList.tsx
@@ -26,7 +26,7 @@ import {
*/
/** Keeps a click on a control inside a clickable row from also opening the row. */
-const stopRowClick = (event: MouseEvent) => event.stopPropagation();
+export const stopRowClick = (event: MouseEvent) => event.stopPropagation();
export interface SkillListRow {
readonly row: SkillRow;
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index a984f612a235a..2620c3a3351e8 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -10,6 +10,7 @@ import {
type ServerSettingsPatch,
type SkillFolderInfo,
type SkillInstallTarget,
+ T3_MCP_SERVER_NAME,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import {
@@ -19,11 +20,18 @@ import {
skillsDisabledPatch,
} from "@t3tools/shared/agentTools";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
-import { AlertTriangleIcon, MoreHorizontalIcon, PlusIcon, SearchIcon } from "lucide-react";
+import {
+ AlertTriangleIcon,
+ ChevronRightIcon,
+ MoreHorizontalIcon,
+ PlusIcon,
+ SearchIcon,
+} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useAfterDelay } from "../../hooks/useAfterDelay";
-import { formatEnvironmentQueryError } from "../../state/query";
+import { cn } from "../../lib/utils";
+import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useEnvironmentsWithScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
@@ -46,6 +54,7 @@ import { Switch } from "../ui/switch";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { AddSkillsDialog } from "./AddSkillsDialog";
+import { McpServerDetail } from "./McpServerDetail";
import { McpServerDialog } from "./McpServerDialog";
import { SettingsGroup } from "./SettingsGroup";
import { SkillDetail } from "./SkillDetail";
@@ -54,7 +63,7 @@ import {
useEnvironmentProviders,
useEnvironmentSkillFolders,
} from "./SkillEnvironments";
-import { SkillListSection, type SkillListRow } from "./SkillList";
+import { SkillListSection, type SkillListRow, stopRowClick } from "./SkillList";
import { useSettingsScope } from "./SettingsScopeContext";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
@@ -182,14 +191,19 @@ function usePersistToolsPatch() {
export function ToolsSettings({
tab = "skills",
skill,
+ server,
onTabChange,
onOpenSkill,
+ onOpenServer,
}: {
readonly tab?: ToolsTab;
/** The skill whose page is open in place of the list; the header names it. */
readonly skill?: string;
+ /** The MCP server whose page is open in place of the list; the header names it. */
+ readonly server?: string;
readonly onTabChange: (tab: ToolsTab) => void;
readonly onOpenSkill: (name: string | null) => void;
+ readonly onOpenServer: (name: string | null) => void;
}) {
// Each tab puts these at the start of its own toolbar row.
const tabs = (
@@ -209,7 +223,7 @@ export function ToolsSettings({
return (
{tab === "mcp" ? (
-
+
) : (
)}
@@ -831,7 +845,15 @@ type ServerEditor =
| { readonly mode: "add" }
| { readonly mode: "edit"; readonly row: McpServerRow };
-function McpServersPanel({ tabs }: { tabs: ReactNode }) {
+function McpServersPanel({
+ tabs,
+ openName,
+ onOpen,
+}: {
+ tabs: ReactNode;
+ openName: string | null;
+ onOpen: (name: string | null) => void;
+}) {
const { scope, target, connectedEnvironments } = useSettingsScope();
const targets = useToolsTargets();
const persist = usePersistToolsPatch();
@@ -928,73 +950,123 @@ function McpServersPanel({ tabs }: { tabs: ReactNode }) {
const ownRows = isProjectScope ? rows.filter((row) => row.origin === "project") : rows;
const inheritedRows = isProjectScope ? rows.filter((row) => row.origin !== "project") : [];
const canEditServers = canWriteSettings && canManageServers && targets.length > 0;
+ // The environment's own switch is part of the server definition.
+ const canSwitchServers = isProjectScope ? canWriteSettings : canEditServers;
+ // Inherited servers are edited where they're defined, on the environment.
+ const editable = (row: McpServerRow) =>
+ canEditServers && (!isProjectScope || row.origin === "project");
+
+ const environmentId = target?.environmentId ?? null;
+ const cwd = targets.find((candidate) => candidate.environmentId === environmentId)?.cwd ?? null;
+ const isBuiltIn = openName === T3_MCP_SERVER_NAME;
+ const opened =
+ openName === null || isBuiltIn ? null : (rows.find((row) => row.name === openName) ?? null);
return (
<>
-
- {tabs}
- {canEditServers ? (
-
setEditor({ mode: "add" })}>
-
- Add server
-
- ) : null}
-
-
- {isProjectScope ? null : }
- {ownRows.length === 0 ? (
+ {openName !== null && environmentId !== null && (isBuiltIn || opened !== null) ? (
+ {
+ if (opened !== null) setEnabled(opened, enabled);
+ }}
+ onEdit={
+ opened !== null && editable(opened)
+ ? () => setEditor({ mode: "edit", row: opened })
+ : null
+ }
+ onRemove={opened !== null && editable(opened) ? () => setRemoving(opened) : null}
+ onReset={
+ opened !== null && opened.origin === "project-switch" ? () => resetSwitch(opened) : null
+ }
+ onBack={() => onOpen(null)}
+ />
+ ) : openName !== null ? (
+ // A link or Back to a server that isn't here (yet, or any more).
+
- ) : (
- ownRows.map((row) => (
- setEnabled(row, enabled)}
- onEdit={() => setEditor({ mode: "edit", row })}
- onRemove={() => setRemoving(row)}
- />
- ))
- )}
-
- {isProjectScope && inheritedRows.length > 0 ? (
-
- {inheritedRows.map((row) => (
- setEnabled(row, enabled)}
- {...(row.origin === "project-switch" ? { onReset: () => resetSwitch(row) } : {})}
- />
- ))}
- ) : null}
- {!canManageServers && connectedEnvironments.length > 0 ? (
-
- Adding or editing servers needs permission to manage providers on this environment.
-
) : (
-
- Servers you add here are given to Claude, Codex, Cursor, OpenCode, Grok and other ACP
- agents. Pi isn't supported yet. Changes apply to new sessions; use Restart agent session
- to pick them up in an open thread.
-
+ <>
+
+ {tabs}
+ {canEditServers ? (
+
setEditor({ mode: "add" })}>
+
+ Add server
+
+ ) : null}
+
+
+ {isProjectScope ? null : onOpen(T3_MCP_SERVER_NAME)} />}
+ {ownRows.length === 0 ? (
+
+ ) : (
+ ownRows.map((row) => (
+ onOpen(row.name)}
+ onEnabledChange={(enabled) => setEnabled(row, enabled)}
+ onEdit={() => setEditor({ mode: "edit", row })}
+ onRemove={() => setRemoving(row)}
+ />
+ ))
+ )}
+
+ {isProjectScope && inheritedRows.length > 0 ? (
+
+ {inheritedRows.map((row) => (
+ onOpen(row.name)}
+ onEnabledChange={(enabled) => setEnabled(row, enabled)}
+ {...(row.origin === "project-switch" ? { onReset: () => resetSwitch(row) } : {})}
+ />
+ ))}
+
+ ) : null}
+ {!canManageServers && connectedEnvironments.length > 0 ? (
+
+ Adding, editing or inspecting servers needs permission to manage providers on this
+ environment.
+
+ ) : (
+
+ Servers you add here are given to Claude, Codex, Cursor, OpenCode, Grok and other ACP
+ agents. Pi isn't supported yet. Changes apply to new sessions; use Restart agent
+ session to pick them up in an open thread. Open a server to see its tools.
+
+ )}
+ >
)}
{editor ? (
@@ -1053,7 +1129,10 @@ function McpServersPanel({ tabs }: { tabs: ReactNode }) {
{
- if (removing) remove(removing);
+ if (removing) {
+ remove(removing);
+ if (removing.name === openName) onOpen(null);
+ }
setRemoving(null);
}}
>
@@ -1066,30 +1145,51 @@ function McpServersPanel({ tabs }: { tabs: ReactNode }) {
);
}
+/** The row's name as a button, so the row opens from the keyboard too; a click bubbles to the row. */
+function OpenServerButton({ name, children }: { name: string; children: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
+/** A server row opens the server's page; its controls keep their clicks to themselves. */
+const OPEN_ROW_CLASS = "cursor-pointer hover:bg-muted/40";
+
/**
* T3 Code's own server, which every session gets so agents can reach threads,
* the browser and other T3 tools. It isn't a setting, so it can't be switched
* off; its name is reserved (see `isValidMcpServerName`).
*/
-function T3McpServerRow() {
+function T3McpServerRow({ onOpen }: { onOpen: () => void }) {
return (
- t3-code
+
+ {T3_MCP_SERVER_NAME}
Built in
-
+
}
description="T3 Code's own tools: threads, tasks, the browser and devices."
control={
-
- }>
-
-
- Every agent session gets this server.
-
+
+
+ }>
+
+
+ Every agent session gets this server.
+
+
+
}
/>
);
@@ -1099,6 +1199,7 @@ function McpServerSettingsRow({
row,
canSwitch,
canEdit,
+ onOpen,
onEnabledChange,
onEdit,
onRemove,
@@ -1107,6 +1208,7 @@ function McpServerSettingsRow({
readonly row: McpServerRow;
readonly canSwitch: boolean;
readonly canEdit: boolean;
+ readonly onOpen: () => void;
readonly onEnabledChange: (enabled: boolean) => void;
readonly onEdit?: () => void;
readonly onRemove?: () => void;
@@ -1115,8 +1217,9 @@ function McpServerSettingsRow({
const transport = row.config.transport;
return (
+
{row.name}
{transport.type === "stdio" ? "Command" : "URL"}
@@ -1131,14 +1234,15 @@ function McpServerSettingsRow({
{row.config.enabled ? "On" : "Off"} for this project
) : null}
-
+
}
description={
{mcpServerTransportSummary(transport)}
}
- className={row.config.enabled ? undefined : "[&_h3]:text-muted-foreground"}
+ className={cn(OPEN_ROW_CLASS, !row.config.enabled && "[&_h3]:text-muted-foreground")}
control={
- <>
+ // Menu items render in a portal, but React still bubbles their clicks through here.
+
{onReset ? (
Reset
@@ -1167,7 +1271,8 @@ function McpServerSettingsRow({
disabled={!canSwitch}
onCheckedChange={onEnabledChange}
/>
- >
+
+
}
/>
);
diff --git a/apps/web/src/components/settings/toolsSettings.logic.test.ts b/apps/web/src/components/settings/toolsSettings.logic.test.ts
index ba8a32a18bf48..23051a0cbd104 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.test.ts
@@ -23,8 +23,23 @@ import {
skillRowDetails,
splitRowsBySource,
type SkillRow,
+ validateToolsSearch,
} from "./toolsSettings.logic";
+describe("validateToolsSearch", () => {
+ it("opens a skill only on the Skills tab and a server only on the MCP tab", () => {
+ expect(validateToolsSearch({ skill: "review" })).toEqual({ skill: "review" });
+ expect(validateToolsSearch({ tab: "mcp", server: "github" })).toEqual({
+ tab: "mcp",
+ server: "github",
+ });
+ // A page from the other tab, or an empty name, opens nothing.
+ expect(validateToolsSearch({ server: "github" })).toEqual({});
+ expect(validateToolsSearch({ tab: "mcp", skill: "review" })).toEqual({ tab: "mcp" });
+ expect(validateToolsSearch({ tab: "mcp", server: "" })).toEqual({ tab: "mcp" });
+ });
+});
+
const provider = (
instanceId: string,
skills: ServerProvider["skills"],
diff --git a/apps/web/src/components/settings/toolsSettings.logic.ts b/apps/web/src/components/settings/toolsSettings.logic.ts
index 1d6dab1fbc08c..aea3bed186aec 100644
--- a/apps/web/src/components/settings/toolsSettings.logic.ts
+++ b/apps/web/src/components/settings/toolsSettings.logic.ts
@@ -15,17 +15,26 @@ import { resolveProviderSkillSourceKind } from "@t3tools/client-runtime/provider
export type ToolsTab = "skills" | "mcp";
-/** `tab` picks the tab; `skill` is the skill whose page is open on the Skills tab. */
+/**
+ * `tab` picks the tab; `skill` is the skill whose page is open on the Skills
+ * tab, and `server` the MCP server whose page is open on the MCP servers tab.
+ */
export function validateToolsSearch(raw: Record): {
tab?: ToolsTab;
skill?: string;
+ server?: string;
} {
const tab = raw.tab === "mcp" || raw.tab === "skills" ? raw.tab : undefined;
const skill =
tab !== "mcp" && typeof raw.skill === "string" && raw.skill.length > 0 ? raw.skill : undefined;
+ const server =
+ tab === "mcp" && typeof raw.server === "string" && raw.server.length > 0
+ ? raw.server
+ : undefined;
return {
...(tab === undefined ? {} : { tab }),
...(skill === undefined ? {} : { skill }),
+ ...(server === undefined ? {} : { server }),
};
}
diff --git a/apps/web/src/components/settings/useEscapeToList.ts b/apps/web/src/components/settings/useEscapeToList.ts
new file mode 100644
index 0000000000000..96bc2a320225a
--- /dev/null
+++ b/apps/web/src/components/settings/useEscapeToList.ts
@@ -0,0 +1,29 @@
+import { useEffect, useEffectEvent } from "react";
+
+/**
+ * Escape goes from a page on the Tools tab (a skill, an MCP server) back to
+ * its list. Settings leaves the page on Escape from its own window listener,
+ * so this one runs first, in the capture phase. Escape inside a field, dialog
+ * or menu belongs to that control.
+ */
+export function useEscapeToList(onBack: () => void) {
+ const goBack = useEffectEvent((event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.defaultPrevented || event.repeat || event.isComposing)
+ return;
+ if (
+ event.target instanceof Element &&
+ event.target.closest(
+ 'input,textarea,select,[contenteditable],[role="dialog"],[role="alertdialog"],[role="menu"]',
+ )
+ )
+ return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ onBack();
+ });
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => goBack(event);
+ window.addEventListener("keydown", onKeyDown, { capture: true });
+ return () => window.removeEventListener("keydown", onKeyDown, { capture: true });
+ }, []);
+}
diff --git a/apps/web/src/routes/settings.tools.tsx b/apps/web/src/routes/settings.tools.tsx
index 7654a6fc2a473..14a974b11b37b 100644
--- a/apps/web/src/routes/settings.tools.tsx
+++ b/apps/web/src/routes/settings.tools.tsx
@@ -4,7 +4,7 @@ import { ToolsSettings } from "../components/settings/ToolsSettings";
import { validateToolsSearch } from "../components/settings/toolsSettings.logic";
function SettingsToolsRoute() {
- const { tab, skill } = Route.useSearch();
+ const { tab, skill, server } = Route.useSearch();
const navigate = Route.useNavigate();
// A settings search result links by hash, so it opens the tab it points at.
const hash = useLocation({ select: (location) => location.hash });
@@ -13,6 +13,7 @@ function SettingsToolsRoute() {
void navigate({
// The settings route keeps the scope; Skills is the default tab.
@@ -21,8 +22,8 @@ function SettingsToolsRoute() {
resetScroll: false,
})
}
- // Like a tab, a skill's page replaces the entry: Escape from the list
- // then still leaves Settings rather than reopening the skill.
+ // Like a tab, a skill's or server's page replaces the entry: Escape from
+ // the list then still leaves Settings rather than reopening the page.
onOpenSkill={(name) =>
void navigate({
search: name === null ? {} : { skill: name },
@@ -30,6 +31,13 @@ function SettingsToolsRoute() {
resetScroll: false,
})
}
+ onOpenServer={(name) =>
+ void navigate({
+ search: name === null ? { tab: "mcp" } : { tab: "mcp", server: name },
+ replace: true,
+ resetScroll: false,
+ })
+ }
/>
);
}
diff --git a/docs/user/tools.md b/docs/user/tools.md
index c779cdc22a57d..e2f0bffb3e416 100644
--- a/docs/user/tools.md
+++ b/docs/user/tools.md
@@ -63,5 +63,10 @@ With a project selected, servers you add belong to that project. Giving one the
environment server replaces it for the project, which is how to point a project at a different
account. Inherited servers can be switched off for the project without removing them elsewhere.
+Open a server, including `t3-code`, to see its tools and the parameters each takes. T3 Code starts
+the server the way an agent would to ask for them, so this works for a server that's switched off
+too, and needs permission to manage providers. A URL server that wants you to sign in can't be
+listed this way; add an access token as a header instead.
+
Claude, Codex, Cursor, OpenCode, Grok and other ACP agents get these servers. ACP agents that don't
support URL servers only get command servers. Pi isn't supported yet.
From 88a827bba7eaa75d0d50e1f70b5c1bc1f4cfb0e5 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Sun, 11 Oct 2026 02:19:31 -0700
Subject: [PATCH 35/35] chore(web): drop an unused import left by combining the
Tools changes
Co-Authored-By: Claude Opus 5.5
---
apps/web/src/components/settings/ToolsSettings.tsx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/apps/web/src/components/settings/ToolsSettings.tsx b/apps/web/src/components/settings/ToolsSettings.tsx
index 2620c3a3351e8..33437a97000af 100644
--- a/apps/web/src/components/settings/ToolsSettings.tsx
+++ b/apps/web/src/components/settings/ToolsSettings.tsx
@@ -31,7 +31,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import { useAfterDelay } from "../../hooks/useAfterDelay";
import { cn } from "../../lib/utils";
-import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
+import { formatEnvironmentQueryError } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useEnvironmentsWithScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";