diff --git a/apps/server/package.json b/apps/server/package.json index 8b6aebfa4d376..3ff7d2c0282c5 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -37,6 +37,7 @@ "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", "@ff-labs/fff-node": "0.11.0", + "@modelcontextprotocol/sdk": "1.29.0", "@muse-code/sdk": "1.4.6", "@napi-rs/keyring": "^1.3.0", "@opencode-ai/sdk": "^1.3.15", @@ -60,6 +61,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", "undici": "catalog:", @@ -69,7 +71,6 @@ "devDependencies": { "@effect/graphql-generator": "catalog:", "@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.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index e97a9c36f896c..7378d6b054d1b 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, @@ -219,6 +220,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 27cc380086b86..a29fb8487a5fa 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, requiredScopesForProjectMutation, @@ -154,6 +155,16 @@ 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, + // 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.projectsListIgnoredFiles]: AuthFilesystemReadScope, [WS_METHODS.projectsReadFile]: AuthFilesystemReadScope, @@ -245,9 +256,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) @@ -260,6 +274,7 @@ const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation); const requiredScopesForRpcCall = ( method: string, payload: unknown, + currentSettings?: Pick, ): ReadonlyArray => { if (method === WS_METHODS.serverRetryResourceTelemetry) { return [AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope]; @@ -274,7 +289,9 @@ const requiredScopesForRpcCall = ( : AuthOrchestrationReadScope, ]; } - if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload); + if (method === WS_METHODS.serverUpdateSettings) { + return requiredScopesForSettingsUpdate(payload, currentSettings); + } if (method === WS_METHODS.projectsMutate) { return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } @@ -284,22 +301,34 @@ const requiredScopesForRpcCall = ( }; /** + * 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`. + * * `onAuthorized` runs once after an authorized request succeeds; for a stream * RPC, that is when the stream completes. Every RPC passes through here, so it * is the one place to observe requests without wrapping each handler. */ export const layer = ( scopes: ReadonlyArray, + currentSettings: Effect.Effect< + Pick | undefined + > = Effect.succeed(undefined), onAuthorized?: (method: string, payload: unknown) => Effect.Effect, ) => - Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => { - const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload); - const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope)); - if (requiredScope !== undefined) return Effect.fail(rpcAuthorizationError(requiredScope)); - return onAuthorized === undefined - ? effect - : Effect.tap(effect, () => onAuthorized(rpc._tag, payload)); - }); + 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)); + if (requiredScope !== undefined) + return yield* Effect.fail(rpcAuthorizationError(requiredScope)); + return yield* onAuthorized === undefined + ? effect + : Effect.tap(effect, () => onAuthorized(rpc._tag, payload)); + }), + ); /** Retrying can install or restart tools even though ordinary listing is readable. */ export const requiredScopeForDeviceList = (input: DeviceListInput): AuthEnvironmentScope => diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 8138631ed026c..ef1a253f0b8c2 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -23,6 +23,10 @@ if ( } else 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 { // Before anything reads stdin: the desktop app's Windows launcher starts // the CLI without one. Never for the fast paths, whose stdin is a pipe. diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 2f7c24536caaa..4d1ece613cee0 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -9,6 +9,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"; @@ -70,6 +71,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..9ca9290579144 --- /dev/null +++ b/apps/server/src/cli/skillsCli.ts @@ -0,0 +1,33 @@ +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 prints its `--json` result and calls `process.exit` straight + // 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"); +} + +/** 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/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 53eaa6bb26c91..69133aa9564a6 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -198,6 +198,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/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 1230f2c09bcc8..12393ef40dcb3 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -43,7 +43,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"; @@ -1055,6 +1057,10 @@ const layerEnvironmentToolkit = toolkitRegistration( const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer); +const layerToolsRegistration = toolkitRegistration(ToolsToolkit, ToolsHandlers.layer).pipe( + Layer.provide(ThreadCommandExecutor.layer), +); + export const layerAttachmentToolkit = toolkitRegistration( AttachmentToolkit, AttachmentHandlers.layer, @@ -1148,6 +1154,31 @@ export const layerMcpTransport = McpServer.layerHttp({ allowSessionTermination: true, }).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, + DocsToolkit, + AipmToolkit, + McpServersToolkit, +]; + export const layer = Layer.mergeAll( layerPreviewToolkit, layerOrchestratorToolkit, @@ -1155,6 +1186,7 @@ export const layer = Layer.mergeAll( layerAttachmentToolkit, layerProjectRegistration, layerEnvironmentToolkit, + layerToolsRegistration, layerPreviewControlsRegistration, layerWorktreeToolkitRegistration, layerPullRequestsToolkit, diff --git a/apps/server/src/mcp/resolveAgentTools.ts b/apps/server/src/mcp/resolveAgentTools.ts new file mode 100644 index 0000000000000..bde07687359b2 --- /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 "@t3tools/provider-core/server/mcpSession"; + +/** + * 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/mcp/toolkits/tools/handlers.test.ts b/apps/server/src/mcp/toolkits/tools/handlers.test.ts new file mode 100644 index 0000000000000..b8c0012a30290 --- /dev/null +++ b/apps/server/src/mcp/toolkits/tools/handlers.test.ts @@ -0,0 +1,156 @@ +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>([]); + // 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, { + 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).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)), + ), + ), + }), + 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"]); + + // 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( + 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..e196af17d59cd --- /dev/null +++ b/apps/server/src/mcp/toolkits/tools/handlers.ts @@ -0,0 +1,182 @@ +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), + })), + }; +} + +/** + * 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; + 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; + 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); + }), + ), + ), + 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..266e15ce6950d --- /dev/null +++ b/apps/server/src/mcp/toolkits/tools/tools.ts @@ -0,0 +1,102 @@ +import { + InstalledSkillName, + McpServerName, + OrchestratorMcpFailure, + ProjectId, + SkillInstallInput, + 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. Servers in Settings → MCP Servers are listed with mcp_servers_list instead.", + 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. Servers in Settings → MCP Servers are switched with mcp_server_set_enabled instead.", + 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: SkillInstallInput.fields.skills, + }), + success: SkillInstallResult, +}).annotate(Tool.Destructive, true); + +const SkillsRemoveTool = Tool.make("t3_skills_remove", { + ...shared, + description: + "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); + +export const ToolsToolkit = Toolkit.make( + ToolsReadTool, + ToolsUpdateTool, + SkillsInstallTool, + SkillsRemoveTool, +); diff --git a/apps/server/src/mcpHub/McpServerOAuth.ts b/apps/server/src/mcpHub/McpServerOAuth.ts index f8358984769b2..48d8072fec496 100644 --- a/apps/server/src/mcpHub/McpServerOAuth.ts +++ b/apps/server/src/mcpHub/McpServerOAuth.ts @@ -19,7 +19,7 @@ import { } from "@modelcontextprotocol/sdk/shared/auth.js"; import { MCP_CLIENT_OAUTH_CALLBACK_PATH, - type McpServerConfig, + type McpHubServerConfig, type McpServerEntry, McpServerError, type McpServerId, @@ -63,12 +63,12 @@ interface PendingSignIn { discovery: OAuthDiscoveryState | undefined; } -type OAuthServerConfig = McpServerConfig & { +type OAuthServerConfig = McpHubServerConfig & { readonly transport: { readonly type: "http"; readonly url: string }; - readonly auth: Extract; + readonly auth: Extract; }; -const isOAuthServer = (config: McpServerConfig): config is OAuthServerConfig => +const isOAuthServer = (config: McpHubServerConfig): config is OAuthServerConfig => config.auth.type === "oauth" && config.transport.type === "http"; /** Tokens for one server or registered client are not valid for another. */ @@ -131,7 +131,7 @@ export class McpServerOAuth extends Context.Service< * interactive sign-in: those fail with the SDK's UnauthorizedError. */ readonly forwardingProvider: ( - config: McpServerConfig, + config: McpHubServerConfig, ) => Effect.Effect; } >()("t3/mcpHub/McpServerOAuth") {} diff --git a/apps/server/src/mcpHub/McpServerRegistry.ts b/apps/server/src/mcpHub/McpServerRegistry.ts index ccc96ed375381..99c8faa725508 100644 --- a/apps/server/src/mcpHub/McpServerRegistry.ts +++ b/apps/server/src/mcpHub/McpServerRegistry.ts @@ -6,7 +6,7 @@ */ import { type McpSecretInput, - McpServerConfig, + McpHubServerConfig, type McpServerEntry, McpServerError, McpServerId, @@ -38,7 +38,7 @@ import * as ServerConfig from "../config.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; const StoredServers = Schema.fromJsonString( - Schema.Struct({ servers: Schema.Array(McpServerConfig) }), + Schema.Struct({ servers: Schema.Array(McpHubServerConfig) }), ); const decodeStored = Schema.decodeUnknownEffect(StoredServers); const encodeStored = Schema.encodeEffect(StoredServers); @@ -56,7 +56,7 @@ const oauthSessionSecretNames = (id: McpServerId) => [ oauthRegistrationSecretName(id), ]; -const secretNames = (config: McpServerConfig): ReadonlyArray => [ +const secretNames = (config: McpHubServerConfig): ReadonlyArray => [ ...(config.auth.type === "header" ? [headerSecretName(config.id)] : []), ...(config.auth.type === "oauth" ? [ @@ -70,7 +70,7 @@ const secretNames = (config: McpServerConfig): ReadonlyArray => [ ]; /** Tokens from one server or client are useless, and possibly unsafe, for another. */ -const oauthIdentity = (config: McpServerConfig) => +const oauthIdentity = (config: McpHubServerConfig) => config.auth.type === "oauth" && config.transport.type === "http" ? `${config.transport.url} ${config.auth.client?.clientId ?? ""}` : undefined; @@ -85,7 +85,9 @@ export class McpServerRegistry extends Context.Service< McpServerRegistry, { readonly list: Effect.Effect; - readonly get: (id: McpServerId) => Effect.Effect; + readonly get: ( + id: McpServerId, + ) => Effect.Effect; /** `projectId` scopes secretRef consumption to the calling thread's project. */ readonly upsert: ( input: McpServerUpsertInput, @@ -96,7 +98,7 @@ export class McpServerRegistry extends Context.Service< input: McpServerSetEnabledInput, ) => Effect.Effect; readonly credentials: ( - config: McpServerConfig, + config: McpHubServerConfig, ) => Effect.Effect; readonly reportStatus: (id: McpServerId, status: McpServerStatus) => Effect.Effect; /** Drops the server's client and reported status after its stored sign-in changed. */ @@ -117,7 +119,7 @@ const make = Effect.gen(function* () { const filePath = path.join(path.dirname(settingsPath), "mcp-servers.json"); const lock = yield* Semaphore.make(1); - const cache = yield* Ref.make | undefined>(undefined); + const cache = yield* Ref.make | undefined>(undefined); const statuses = yield* Ref.make>(new Map()); const changed = yield* PubSub.unbounded(); // Subscribers re-read the whole list, so one pending signal covers any burst. @@ -136,7 +138,7 @@ const make = Effect.gen(function* () { return servers; }).pipe(Effect.mapError((cause) => new McpServerError({ reason: "read_failed", cause }))); - const save = (servers: ReadonlyArray) => + const save = (servers: ReadonlyArray) => encodeStored({ servers }).pipe( Effect.flatMap((contents) => writeFileStringAtomically({ filePath, contents: `${contents}\n` }), @@ -156,7 +158,7 @@ const make = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); - const statusOf = (config: McpServerConfig) => + const statusOf = (config: McpHubServerConfig) => Effect.gen(function* () { if (!config.enabled) return { state: "disabled" } as const; if (config.auth.type === "oauth" && !(yield* hasTokens(config.id))) { @@ -165,7 +167,7 @@ const make = Effect.gen(function* () { return (yield* Ref.get(statuses)).get(config.id) ?? ({ state: "idle" } as const); }); - const toEntry = (config: McpServerConfig) => + const toEntry = (config: McpHubServerConfig) => statusOf(config).pipe(Effect.map((status): McpServerEntry => ({ ...config, status }))); const markChanged = (id: McpServerId) => @@ -270,7 +272,7 @@ const make = Effect.gen(function* () { } const now = DateTime.formatIso(yield* DateTime.now); - const config: McpServerConfig = { + const config: McpHubServerConfig = { id, name: input.name, enabled: input.enabled ?? true, @@ -350,7 +352,7 @@ const make = Effect.gen(function* () { const servers = yield* load; const existing = servers.find((server) => server.id === input.id); if (existing === undefined) return yield* new McpServerError({ reason: "not_found" }); - const config: McpServerConfig = { + const config: McpHubServerConfig = { ...existing, enabled: input.enabled, updatedAt: DateTime.formatIso(yield* DateTime.now), diff --git a/apps/server/src/mcpHub/McpUpstreamClients.ts b/apps/server/src/mcpHub/McpUpstreamClients.ts index 9449f15450cb5..846874344ed16 100644 --- a/apps/server/src/mcpHub/McpUpstreamClients.ts +++ b/apps/server/src/mcpHub/McpUpstreamClients.ts @@ -4,7 +4,11 @@ * reconnects, and closes after sitting idle, which also stops a stdio server's * process. Upstream credentials are attached here and never leave the server. */ -import { type McpServerConfig, type McpServerId, type McpServerStatus } from "@t3tools/contracts"; +import { + type McpHubServerConfig, + type McpServerId, + type McpServerStatus, +} from "@t3tools/contracts"; import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { @@ -94,7 +98,7 @@ interface Entry { * UnauthorizedError or an OAuth error from the token endpoint. */ const authFailure = ( - config: McpServerConfig, + config: McpHubServerConfig, cause: unknown, ): UpstreamFailureReason | undefined => { if (cause instanceof StreamableHTTPError && (cause.code === 401 || cause.code === 403)) { @@ -110,7 +114,7 @@ const authFailure = ( return undefined; }; -const connectFailure = (config: McpServerConfig, cause: unknown): UpstreamFailureReason => +const connectFailure = (config: McpHubServerConfig, cause: unknown): UpstreamFailureReason => authFailure(config, cause) ?? "unavailable"; const statusFor = (reason: UpstreamFailureReason): McpServerStatus => @@ -134,7 +138,7 @@ const make = Effect.gen(function* () { if (entry.connected !== undefined) yield* closeClient(entry.connected); }); - const connect = (config: McpServerConfig) => + const connect = (config: McpHubServerConfig) => Effect.gen(function* () { const fail = (reason: UpstreamFailureReason, cause?: unknown) => new McpUpstreamError({ @@ -171,7 +175,7 @@ const make = Effect.gen(function* () { return client; }); - const acquire = (config: McpServerConfig) => + const acquire = (config: McpHubServerConfig) => Effect.gen(function* () { const existing = entries.get(config.id); if (existing !== undefined) return existing; diff --git a/apps/server/src/mcpServerSecrets.ts b/apps/server/src/mcpServerSecrets.ts new file mode 100644 index 0000000000000..2bf030836597e --- /dev/null +++ b/apps/server/src/mcpServerSecrets.ts @@ -0,0 +1,239 @@ +/** + * 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). */ +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: "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, + * 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 Map(); + for (const site of variableSites(current)) { + 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 { 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); + 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); + 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.keys()) { + 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/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..ad86d81631a51 --- /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 * as HostProcess 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* HostProcess.Environment; + 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 83da21d14884e..f52f3532c1583 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -34,6 +34,14 @@ 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.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/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 68cc750a3b802..dd75c54feb110 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -429,11 +429,14 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { type: "http", url: "http://127.0.0.1:43123/mcp", headers: { - Authorization: "Bearer secret-claude-token", + Authorization: "${T3_CODE_MCP_AUTHORIZATION}", }, timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS, }, } as const; + const T3_MCP_ENVIRONMENT = { + T3_CODE_MCP_AUTHORIZATION: "Bearer secret-claude-token", + } as const; const mcpSessionFor = ( threadId: ThreadId, @@ -463,6 +466,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { ...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS, ], mcpServers: T3_MCP_SERVERS, + mcpEnvironment: T3_MCP_ENVIRONMENT, }); assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD)); }); @@ -492,6 +496,98 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { assert.notEqual(rotatedKey, initialKey); }); + 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 mcpSession: McpProviderSession.McpProviderSessionConfig = { + ...mcpSessionFor(threadId), + 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", + }, + }; + const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( + ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }), + ); + const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({ + mcpSession, + readOnlySandbox: false, + }); + // The secret reaches the child's environment, never `--mcp-config`. + assert.deepEqual(overrides, { + // Its tools go through the session's approval like any other tool. + allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD], + mcpServers: { + supabase: { + type: "stdio", + command: "npx", + args: ["-y", "@supabase/mcp-server-supabase"], + env: { SUPABASE_ACCESS_TOKEN: "${T3_MCP_SECRET_0}" }, + }, + ...T3_MCP_SERVERS, + }, + sdkSettings: { skillOverrides: { "grill-me": "off" } }, + mcpEnvironment: { T3_MCP_SECRET_0: "token", ...T3_MCP_ENVIRONMENT }, + }); + // 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( + queryPolicy, + ClaudeAdapterV2.claudeMcpQueryOverrides({ + mcpSession: { ...mcpSession, tools: { servers: [], disabledSkills: [], fingerprint: "" } }, + readOnlySandbox: false, + }), + ); + assert.notEqual(clearedKey, initialKey); + }); + it("matches the read-only allowlist to the orchestrator toolkit annotations", () => { const readOnlyToolNames = [ ...Object.values(OrchestratorToolkit.tools), @@ -539,11 +635,12 @@ describe("ClaudeAdapterV2 native protocol logging", () => { type: "http", url: "http://127.0.0.1:43123/mcp", headers: { - Authorization: "Bearer secret-claude-token", + Authorization: "${T3_CODE_MCP_AUTHORIZATION}", }, timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS, }, }, + mcpEnvironment: { T3_CODE_MCP_AUTHORIZATION: "Bearer secret-claude-token" }, }); const options = ClaudeAdapterV2.makeClaudeQueryOptions({ @@ -966,6 +1063,107 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { ); }); +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, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + stopTask: () => 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* () { @@ -13379,7 +13577,10 @@ describe("ClaudeAdapterV2 configured MCP servers", () => { assert.deepEqual(overrides.mcpServers?.notion, { type: "http", url: "http://127.0.0.1:43123/mcp/upstream/server-notion", - headers: { Authorization: "Bearer thread-token" }, + headers: { Authorization: "${T3_CODE_MCP_AUTHORIZATION}" }, + }); + assert.deepEqual(overrides.mcpEnvironment, { + T3_CODE_MCP_AUTHORIZATION: "Bearer thread-token", }); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 4d5ba816dafd4..a5fa0c133a25c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -66,6 +66,7 @@ import { ClaudeSettings, TrimmedNonEmptyString, defaultInstanceIdForDriver, + mcpServerVariableRecord, type ModelSelection, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, @@ -95,6 +96,8 @@ import { type ProviderRequestKind, type ProviderUserInputAnswers, type ProviderThreadId, + type McpServerVariable, + type ResolvedMcpServer, type RunId, type ThreadId, resolveIdleCompaction, @@ -1395,7 +1398,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), ...launchAppendSystemPrompt, ].join("\n\n"), }, @@ -1490,6 +1493,13 @@ export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000; // pre-approve only the annotated read-only orchestrator tools so a read-only session cannot // silently spawn threads or scheduled tasks. +// +// The SDK passes `mcpServers` to the CLI as an inline `--mcp-config` argument, +// and process arguments are readable by every local user. The credential +// therefore travels in the child's environment, which only its owner can read, +// and the CLI expands the `${VAR}` reference when it connects. +const CLAUDE_T3_MCP_AUTHORIZATION_ENV = "T3_CODE_MCP_AUTHORIZATION"; + export function claudeMcpQueryOverrides(input: { readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; readonly readOnlySandbox: boolean; @@ -1497,23 +1507,30 @@ export function claudeMcpQueryOverrides(input: { }): { readonly allowedTools?: ReadonlyArray; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + readonly sdkSettings?: ClaudeSdkSettings; + readonly mcpEnvironment?: Readonly>; } { const session = input.mcpSession; if (session === undefined) { return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }; } + const tools = session.tools ?? McpProviderSession.EMPTY_MCP_PROVIDER_SESSION_TOOLS; const upstreamServers = input.readOnlySandbox ? [] : (session.upstreamServers ?? []); const mcpAllowedTools = input.readOnlySandbox ? CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS : [CLAUDE_T3_MCP_TOOL_WILDCARD, ...upstreamServers.map((server) => `mcp__${server.name}__*`)]; + // Settings → Tools 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])), mcpServers: { + ...userServers.mcpServers, "t3-code": { type: "http", url: session.endpoint, headers: { - Authorization: session.authorizationHeader, + Authorization: `\${${CLAUDE_T3_MCP_AUTHORIZATION_ENV}}`, }, timeout: CLAUDE_T3_MCP_TOOL_TIMEOUT_MS, }, @@ -1523,14 +1540,73 @@ export function claudeMcpQueryOverrides(input: { { type: "http" as const, url: server.endpoint, - headers: { Authorization: session.authorizationHeader }, + headers: { Authorization: `\${${CLAUDE_T3_MCP_AUTHORIZATION_ENV}}` }, }, ]), ), }, + ...(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]), + ), + }, + }), + mcpEnvironment: { + ...userServers.environment, + [CLAUDE_T3_MCP_AUTHORIZATION_ENV]: session.authorizationHeader, + }, }; } +/** + * 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 = (variables: ReadonlyArray) => { + const record = mcpServerVariableRecord(variables); + // 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[name]!; + record[name] = `\${${reference}}`; + } + return record; + }; + const mcpServers = Object.fromEntries( + servers.map((server) => [ + server.name, + server.transport.type === "stdio" + ? { + type: "stdio" as const, + command: server.transport.command, + args: [...server.transport.args], + env: values(server.transport.env), + } + : { + type: "http" as const, + url: server.transport.url, + headers: values(server.transport.headers), + }, + ]), + ); + return { mcpServers, environment }; +} + function providerSession(input: { readonly providerSessionId: OrchestrationV2ProviderSession["id"]; readonly providerInstanceId: ProviderInstanceId; @@ -2227,6 +2303,8 @@ export function claudeEffectiveQueryPolicyKey( mcpOverrides: { readonly allowedTools?: ReadonlyArray; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + readonly sdkSettings?: ClaudeSdkSettings; + readonly mcpEnvironment?: Readonly>; }, ): string { return JSON.stringify({ @@ -2237,6 +2315,9 @@ export function claudeEffectiveQueryPolicyKey( : { allowedTools: mcpOverrides.allowedTools }), }), mcpServers: mcpOverrides.mcpServers, + // Skill switches load at process start, so a change reopens the query. + sdkSettings: mcpOverrides.sdkSettings, + mcpEnvironment: mcpOverrides.mcpEnvironment, }); } @@ -9301,7 +9382,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( attachmentsDir, settings: adapterOptions.settings, environment: claudeQueryEnvironment( - adapterOptions.environment, + { ...adapterOptions.environment, ...mcpOverrides.mcpEnvironment }, turnInput.appThread, turnInput.appThread.lineage.relationshipToParent === "subagent" ? yield* resolveSubagentPromptCacheTtl(turnInput.runtimePolicy.cwd) @@ -9314,6 +9395,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 ? {} diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 7f07a5d4a87c6..2a635eb565c60 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -51,6 +51,7 @@ import { TestClock } from "effect/testing"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import packageJson from "../../../package.json" with { type: "json" }; +import type * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -6532,6 +6533,41 @@ describe("CodexAdapterV2 configured MCP servers", () => { assert.deepEqual(mcpServerKeys(config), ["mcp_servers.t3-code", "mcp_servers.notion"]); }); + it("adds the user's servers and disabled skills to thread config", () => { + const threadId = ThreadId.make("thread-codex-user-tools"); + const toolsSession: McpProviderSession.McpProviderSessionConfig = { + 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", + }, + }; + + const { config } = CodexAdapterV2.codexThreadRuntimeParams({ mcpSession: toolsSession }); + assert.deepEqual(mcpServerKeys(config), ["mcp_servers.linear", "mcp_servers.t3-code"]); + assert.deepEqual(config["mcp_servers.linear"], { + url: "https://mcp.linear.app/mcp", + http_headers: { Authorization: "Bearer lin" }, + }); + assert.deepEqual(config.skills, { config: [{ name: "grill-me", enabled: false }] }); + }); + it("reads the user's Codex MCP server names from config/read", () => { assert.deepEqual( [ diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 98cc3741def39..52419a5dd19af 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -30,6 +30,7 @@ import { CodexSettings, defaultInstanceIdForDriver, isOrchestrationV2WorkActive, + mcpServerVariableRecord, OrchestrationV2ProviderGoal, ProviderDriverKind, type ProviderSetupError, @@ -68,6 +69,7 @@ import type { ProviderThreadId, ProviderTurnId, ProviderInstanceId, + ResolvedMcpServer, RuntimeMode, RuntimeRequestId, ThreadId, @@ -1392,6 +1394,7 @@ export function codexThreadRuntimeParams(input: { readonly config: Readonly>; } { const { mcpSession } = input; + 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 }), @@ -1400,7 +1403,12 @@ export function codexThreadRuntimeParams(input: { ...(mcpSession === undefined ? {} : { - // Override only T3's server so launch-argument MCP servers survive. + // Dotted keys override single servers, so launch-argument MCP servers survive. + ...Object.fromEntries( + Object.entries(codexUserMcpServers(tools.servers)) + .filter(([name]) => !input.userMcpServerNames?.has(name)) + .map(([name, server]) => [`mcp_servers.${name}`, server]), + ), "mcp_servers.t3-code": { url: mcpSession.endpoint, tool_timeout_sec: CODEX_T3_MCP_TOOL_TIMEOUT_SEC, @@ -1420,10 +1428,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/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 302b29ddab2ad..113e81cd55c5a 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -82,11 +82,16 @@ const event = ( }); const durable = { durable: { aggregateID: SESSION, seq: 1, version: 1 } }; +/** + * The rules T3 gives every session it runs: only this thread's own T3 MCP + * server and hub servers are 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: "t3-mcp-*", resource: "*", effect: "deny" }, { action: "t3-mcp-c26f2f1f-*", resource: "*", effect: "allow" }, + { action: "t3u-*", resource: "*", effect: "deny" }, ]; const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules]; const TITLE = "Prime check"; @@ -2448,6 +2453,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { { action: `${server}_*`, resource: "*", effect: "allow" }, { action: "t3-mcp-*", resource: "*", effect: "deny" }, { action: "t3-mcp-aa73fa1e-*", resource: "*", effect: "allow" }, + { action: "t3u-*", resource: "*", effect: "deny" }, ], }), ), @@ -3855,6 +3861,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { { action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" }, { action: "t3-mcp-*", resource: "*", effect: "deny" }, { action: "t3-mcp-7c81f4ba-*", 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 187c25935a07b..2da60ba6490a5 100644 --- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts +++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts @@ -62,11 +62,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" }]; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 17d78ecda3c55..b354bb1aa3a1f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -43,7 +43,11 @@ import { import { ProviderWorkspaceMissingError } from "../provider/Errors.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; -import type * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; +import { + EMPTY_MCP_PROVIDER_SESSION_TOOLS, + type McpUpstreamServerEntry, +} from "@t3tools/provider-core/server/mcpSession"; +import { resolveAgentTools } from "../mcp/resolveAgentTools.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import * as McpServerRegistry from "../mcpHub/McpServerRegistry.ts"; @@ -334,7 +338,7 @@ export const layerWithOptions = ( */ const upstreamServers = ( endpoint: string, - ): Effect.Effect> => + ): Effect.Effect> => Option.isNone(mcpServerRegistry) ? Effect.succeed([]) : mcpServerRegistry.value.list.pipe( @@ -360,7 +364,12 @@ export const layerWithOptions = ( const agentScope = yield* AgentScope; 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: EMPTY_MCP_PROVIDER_SESSION_TOOLS, + }; return yield* Effect.gen(function* () { const settings = yield* serverSettings.value.getSettings; const thread = yield* projectionStore.getThread(threadId); @@ -379,19 +388,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: EMPTY_MCP_PROVIDER_SESSION_TOOLS, + }), + ), ), ); }, @@ -478,8 +495,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"]); @@ -509,9 +529,12 @@ 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. yield* mcpSessions.set({ ...existing, upstreamServers: yield* upstreamServers(existing.endpoint), + tools, }); return { mcpCredentialId: existing.providerSessionId, issued: false }; } @@ -527,6 +550,7 @@ export const layerWithOptions = ( yield* mcpSessions.set({ ...credential.config, upstreamServers: yield* upstreamServers(credential.config.endpoint), + tools, }); reserveMcpCredential(threadId, credential.config.providerSessionId); return { mcpCredentialId: credential.config.providerSessionId, issued: true }; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 10caf988e475f..da024dcd3cca3 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -553,6 +553,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/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_fork/opencode_transcript.ndjson index 57cbd14853460..d988be1e97791 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.update.title", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "title": ""}}} 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 ee2519419915a..f208396f5f914 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/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 8bcde5f9420ca..556efc229486b 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -269,6 +269,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/server.ts b/apps/server/src/server.ts index 34f592b092cc4..94bb96e8e234f 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -70,6 +70,7 @@ import * as McpServerRegistry from "./mcpHub/McpServerRegistry.ts"; import * as McpUpstreamClients from "./mcpHub/McpUpstreamClients.ts"; import * as DocCommentsService from "./docs/DocCommentsService.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"; @@ -95,6 +96,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"; @@ -607,6 +609,8 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( layerProviderInstallationRefresh, ReplayMarkers.layer, Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), + SkillLibrary.layer.pipe(Layer.provide(ProcessRunner.layer)), + McpServerTools.layer, ).pipe( Layer.provideMerge(layerOrchestrationApplication), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index ac4e0d394284a..eb46d5cbefd61 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1403,6 +1403,224 @@ 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("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("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; + 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("keeps the retired keys for another load when a token cannot be copied", () => { const cause = new ServerSecretStore.SecretStoreReadError({ resource: "bitbucket-access-token", diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 65c114c75ca8d..0c0d61439f206 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -54,6 +54,12 @@ import { readSecretFieldValues, sourceControlHostSecretName, } from "./sourceControl/sourceControlHostSecrets.ts"; +import { + materializeMcpServerSecrets, + mcpServerSecretNames, + planMcpServerSecrets, + redactMcpServerSecrets, +} from "./mcpServerSecrets.ts"; import { mapSettingsSecrets, SECRET_REDACTED, type SettingsSecret } from "./settingsSecrets.ts"; @@ -132,10 +138,12 @@ const normalizeServerSettings = ( ); export function redactServerSettingsForClient(settings: ServerSettings): ServerSettings { - return mapSettingsSecrets(settings, (secret) => - secret.sensitive - ? { value: "", redacted: secret.redacted || secret.value.length > 0 } - : { value: secret.value, redacted: false }, + return redactMcpServerSecrets( + mapSettingsSecrets(settings, (secret) => + secret.sensitive + ? { value: "", redacted: secret.redacted || secret.value.length > 0 } + : { value: secret.value, redacted: false }, + ), ); } @@ -185,6 +193,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; + readonly updateProviderInstance: ( mutation: ProviderInstanceMutation, patch?: ServerSettingsPatch, @@ -245,6 +261,10 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( 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* () { @@ -833,13 +853,27 @@ const make = Effect.gen(function* () { Option.isSome(value) ? textDecoder.decode(value.value) : "", ); } - return mapSettingsSecrets(settings, (secret) => ({ - value: - secret.sensitive && secret.redacted - ? (storedSecrets.get(secret.secretName) ?? "") - : secret.value, - redacted: secret.sensitive && secret.kind === "environment" && secret.redacted, - })); + 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( + mapSettingsSecrets(settings, (secret) => ({ + value: + secret.sensitive && secret.redacted + ? (storedSecrets.get(secret.secretName) ?? "") + : secret.value, + redacted: secret.sensitive && secret.kind === "environment" && secret.redacted, + })), + mcpSecrets, + ); }, ); @@ -866,6 +900,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" } ); @@ -923,7 +959,21 @@ const make = Effect.gen(function* () { : {}), }); } - return { settings, changes }; + const mcp = planMcpServerSecrets(current, settings); + for (const change of mcp.changes) { + changes.push( + change.kind === "write" + ? { + kind: "write", + secretName: change.secretName, + value: textEncoder.encode(change.value), + } + : change.kind === "copy" + ? { kind: "copy", secretName: change.secretName, from: change.from } + : { kind: "remove", secretName: change.secretName, operation: "remove-secret" }, + ); + } + return { settings: mcp.settings, changes }; }); const rollbackSettingsSecretWrites = ( @@ -960,43 +1010,63 @@ const make = Effect.gen(function* () { readonly environmentVariable?: string; }> = []; const rollback = Effect.suspend(() => rollbackSettingsSecretWrites(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, + }), + ), + ); + 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( - changes, + changes.filter((change) => change.kind === "copy"), (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, - }), - ), - ); - // 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) - : secretStore.remove(change.secretName) - ).pipe( - Effect.mapError( - (cause) => - new ServerSettingsError({ - settingsPath, - operation: change.kind === "write" ? "write-secret" : change.operation, - 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), ); @@ -1163,6 +1233,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 new file mode 100644 index 0000000000000..bd3e6843af727 --- /dev/null +++ b/apps/server/src/skills/SkillLibrary.test.ts @@ -0,0 +1,572 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, expect, it } from "@effect/vitest"; +import { + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import * as HostProcess 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"; +import { lockedInstallSource } 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."), + ); + // 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>([]); + const record = (entry: string) => + 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, 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"]; + 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(HostProcess.Environment, { + ...process.env, + HOME: home, + XDG_STATE_HOME: "", + }), + Effect.provideService(HostProcess.Arguments, [process.execPath, entry]), + Effect.provideService(HostProcess.IsExecutable, 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.folder, + skill.description, + skill.scripts, + ]), + [ + ["Git Review", "git-review", "Review with git.", false], + ["notes", "notes", "Take notes.", false], + ["review", "review", "Review a change.", true], + ], + ); + assert.deepEqual( + preview.skills[2]?.files.map((file) => [file.path, file.executable, file.script]), + [ + ["SKILL.md", false, false], + ["bin/run", true, 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)).filter((entry) => entry.startsWith("workspace:")), + [`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, +); + +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( + "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", + () => + 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, +); + +it.effect( + "keeps both lock entries when two installs run at once, and rescans listed projects", + () => + 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; + // 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, + ...listed, + driver: ProviderDriverKind.make("codex"), + instanceId: ProviderInstanceId.make("codex"), + }, + ]); + 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"]); + 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, + // 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, +); + +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, +); + +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"; + 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 new file mode 100644 index 0000000000000..8f562fcd2ed6c --- /dev/null +++ b/apps/server/src/skills/SkillLibrary.ts @@ -0,0 +1,859 @@ +/** + * 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 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 + */ +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, + type SkillInstallResult, + type SkillInstallTarget, + SkillLibraryError, + type SkillPreviewInput, + type SkillPreviewResult, +} from "@t3tools/contracts"; +import { + STANDARD_SKILL_FOLDER, + agentSkillFolderRoots, + skillLinkFolders, + skillsCliInstallAgents, +} from "@t3tools/provider-core/server/AgentSkillFolders"; +import * as HostProcess 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 Base64 from "effect/encoding/Base64"; +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 * as Semaphore from "effect/Semaphore"; +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 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; + /** 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") {} + +/** 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) })), +); + +/** 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; +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 `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. + */ +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, "") ?? ""; + if (folder !== "" && takesSubpath(source)) { + return { source: `${source}/${folder}${ref}`, fullDepth: false }; + } + return { source: `${source}${ref}`, fullDepth: folder !== "" }; +} + +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; + // 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* HostProcess.Environment; + + 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; + // 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 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 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( + scansByCwd, + ([cwd, instanceIds]) => + Effect.forEach( + instanceIds, + (instanceId, index) => + providerRegistry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh: index === 0 }), + { discard: 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 }; + const executable = info !== undefined && (info.mode & 0o111) !== 0; + files.push({ + path: childPath, + size: info === undefined ? 0 : Number(info.size), + executable, + script: executable || childPath.startsWith("bin/") || SCRIPT_EXTENSION.test(childPath), + }); + } + } + return { files, truncated }; + }); + + 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), + 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), + roots: yield* skillRoots(target), + }; + }), + ); + + 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 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 && + lockEntryFor(candidate.lock, name) !== undefined, + ); + const entry = + install === undefined ? undefined : lockEntryFor(install.lock, name)?.entry; + const { files, truncated } = yield* listFiles(folder); + return { + path: skillPath, + folder, + hash: yield* sha256(contents), + files, + filesTruncated: truncated, + scripts: hasScripts(files), + ...(location === undefined ? {} : { location }), + ...(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 folders = yield* fileSystem + .readDirectory(folder) + .pipe(Effect.orElseSucceed((): string[] => [])); + // 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, skillFolder); + const contents = yield* fileSystem + .readFileString(path.join(root, "SKILL.md")) + .pipe(Effect.orElseSucceed(() => "")); + const { files, truncated } = yield* listFiles(root); + return { + name: nameByFolder.get(skillFolder) ?? skillFolder, + folder: skillFolder, + 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, + fullDepth = false, + ) => + 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", + fullDepth, + 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).pipe(changes.withPermits(1)); + }, + ); + + /** 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 found = lockEntryFor(lock, name); + return found === undefined + ? Effect.fail( + new SkillLibraryError({ + reason: "notInstalled", + message: "Only skills installed from a source can be updated here.", + }), + ) + : Effect.succeed(found); + }), + ); + + const update: SkillLibrary["Service"]["update"] = Effect.fn("SkillLibrary.update")( + function* (input) { + const target = yield* resolveTarget(input.target); + return yield* updateLocked(target, input.name).pipe(changes.withPermits(1)); + }, + ); + + const updateLocked = (target: SkillInstallTarget, name: string) => + Effect.gen(function* () { + const { key, entry } = yield* lockedEntry(target, 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.", + }); + } + // 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")( + function* (input) { + const target = yield* resolveTarget(input.target); + yield* removeLocked(target, input.name).pipe(changes.withPermits(1)); + }, + ); + + const removeLocked = (target: SkillInstallTarget, name: string) => + Effect.gen(function* () { + 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({ + skills: [key], + global: target.kind === "environment", + cwd: paths.root, + }) + .pipe( + Effect.catchTags({ + SkillsCliError: (error) => Effect.fail(cliFailed(error.message)), + }), + ); + 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, skillFolderName(key))) + .pipe(Effect.orElseSucceed(() => false)); + 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}.`, + ); + } + }); + + /** + * 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); + }); + + /** + * 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/skills/SkillsCli.ts b/apps/server/src/skills/SkillsCli.ts new file mode 100644 index 0000000000000..5ffd05f006400 --- /dev/null +++ b/apps/server/src/skills/SkillsCli.ts @@ -0,0 +1,147 @@ +/** + * 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 * as HostProcess from "@t3tools/shared/HostProcess"; +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; + /** 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; +} + +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(); + // 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* HostProcess.Environment; + + const run = (command: "add" | "remove", args: ReadonlyArray, cwd: string) => + processRunner + .run({ + command: self.command, + args: [...selfInvocationArgs(self, ["skills-cli", command, ...args])], + cwd, + env: { + ...environment, + 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"] : []), + ...(input.fullDepth === true ? ["--full-depth"] : []), + "--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.test.ts b/apps/server/src/ws.test.ts index 75da37ad3b6c5..97723850530e2 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -67,6 +67,8 @@ import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolve import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as McpServerTools from "./mcpServers/McpServerTools.ts"; +import * as SkillLibrary from "./skills/SkillLibrary.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; @@ -338,6 +340,8 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ReviewService.ReviewService)({}), Layer.mock(ScheduledTasks.ScheduledTaskService)({}), Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(SkillLibrary.SkillLibrary)({}), + Layer.mock(McpServerTools.McpServerTools)({}), Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}), Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}), Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 0fb68f34e7174..ae8e2154a095d 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -204,6 +204,8 @@ import * as PortScanner from "./preview/PortScanner.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as KnownWorkspaces from "./workspace/KnownWorkspaces.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"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; @@ -1438,6 +1440,8 @@ export const layerWsRpc = ( const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; 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()); @@ -2824,6 +2828,14 @@ export 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.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( @@ -3318,6 +3330,7 @@ export const layer = Layer.unwrap( const mcpServerOAuth = yield* McpServerOAuth.McpServerOAuth; const secretRequests = yield* SecretRequests.SecretRequests; const sql = yield* SqlClient.SqlClient; + const serverSettingsService = yield* ServerSettings.ServerSettingsService; return HttpRouter.add( "GET", "/ws", @@ -3359,21 +3372,25 @@ export const layer = Layer.unwrap( Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)), Effect.provide( Layer.merge( - RpcAuthorization.layer(session.scopes, (method, payload) => { - // Anonymous product signal: the feature and its enum variant, - // credited to the connecting client's surface only. - const usage = featureUsage(method, payload); - return usage === undefined - ? Effect.void - : analytics - .record("feature.used", { - ...usage, - ...(clientAnalyticsProps.surface === undefined - ? {} - : { surface: clientAnalyticsProps.surface }), - }) - .pipe(Effect.ignore); - }), + RpcAuthorization.layer( + session.scopes, + serverSettingsService.getSettings.pipe(Effect.orElseSucceed(() => undefined)), + (method, payload) => { + // Anonymous product signal: the feature and its enum variant, + // credited to the connecting client's surface only. + const usage = featureUsage(method, payload); + return usage === undefined + ? Effect.void + : analytics + .record("feature.used", { + ...usage, + ...(clientAnalyticsProps.surface === undefined + ? {} + : { surface: clientAnalyticsProps.surface }), + }) + .pipe(Effect.ignore); + }, + ), rpcInstrumentationLayer, ), ), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d0fcd0434eac7..f3fb7e7a4ba63 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3589,6 +3589,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 b74e691ddd139..e4c8af5d1d80a 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -274,6 +274,7 @@ import { resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "@t3tools/client-runtime/providerSkills"; +import { mergeProjectDisabledSkills } from "@t3tools/shared/projectSettings"; import { useDelayedStatus } from "../../hooks/useDelayedStatus"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; @@ -457,6 +458,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; threadPullRequests: ReadonlyArray | undefined; @@ -593,6 +596,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) keybindings, terminalOpen, gitCwd, + skillsProjectId, pullRequestProjectId, pullRequestRepository, threadPullRequests, @@ -996,12 +1000,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const isSendDisabled = sendDisabledReason !== null; const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null; const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry); - const selectedProviderSkills = 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 = new Set( + mergeProjectDisabledSkills( + settings.disabledSkills, + skillsProjectId === null + ? undefined + : settings.projectSettingsOverrides[skillsProjectId]?.disabledSkills, + ).map((name) => name.toLowerCase()), + ); + const providerSkills = selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd) : NO_PROVIDER_SKILLS; - const selectedProviderSlashCommands = selectedProviderStatus + const selectedProviderSkills = + disabledSkillNames.size === 0 + ? providerSkills + : providerSkills.filter((skill) => !disabledSkillNames.has(skill.name.toLowerCase())); + // Claude also lists each skill as a slash command; a disabled one leaves both. + const providerSlashCommands = selectedProviderStatus ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd) : NO_PROVIDER_SLASH_COMMANDS; + const selectedProviderSlashCommands = + disabledSkillNames.size === 0 + ? providerSlashCommands + : providerSlashCommands.filter( + (command) => !disabledSkillNames.has(command.name.toLowerCase()), + ); const refreshWorkspaceSnapshotOnTyping = useProviderWorkspaceSnapshotRefresh({ environmentId, gitCwd, diff --git a/apps/web/src/components/settings/AddSkillsDialog.tsx b/apps/web/src/components/settings/AddSkillsDialog.tsx new file mode 100644 index 0000000000000..4614c4cb43395 --- /dev/null +++ b/apps/web/src/components/settings/AddSkillsDialog.tsx @@ -0,0 +1,314 @@ +import { + type EnvironmentId, + MAX_SKILLS_PER_INSTALL, + type SkillInstallTarget, + type SkillPreviewItem, +} from "@t3tools/contracts"; +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 { 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 { 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; + +/** + * 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, + 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 [filter, setFilter] = useState(""); + 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 }); + 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)), + ); + }; + + 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) => { + 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; + 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 ( + { + if (busy === null) onOpenChange(next); + }} + > + + + Add skills + + Installs for every agent on {scopeLabel}, the same way npx skills add does. + + + +
{ + event.preventDefault(); + void find(); + }} + > +
+ +
+ { + setSource(event.target.value); + setFound(null); + }} + spellCheck={false} + autoFocus + /> + +
+

+ A GitHub owner/repo, a git URL, or a folder on the environment. +

+
+ {found !== null ? ( +
+ Skills in {found.source} + {found.skills.length >= FILTER_FROM ? ( + + + + + setFilter(event.target.value)} + aria-label="Filter skills" + /> + + ) : null} +
+ +
    + {shown.length === 0 ? ( +
  • + No skills match “{filter.trim()}”. +
  • + ) : null} + {shown.map((skill) => ( +
  • + +
  • + ))} +
+
+ {found.skills.length > MAX_SKILLS_PER_INSTALL ? ( +

+ One install takes up to {MAX_SKILLS_PER_INSTALL} skills. Install the rest + afterwards. +

+ ) : null} +

+ + marks skills with scripts agents can be told to run. Install only sources you + trust. +

+
+ ) : null} + {error !== null ? ( +

{error}

+ ) : null} +
+
+ + + + +
+
+ ); +} 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 ? ( + + ) : null} + {onEdit !== null ? ( + + ) : null} + {onRemove !== null ? ( + + ) : 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} +

+ +
+
+ ) : 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 ( +
  • + + {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/McpServerDialog.tsx b/apps/web/src/components/settings/McpServerDialog.tsx new file mode 100644 index 0000000000000..be1740f1af6ab --- /dev/null +++ b/apps/web/src/components/settings/McpServerDialog.tsx @@ -0,0 +1,344 @@ +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, initial?.name ?? null); + 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. + + + +
    { + event.preventDefault(); + save(); + }} + > + {initial === null ? ( +
    + +