From fbc4574fb5abd559d505e27749276cb031f3e091 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 16:46:16 -0800 Subject: [PATCH] feat: install skills from a source, view their files, and let agents change Tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → Tools manages skills and MCP servers per environment and project: switch them on or off, install skills from a source with the bundled skills CLI, view a skill's files, see which environments have it, and list an MCP server's tools. Tool presets in the composer turn a set of skills and servers on or off for one thread and save on every connected environment. Agents can read and change Tools through new MCP tools. Squashed from the 37 commits of #17691 before rebasing onto main. Co-authored-by: n0mahd <39080654+n0mahd@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/i18n/translations/de.json | 10 +- apps/mobile/src/i18n/translations/en.json | 10 +- apps/mobile/src/i18n/translations/es.json | 10 +- apps/mobile/src/i18n/translations/fr.json | 10 +- apps/mobile/src/i18n/translations/ja.json | 10 +- apps/mobile/src/i18n/translations/ko.json | 10 +- apps/mobile/src/i18n/translations/pt-BR.json | 10 +- apps/mobile/src/i18n/translations/ru.json | 10 +- apps/mobile/src/i18n/translations/sv.json | 10 +- apps/mobile/src/i18n/translations/zh.json | 10 +- apps/server/package.json | 2 + apps/server/src/auth/RpcAuthorization.test.ts | 58 +- apps/server/src/auth/RpcAuthorization.ts | 48 +- apps/server/src/binCli.ts | 2 + apps/server/src/binMain.ts | 4 + apps/server/src/cli/skillsCli.ts | 29 + apps/server/src/device/DeviceService.test.ts | 1 + apps/server/src/mcp/McpHttpServer.ts | 33 + apps/server/src/mcp/resolveAgentTools.ts | 37 + .../src/mcp/toolkits/tools/handlers.test.ts | 156 ++ .../server/src/mcp/toolkits/tools/handlers.ts | 182 +++ apps/server/src/mcp/toolkits/tools/tools.ts | 102 ++ apps/server/src/mcpServerSecrets.ts | 229 +++ .../src/mcpServers/McpServerTools.test.ts | 203 +++ apps/server/src/mcpServers/McpServerTools.ts | 355 +++++ .../testFixtures/two-tool-mcp-server.mjs | 72 + .../src/observability/RpcInstrumentation.ts | 8 + .../Adapters/ClaudeAdapterV2.test.ts | 172 +++ .../Adapters/ClaudeAdapterV2.ts | 49 +- .../Adapters/CodexAdapterV2.test.ts | 84 + .../Adapters/CodexAdapterV2.ts | 37 +- .../Adapters/OpenCode2AdapterV2.test.ts | 3 + ...penCode2OrchestratorV2.integration.test.ts | 6 +- .../Orchestrator.control-reads.test.ts | 92 ++ .../src/orchestration-v2/Orchestrator.ts | 38 +- .../src/orchestration-v2/ProjectionStore.ts | 9 + .../ProviderSessionManager.ts | 32 +- .../orchestration-v2/ThreadLaunchService.ts | 3 + .../ThreadSettlementService.test.ts | 1 + .../testkit/OrchestratorScenario.ts | 1 + .../opencode2_fork/opencode_transcript.ndjson | 2 +- .../src/provider/AgentContextBudget.test.ts | 11 + .../src/provider/ProviderRegistry.test.ts | 9 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/relay/AgentAwarenessRelay.ts | 1 + apps/server/src/server.ts | 4 + apps/server/src/serverSettings.test.ts | 222 +++ apps/server/src/serverSettings.ts | 185 ++- apps/server/src/skills/SkillLibrary.test.ts | 547 +++++++ apps/server/src/skills/SkillLibrary.ts | 855 ++++++++++ apps/server/src/skills/SkillsCli.ts | 142 ++ apps/server/src/ws.test.ts | 4 + apps/server/src/ws.ts | 50 +- apps/web/src/components/ChatView.tsx | 2 + apps/web/src/components/chat/ChatComposer.tsx | 47 +- .../chat/CompactComposerControlsMenu.tsx | 11 +- .../components/chat/ComposerControlsBar.tsx | 60 +- .../components/chat/ComposerToolPresets.tsx | 278 ++++ .../src/components/chat/ToolPresetDialog.tsx | 346 +++++ .../chat/composerControlsOwnership.test.ts | 14 + .../chat/composerControlsOwnership.ts | 15 +- .../src/components/chat/useComposerSend.ts | 2 + .../components/chat/useMultipleModelSend.ts | 4 + .../useProviderWorkspaceSnapshotRefresh.ts | 2 +- .../components/settings/AddSkillsDialog.tsx | 349 +++++ .../components/settings/McpServerDetail.tsx | 351 +++++ .../components/settings/McpServerDialog.tsx | 391 +++++ .../settings/SettingsBreadcrumb.tsx | 27 +- .../settings/SettingsSidebarNav.tsx | 2 + .../src/components/settings/SkillAgents.tsx | 59 + .../src/components/settings/SkillDetail.tsx | 302 ++++ .../components/settings/SkillEnvironments.tsx | 182 +++ .../src/components/settings/SkillFiles.tsx | 203 +++ .../web/src/components/settings/SkillList.tsx | 264 ++++ .../src/components/settings/ToolsSettings.tsx | 1369 +++++++++++++++++ .../src/components/settings/TruncatedText.tsx | 31 + .../settings/scopedSettings.test.ts | 11 + .../src/components/settings/scopedSettings.ts | 20 + .../src/components/settings/settingsSearch.ts | 24 + .../settings/toolsSettings.logic.test.ts | 455 ++++++ .../settings/toolsSettings.logic.ts | 777 ++++++++++ .../components/settings/useEscapeToList.ts | 30 + .../components/settings/useScopedSettings.ts | 19 +- apps/web/src/composerDraftStore.ts | 16 + apps/web/src/hooks/useAfterDelay.ts | 19 + apps/web/src/hooks/useSettings.ts | 15 +- apps/web/src/i18n/translations/de.json | 396 ++++- apps/web/src/i18n/translations/en.json | 398 ++++- apps/web/src/i18n/translations/es.json | 397 ++++- apps/web/src/i18n/translations/fr.json | 397 ++++- apps/web/src/i18n/translations/ja.json | 381 ++++- apps/web/src/i18n/translations/ko.json | 381 ++++- apps/web/src/i18n/translations/pt-BR.json | 398 ++++- apps/web/src/i18n/translations/ru.json | 398 ++++- apps/web/src/i18n/translations/sv.json | 398 ++++- apps/web/src/i18n/translations/zh.json | 391 ++++- apps/web/src/routeTree.gen.ts | 21 + apps/web/src/routes/_chat.settings.tools.tsx | 48 + docs/README.md | 1 + docs/user/composer.md | 3 +- docs/user/project-settings.md | 5 +- docs/user/tools.md | 93 ++ .../client-runtime/src/operations/commands.ts | 16 + packages/client-runtime/src/providerSkills.ts | 2 +- packages/client-runtime/src/state/models.ts | 2 + .../src/state/orchestrationV2Projection.ts | 3 +- packages/client-runtime/src/state/server.ts | 43 + .../src/state/threadCommands.ts | 7 + packages/client-runtime/src/t3ToolSummary.ts | 68 + packages/contracts/src/agentTools.ts | 251 +++ .../contracts/src/clientRpcPermissions.ts | 8 + packages/contracts/src/index.ts | 2 + packages/contracts/src/orchestrationV2.ts | 16 + packages/contracts/src/rpc.ts | 78 + packages/contracts/src/settings.ts | 55 +- packages/contracts/src/skills.ts | 218 +++ .../src/server/AcpSessionRuntime.ts | 18 +- packages/provider-acp/src/server/adapter.ts | 55 +- packages/provider-core/package.json | 4 + .../src/server/AgentSkillFolders.ts | 115 ++ .../provider-core/src/server/mcpSession.ts | 32 +- .../provider-cursor/src/server/adapter.ts | 19 + .../provider-opencode/src/server/adapter.ts | 64 +- .../src/server/v2/adapter.ts | 155 +- packages/shared/package.json | 4 + packages/shared/src/agentTools.test.ts | 209 +++ packages/shared/src/agentTools.ts | 216 +++ packages/shared/src/projectSettings.ts | 61 + packages/shared/src/serverSettings.ts | 11 + packages/shared/src/t3McpToolPresentation.ts | 11 + pnpm-lock.yaml | 19 + pnpm-workspace.yaml | 1 + 132 files changed, 15573 insertions(+), 175 deletions(-) create mode 100644 apps/server/src/cli/skillsCli.ts create mode 100644 apps/server/src/mcp/resolveAgentTools.ts create mode 100644 apps/server/src/mcp/toolkits/tools/handlers.test.ts create mode 100644 apps/server/src/mcp/toolkits/tools/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/tools/tools.ts create mode 100644 apps/server/src/mcpServerSecrets.ts create mode 100644 apps/server/src/mcpServers/McpServerTools.test.ts create mode 100644 apps/server/src/mcpServers/McpServerTools.ts create mode 100644 apps/server/src/mcpServers/testFixtures/two-tool-mcp-server.mjs create mode 100644 apps/server/src/skills/SkillLibrary.test.ts create mode 100644 apps/server/src/skills/SkillLibrary.ts create mode 100644 apps/server/src/skills/SkillsCli.ts create mode 100644 apps/web/src/components/chat/ComposerToolPresets.tsx create mode 100644 apps/web/src/components/chat/ToolPresetDialog.tsx create mode 100644 apps/web/src/components/settings/AddSkillsDialog.tsx create mode 100644 apps/web/src/components/settings/McpServerDetail.tsx create mode 100644 apps/web/src/components/settings/McpServerDialog.tsx create mode 100644 apps/web/src/components/settings/SkillAgents.tsx create mode 100644 apps/web/src/components/settings/SkillDetail.tsx create mode 100644 apps/web/src/components/settings/SkillEnvironments.tsx create mode 100644 apps/web/src/components/settings/SkillFiles.tsx create mode 100644 apps/web/src/components/settings/SkillList.tsx create mode 100644 apps/web/src/components/settings/ToolsSettings.tsx create mode 100644 apps/web/src/components/settings/TruncatedText.tsx create mode 100644 apps/web/src/components/settings/toolsSettings.logic.test.ts create mode 100644 apps/web/src/components/settings/toolsSettings.logic.ts create mode 100644 apps/web/src/components/settings/useEscapeToList.ts create mode 100644 apps/web/src/hooks/useAfterDelay.ts create mode 100644 apps/web/src/routes/_chat.settings.tools.tsx create mode 100644 docs/user/tools.md create mode 100644 packages/contracts/src/agentTools.ts create mode 100644 packages/contracts/src/skills.ts create mode 100644 packages/provider-core/src/server/AgentSkillFolders.ts create mode 100644 packages/shared/src/agentTools.test.ts create mode 100644 packages/shared/src/agentTools.ts diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 37470078895b1..20a0b0ab0aeb2 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5390,5 +5390,13 @@ "ad208e3e32c85029": "Alle ausblenden", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool-Aufrufe im Chat", - "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt." + "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Skills und MCP-Server {count}-mal geprüft} other {Skills und MCP-Server {count}-mal geprüft}}", + "651333a8798481cf": "{count, plural, one {{count}-mal versucht, Skills und MCP-Server zu prüfen} other {{count}-mal versucht, Skills und MCP-Server zu prüfen}}", + "7aae4f6df36c4e7b": "{count, plural, one {Skills und MCP-Server {count}-mal aktualisiert} other {Skills und MCP-Server {count}-mal aktualisiert}}", + "15eae995296a4525": "{count, plural, one {{count}-mal versucht, Skills und MCP-Server zu aktualisieren} other {{count}-mal versucht, Skills und MCP-Server zu aktualisieren}}", + "5ba9aa4175d4965c": "{count, plural, one {Skills {count}-mal installiert} other {Skills {count}-mal installiert}}", + "f5fb66293e616534": "{count, plural, one {{count}-mal versucht, Skills zu installieren} other {{count}-mal versucht, Skills zu installieren}}", + "c06fc69851054582": "{count, plural, one {Skills {count}-mal entfernt} other {Skills {count}-mal entfernt}}", + "0af78fcce5177598": "{count, plural, one {{count}-mal versucht, Skills zu entfernen} other {{count}-mal versucht, Skills zu entfernen}}" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index f89c5bddb7eb2..c76c360e2d350 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5391,5 +5391,13 @@ "ad208e3e32c85029": "Hide all", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool calls in chat", - "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show." + "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Checked skills and MCP servers {count} time} other {Checked skills and MCP servers {count} times}}", + "651333a8798481cf": "{count, plural, one {Tried to check skills and MCP servers {count} time} other {Tried to check skills and MCP servers {count} times}}", + "7aae4f6df36c4e7b": "{count, plural, one {Updated skills and MCP servers {count} time} other {Updated skills and MCP servers {count} times}}", + "15eae995296a4525": "{count, plural, one {Tried to update skills and MCP servers {count} time} other {Tried to update skills and MCP servers {count} times}}", + "5ba9aa4175d4965c": "{count, plural, one {Installed skills {count} time} other {Installed skills {count} times}}", + "f5fb66293e616534": "{count, plural, one {Tried to install skills {count} time} other {Tried to install skills {count} times}}", + "c06fc69851054582": "{count, plural, one {Removed skills {count} time} other {Removed skills {count} times}}", + "0af78fcce5177598": "{count, plural, one {Tried to remove skills {count} time} other {Tried to remove skills {count} times}}" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index a0df74614dfda..2c0758131666c 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5384,5 +5384,13 @@ "ad208e3e32c85029": "Ocultar todo", "3328503592789bed": "Zen", "856812e7e1fc445e": "Llamadas a herramientas en el chat", - "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran." + "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Comprobó skills y servidores MCP {count} vez} other {Comprobó skills y servidores MCP {count} veces}}", + "651333a8798481cf": "{count, plural, one {Intentó comprobar skills y servidores MCP {count} vez} other {Intentó comprobar skills y servidores MCP {count} veces}}", + "7aae4f6df36c4e7b": "{count, plural, one {Actualizó skills y servidores MCP {count} vez} other {Actualizó skills y servidores MCP {count} veces}}", + "15eae995296a4525": "{count, plural, one {Intentó actualizar skills y servidores MCP {count} vez} other {Intentó actualizar skills y servidores MCP {count} veces}}", + "5ba9aa4175d4965c": "{count, plural, one {Instaló skills {count} vez} other {Instaló skills {count} veces}}", + "f5fb66293e616534": "{count, plural, one {Intentó instalar skills {count} vez} other {Intentó instalar skills {count} veces}}", + "c06fc69851054582": "{count, plural, one {Quitó skills {count} vez} other {Quitó skills {count} veces}}", + "0af78fcce5177598": "{count, plural, one {Intentó quitar skills {count} vez} other {Intentó quitar skills {count} veces}}" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 9e9d733338aff..ba767d1d9cbe4 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5384,5 +5384,13 @@ "ad208e3e32c85029": "Tout masquer", "3328503592789bed": "Zen", "856812e7e1fc445e": "Appels d’outils dans la discussion", - "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours." + "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Skills et serveurs MCP vérifiés {count} fois} other {Skills et serveurs MCP vérifiés {count} fois}}", + "651333a8798481cf": "{count, plural, one {Tentative de vérifier les skills et serveurs MCP {count} fois} other {Tentative de vérifier les skills et serveurs MCP {count} fois}}", + "7aae4f6df36c4e7b": "{count, plural, one {Skills et serveurs MCP mis à jour {count} fois} other {Skills et serveurs MCP mis à jour {count} fois}}", + "15eae995296a4525": "{count, plural, one {Tentative de mettre à jour les skills et serveurs MCP {count} fois} other {Tentative de mettre à jour les skills et serveurs MCP {count} fois}}", + "5ba9aa4175d4965c": "{count, plural, one {Skills installés {count} fois} other {Skills installés {count} fois}}", + "f5fb66293e616534": "{count, plural, one {Tentative d’installer des skills {count} fois} other {Tentative d’installer des skills {count} fois}}", + "c06fc69851054582": "{count, plural, one {Skills supprimés {count} fois} other {Skills supprimés {count} fois}}", + "0af78fcce5177598": "{count, plural, one {Tentative de supprimer des skills {count} fois} other {Tentative de supprimer des skills {count} fois}}" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f8c3f391742a3..66ca7998b62d2 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5366,5 +5366,13 @@ "ad208e3e32c85029": "すべて非表示", "3328503592789bed": "Zen", "856812e7e1fc445e": "チャット内のツール呼び出し", - "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。" + "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", + "6c4b55cdbe5dd1d0": "{count, plural, other {スキルと MCP サーバーを {count} 回確認しました}}", + "651333a8798481cf": "{count, plural, other {スキルと MCP サーバーを {count} 回確認しようとしました}}", + "7aae4f6df36c4e7b": "{count, plural, other {スキルと MCP サーバーを {count} 回更新しました}}", + "15eae995296a4525": "{count, plural, other {スキルと MCP サーバーを {count} 回更新しようとしました}}", + "5ba9aa4175d4965c": "{count, plural, other {スキルを {count} 回インストールしました}}", + "f5fb66293e616534": "{count, plural, other {スキルを {count} 回インストールしようとしました}}", + "c06fc69851054582": "{count, plural, other {スキルを {count} 回削除しました}}", + "0af78fcce5177598": "{count, plural, other {スキルを {count} 回削除しようとしました}}" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 368b459f45b56..7471f80429290 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5370,5 +5370,13 @@ "ad208e3e32c85029": "모두 숨기기", "3328503592789bed": "Zen", "856812e7e1fc445e": "채팅의 도구 호출", - "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다." + "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", + "6c4b55cdbe5dd1d0": "{count, plural, other {스킬 및 MCP 서버 {count}회 확인함}}", + "651333a8798481cf": "{count, plural, other {스킬 및 MCP 서버 확인 {count}회 시도함}}", + "7aae4f6df36c4e7b": "{count, plural, other {스킬 및 MCP 서버 {count}회 업데이트함}}", + "15eae995296a4525": "{count, plural, other {스킬 및 MCP 서버 업데이트 {count}회 시도함}}", + "5ba9aa4175d4965c": "{count, plural, other {스킬 {count}회 설치함}}", + "f5fb66293e616534": "{count, plural, other {스킬 설치 {count}회 시도함}}", + "c06fc69851054582": "{count, plural, other {스킬 {count}회 제거함}}", + "0af78fcce5177598": "{count, plural, other {스킬 제거 {count}회 시도함}}" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 7529fe5138851..2011ebbbeca53 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5384,5 +5384,13 @@ "ad208e3e32c85029": "Ocultar todas", "3328503592789bed": "Zen", "856812e7e1fc445e": "Chamadas de ferramentas no chat", - "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem." + "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Verificou skills e servidores MCP {count} vez} other {Verificou skills e servidores MCP {count} vezes}}", + "651333a8798481cf": "{count, plural, one {Tentou verificar skills e servidores MCP {count} vez} other {Tentou verificar skills e servidores MCP {count} vezes}}", + "7aae4f6df36c4e7b": "{count, plural, one {Atualizou skills e servidores MCP {count} vez} other {Atualizou skills e servidores MCP {count} vezes}}", + "15eae995296a4525": "{count, plural, one {Tentou atualizar skills e servidores MCP {count} vez} other {Tentou atualizar skills e servidores MCP {count} vezes}}", + "5ba9aa4175d4965c": "{count, plural, one {Instalou skills {count} vez} other {Instalou skills {count} vezes}}", + "f5fb66293e616534": "{count, plural, one {Tentou instalar skills {count} vez} other {Tentou instalar skills {count} vezes}}", + "c06fc69851054582": "{count, plural, one {Removeu skills {count} vez} other {Removeu skills {count} vezes}}", + "0af78fcce5177598": "{count, plural, one {Tentou remover skills {count} vez} other {Tentou remover skills {count} vezes}}" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 976f53ecf6dec..57f373d82e13e 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5464,5 +5464,13 @@ "ad208e3e32c85029": "Скрывать все", "3328503592789bed": "Дзен", "856812e7e1fc445e": "Вызовы инструментов в чате", - "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда." + "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Навыки и MCP-серверы проверены {count} раз} few {Навыки и MCP-серверы проверены {count} раза} many {Навыки и MCP-серверы проверены {count} раз} other {Навыки и MCP-серверы проверены {count} раза}}", + "651333a8798481cf": "{count, plural, one {Попытка проверить навыки и MCP-серверы: {count} раз} few {Попытка проверить навыки и MCP-серверы: {count} раза} many {Попытка проверить навыки и MCP-серверы: {count} раз} other {Попытка проверить навыки и MCP-серверы: {count} раза}}", + "7aae4f6df36c4e7b": "{count, plural, one {Навыки и MCP-серверы обновлены {count} раз} few {Навыки и MCP-серверы обновлены {count} раза} many {Навыки и MCP-серверы обновлены {count} раз} other {Навыки и MCP-серверы обновлены {count} раза}}", + "15eae995296a4525": "{count, plural, one {Попытка обновить навыки и MCP-серверы: {count} раз} few {Попытка обновить навыки и MCP-серверы: {count} раза} many {Попытка обновить навыки и MCP-серверы: {count} раз} other {Попытка обновить навыки и MCP-серверы: {count} раза}}", + "5ba9aa4175d4965c": "{count, plural, one {Навыки установлены {count} раз} few {Навыки установлены {count} раза} many {Навыки установлены {count} раз} other {Навыки установлены {count} раза}}", + "f5fb66293e616534": "{count, plural, one {Попытка установить навыки: {count} раз} few {Попытка установить навыки: {count} раза} many {Попытка установить навыки: {count} раз} other {Попытка установить навыки: {count} раза}}", + "c06fc69851054582": "{count, plural, one {Навыки удалены {count} раз} few {Навыки удалены {count} раза} many {Навыки удалены {count} раз} other {Навыки удалены {count} раза}}", + "0af78fcce5177598": "{count, plural, one {Попытка удалить навыки: {count} раз} few {Попытка удалить навыки: {count} раза} many {Попытка удалить навыки: {count} раз} other {Попытка удалить навыки: {count} раза}}" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 45a259d11d34b..6e1444b37088f 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5390,5 +5390,13 @@ "ad208e3e32c85029": "Dölj alla", "3328503592789bed": "Zen", "856812e7e1fc445e": "Verktygsanrop i chatten", - "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid." + "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", + "6c4b55cdbe5dd1d0": "{count, plural, one {Kontrollerade färdigheter och MCP-servrar {count} gång} other {Kontrollerade färdigheter och MCP-servrar {count} gånger}}", + "651333a8798481cf": "{count, plural, one {Försökte kontrollera färdigheter och MCP-servrar {count} gång} other {Försökte kontrollera färdigheter och MCP-servrar {count} gånger}}", + "7aae4f6df36c4e7b": "{count, plural, one {Uppdaterade färdigheter och MCP-servrar {count} gång} other {Uppdaterade färdigheter och MCP-servrar {count} gånger}}", + "15eae995296a4525": "{count, plural, one {Försökte uppdatera färdigheter och MCP-servrar {count} gång} other {Försökte uppdatera färdigheter och MCP-servrar {count} gånger}}", + "5ba9aa4175d4965c": "{count, plural, one {Installerade färdigheter {count} gång} other {Installerade färdigheter {count} gånger}}", + "f5fb66293e616534": "{count, plural, one {Försökte installera färdigheter {count} gång} other {Försökte installera färdigheter {count} gånger}}", + "c06fc69851054582": "{count, plural, one {Tog bort färdigheter {count} gång} other {Tog bort färdigheter {count} gånger}}", + "0af78fcce5177598": "{count, plural, one {Försökte ta bort färdigheter {count} gång} other {Försökte ta bort färdigheter {count} gånger}}" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 860ff98a0f10c..7a03e0299662d 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5375,5 +5375,13 @@ "ad208e3e32c85029": "全部隐藏", "3328503592789bed": "专注模式", "856812e7e1fc445e": "聊天中的工具调用", - "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。" + "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", + "6c4b55cdbe5dd1d0": "{count, plural, other {已检查技能和 MCP 服务器 {count} 次}}", + "651333a8798481cf": "{count, plural, other {尝试检查技能和 MCP 服务器 {count} 次}}", + "7aae4f6df36c4e7b": "{count, plural, other {已更新技能和 MCP 服务器 {count} 次}}", + "15eae995296a4525": "{count, plural, other {尝试更新技能和 MCP 服务器 {count} 次}}", + "5ba9aa4175d4965c": "{count, plural, other {已安装技能 {count} 次}}", + "f5fb66293e616534": "{count, plural, other {尝试安装技能 {count} 次}}", + "c06fc69851054582": "{count, plural, other {已移除技能 {count} 次}}", + "0af78fcce5177598": "{count, plural, other {尝试移除技能 {count} 次}}" } diff --git a/apps/server/package.json b/apps/server/package.json index 8ece0aaa8118f..172cbf38ea81f 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -41,6 +41,7 @@ "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", "@ff-labs/fff-node": "0.11.0", + "@modelcontextprotocol/sdk": "catalog:", "@muse-code/sdk": "1.4.6", "@napi-rs/keyring": "^1.3.0", "@t3tools/issue-tracker-linear": "workspace:*", @@ -71,6 +72,7 @@ "playwright-core": "1.64.1", "proper-lockfile": "4.1.2", "saxes": "6.0.0", + "skills": "1.7.1", "stream-chain": "^4.2.5", "stream-json": "3.7.0", "transcribe-cpp": "0.4.1", diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 200a049e0118b..2194fba08b7fc 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -8,8 +8,8 @@ import { DEFAULT_SERVER_SETTINGS, EnvironmentId, ProviderDriverKind, - ProviderInstanceId, ProjectId, + ProviderInstanceId, IssueTrackerKind, SecretProviderId, ThreadId, @@ -524,6 +524,62 @@ describe("settings mutation authorization", () => { }), ); + 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], + undefined, + 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 send a named secret to a gateway it picks", () => Effect.gen(function* () { const group = WsRpcGroup.omit( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 7eea0a7e364a0..8ca637a0cb243 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -7,6 +7,7 @@ import { AssetCreateUrlInput, AuthAccessReadScope, ServerSettingsPatch, + type ServerSettings, ProviderInstanceMutation, requiredScopesForServerSettingsPatch, requiredScopesForProjectMutation, @@ -171,6 +172,16 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.sourceControlAppAccess]: AuthOrchestrationReadScope, [WS_METHODS.sourceControlStarred]: 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, @@ -264,9 +275,12 @@ const SettingsUpdate = Schema.Struct({ // Middleware receives the payload already decoded, so it is checked against the decoded shape. const decodeSettingsUpdate = Schema.decodeUnknownSync(Schema.toType(SettingsUpdate)); -const requiredScopesForSettingsUpdate = (payload: unknown) => { +const requiredScopesForSettingsUpdate = ( + payload: unknown, + current: Pick | undefined, +) => { const input = decodeSettingsUpdate(payload); - const scopes = requiredScopesForServerSettingsPatch(input.patch); + const scopes = requiredScopesForServerSettingsPatch(input.patch, current); if (input.providerInstanceMutation === undefined) return scopes; return Object.values(input.patch).every((value) => value === undefined) ? [AuthProvidersManageScope] @@ -305,6 +319,7 @@ const sendsProviderSignOutPrompt = (method: string, payload: unknown): boolean = const requiredScopesForRpcCall = ( method: string, payload: unknown, + currentSettings?: Pick, ): ReadonlyArray => { if (method === WS_METHODS.serverRetryResourceTelemetry) { return [AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope]; @@ -320,7 +335,9 @@ const requiredScopesForRpcCall = ( : AuthOrchestrationReadScope, ]; } - if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload); + if (method === WS_METHODS.serverUpdateSettings) { + return requiredScopesForSettingsUpdate(payload, currentSettings); + } // These send the credential they are given to a URL the caller names, as a saved setting would. if ( (method === WS_METHODS.deviceSimlockIdentity || @@ -341,21 +358,28 @@ const requiredScopesForRpcCall = ( }; /** - * `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. + * `onAuthorized` runs once after an authorized request succeeds (a stream RPC: when it + * completes), the one place to observe every request. `currentSettings` lets a settings + * update that only resends a project's stored MCP servers pass with `settings:write`. */ export const layer = ( scopes: ReadonlyArray, onAuthorized?: (method: string, payload: unknown) => Effect.Effect, + currentSettings?: Effect.Effect | undefined>, ) => 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)); + const authorize = (settings: Pick | undefined) => { + const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload, settings); + 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)); + }; + // Only a settings update reads the stored settings, to tell a resent server from a new one. + return rpc._tag === WS_METHODS.serverUpdateSettings && currentSettings !== undefined + ? Effect.flatMap(currentSettings, authorize) + : authorize(undefined); }); /** Retrying can install or restart tools even though ordinary listing is readable. */ diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 995b207e7c781..d4876e197e12d 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -11,6 +11,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 { environmentCommand } from "./cli/environment.ts"; import { appCommand } from "./cli/app.ts"; @@ -82,6 +83,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => ), acpMcpBridgeCommand, acpMcpCallCommand, + skillsCliCommand, startCommand, serveCommand, appCommand, diff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts index 7d4c93fb040e7..84b5970f0f407 100644 --- a/apps/server/src/binMain.ts +++ b/apps/server/src/binMain.ts @@ -25,6 +25,10 @@ export async function runCliCommand() { } 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 if (command === "__speech-worker") { const mode = process.argv[3]; if (mode !== "discover" && mode !== "model") throw new Error("Unknown speech worker mode."); diff --git a/apps/server/src/cli/skillsCli.ts b/apps/server/src/cli/skillsCli.ts new file mode 100644 index 0000000000000..1f23ec1445af2 --- /dev/null +++ b/apps/server/src/cli/skillsCli.ts @@ -0,0 +1,29 @@ +import * as Effect from "effect/Effect"; +import { Argument, Command } from "effect/cli"; + +/** + * `t3 skills-cli ` runs the bundled `skills` CLI (vercel-labs/skills, what + * `npx skills` runs), so installs need no Node or npm of their own. The server spawns + * it as a child, which keeps its `process.exit` and prompts out of the server. + */ +export async function runSkillsCli(args: ReadonlyArray): Promise { + // The CLI calls `process.exit` right after printing its `--json` result, and POSIX + // pipe writes are async, so a large result was cut at 64 KiB. A blocking pipe + // finishes each write first. Do not defer exit instead: the CLI relies on it. + 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 00e942f1e6df5..d560e4105e212 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -386,6 +386,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 d7bea75493b73..a596bfc8fdc7b 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -57,9 +57,11 @@ 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 { ThemeToolkit } from "./toolkits/theme/tools.ts"; import * as ThemeHandlers from "./toolkits/theme/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"; @@ -1355,6 +1357,10 @@ const layerThemeToolkit = toolkitRegistration(ThemeToolkit, ThemeHandlers.layer) export const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer); +const layerToolsRegistration = toolkitRegistration(ToolsToolkit, ToolsHandlers.layer).pipe( + Layer.provide(ThreadCommandExecutor.layer), +); + export const layerAttachmentToolkit = toolkitRegistration( AttachmentToolkit, AttachmentHandlers.layer, @@ -1411,6 +1417,32 @@ export const layerMcpTransport = (registrations: Layer.Layer = [ + PreviewStandardToolkit, + PreviewSnapshotToolkit, + OrchestratorToolkit, + ThreadToolkit, + AttachmentToolkit, + ProjectToolkit, + EnvironmentToolkit, + ThemeToolkit, + ToolsToolkit, + PreviewControlsToolkit, + WorktreeToolkit, + PullRequestsToolkit, + IssuesToolkit, + DeviceStandardToolkit, + DeviceScreenshotToolkit, + HtmlRenderToolkit, + HtmlPreviewToolkit, + MessageToolkit, +]; + /** Every tool the T3 MCP server advertises. AgentContextBudget.test.ts measures this set. */ export const layerTools = Layer.mergeAll( layerPreviewToolkit, @@ -1420,6 +1452,7 @@ export const layerTools = Layer.mergeAll( layerProjectRegistration, layerEnvironmentToolkit, layerThemeToolkit, + 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..b95f8814de9fc --- /dev/null +++ b/apps/server/src/mcp/resolveAgentTools.ts @@ -0,0 +1,37 @@ +import type { + ProjectId, + ResolvedMcpServer, + ServerSettings, + ThreadToolPresets, +} from "@t3tools/contracts"; +import { applyThreadToolPresets } from "@t3tools/shared/agentTools"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; + +import type { McpProviderSessionTools } from "@t3tools/provider-core/server/mcpSession"; + +/** + * A thread's tools from secret-materialized settings: project overrides, then + * the thread's presets, disabled servers dropped. The fingerprint covers the + * full config (a rotated secret counts) and is only compared, never sent. + */ +export function resolveAgentTools( + settings: ServerSettings, + projectId: ProjectId | null, + threadPresets?: ThreadToolPresets, +): McpProviderSessionTools { + const effective = applyThreadToolPresets( + resolveProjectSettings(settings, projectId).settings, + settings.toolPresets, + threadPresets, + ); + 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..dd33826c8fa58 --- /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 = Effect.fn("ToolsHandlers.projectTarget")(function* ( + projectId: ProjectId | undefined, +) { + 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 = Effect.fn("ToolsHandlers.asCaller")(function* ( + check: Effect.Effect, + change: Effect.Effect, +) { + 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..0a8c8a608fd97 --- /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.", + parameters: Schema.Struct(Scope), + success: ToolsState, +}) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false); + +const ToolsUpdateTool = Tool.make("t3_tools_update", { + ...shared, + description: + "Turn skills or Settings → Tools MCP servers on or off for this environment or one project. Skills are named as agents invoke them. Requires a live full-access/default calling thread. Applies to new agent sessions.", + parameters: Schema.Struct({ + ...Scope, + skills: Schema.optional( + Schema.Array(Schema.Struct({ name: TrimmedNonEmptyString, enabled: Schema.Boolean })), + ), + mcpServers: Schema.optional( + Schema.Array(Schema.Struct({ name: McpServerName, enabled: Schema.Boolean })), + ), + }), + success: ToolsState, +}).annotate(Tool.Destructive, true); + +const SkillsInstallTool = Tool.make("t3_skills_install", { + ...shared, + description: + "Install skills from a source (GitHub owner/repo, git URL, or a folder on this environment) for every agent, the way `npx skills add` does. With projectId they go into that project's .agents/skills; without, into the environment's ~/.agents/skills. Skills may include scripts agents can run: install only sources the user asked for. Requires a live full-access/default calling thread.", + parameters: Schema.Struct({ + ...Scope, + source: SkillSource, + skills: 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/mcpServerSecrets.ts b/apps/server/src/mcpServerSecrets.ts new file mode 100644 index 0000000000000..8731227e2c21b --- /dev/null +++ b/apps/server/src/mcpServerSecrets.ts @@ -0,0 +1,229 @@ +/** + * Sensitive MCP server variables live in the secret store, never in settings.json or on + * the wire, as `{value: "", valueRedacted: true}`; sending that back keeps the secret. + * Servers sit in the environment's `mcpServers` and each project's entry; helpers walk both. + */ +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 }; + +/** + * The secret-store changes from `current` to `next`, and the redacted settings to persist. + * A redacted variable keeps its secret (moved when `storedAs` names a rename, or taken from + * a hand-edited inline value); a typed value replaces it; empty or non-sensitive 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..fe252725cb282 --- /dev/null +++ b/apps/server/src/mcpServers/McpServerTools.ts @@ -0,0 +1,355 @@ +/** + * 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 = Effect.fn("McpServerTools.listPages")(function* ( + client: InstanceType, + ) { + 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 de140587e4569..24833da2d261c 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -40,6 +40,14 @@ const RPC_AGGREGATES = { [WS_METHODS.serverGetConfig]: "server", [WS_METHODS.serverGetNpmRelease]: "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 c09aca71dfc2f..91c2d6e0e9904 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -747,6 +747,63 @@ 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, + }); + 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: "token" }, + }, + ...T3_MCP_SERVERS, + }, + sdkSettings: { skillOverrides: { "grill-me": "off" } }, + }); + + 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), @@ -1627,6 +1684,121 @@ describe("ClaudeAdapterV2 provider installation gate", () => { ); }); +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, + random: yield* SecureRandom.SecureRandom, + 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, + renameSession: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + mcpAuthenticate: () => Effect.die("unexpected MCP sign-in"), + mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in"), + reconnectMcpServer: () => Effect.die("unexpected MCP reconnect"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => 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, + NodeCrypto.layer, + ), + ), + ), + ), + ); +}); + describe("ClaudeAdapterV2 approval cancellation", () => { it.effect("observes an approval signal that was already aborted", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 3b3e2b273977f..15f7e6968dcbf 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -102,6 +102,7 @@ import { isCompactionCommandMessage, parseGoalCommand, type MessageId, + mcpServerVariableRecord, type ModelSelection, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, @@ -133,6 +134,7 @@ import { type ProviderUserInputAnswers, type ProviderThreadId, type RunId, + type ResolvedMcpServer, type ThreadId, resolveIdleCompaction, isDelegatedAppThread, @@ -2457,7 +2459,7 @@ export function makeClaudeQueryOptions(input: { preset: "claude_code" as const, append: [ buildRuntimeInstructions({ harness: "Claude Code" }) + - (input.mcpServers === undefined + (input.mcpServers?.["t3-code"] === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS + CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS + @@ -2611,17 +2613,22 @@ export function claudeMcpQueryOverrides(input: { }): { readonly allowedTools?: ReadonlyArray; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + readonly sdkSettings?: ClaudeSdkSettings; } { 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 mcpAllowedTools = input.readOnlySandbox ? CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS : [CLAUDE_T3_MCP_TOOL_WILDCARD]; + // The user's servers are not pre-approved: full access already skips the + // prompt, so an allow rule would only bypass the modes that ask to approve. return { allowedTools: Array.from(new Set([...(input.allowedTools ?? []), ...mcpAllowedTools])), mcpServers: { + ...claudeUserMcpServers(tools.servers), "t3-code": { type: "http", url: session.endpoint, @@ -2631,9 +2638,43 @@ export function claudeMcpQueryOverrides(input: { timeout: CLAUDE_T3_MCP_TOOL_TIMEOUT_MS, }, }, + ...(tools.disabledSkills.length === 0 + ? {} + : { + // The flag-settings layer outranks the user's and project's + // settings files, so an "off" here hides the skill from both the + // model and the slash menu whatever those files say. + sdkSettings: { + skillOverrides: Object.fromEntries( + tools.disabledSkills.map((name) => [name, "off" as const]), + ), + }, + }), }; } +function claudeUserMcpServers( + servers: ReadonlyArray, +): NonNullable { + return Object.fromEntries( + servers.map((server) => [ + server.name, + server.transport.type === "stdio" + ? { + type: "stdio" as const, + command: server.transport.command, + args: [...server.transport.args], + env: mcpServerVariableRecord(server.transport.env), + } + : { + type: "http" as const, + url: server.transport.url, + headers: mcpServerVariableRecord(server.transport.headers), + }, + ]), + ); +} + function providerSession(input: { readonly providerSessionId: OrchestrationV2ProviderSession["id"]; readonly providerInstanceId: ProviderInstanceId; @@ -3686,6 +3727,7 @@ export function claudeEffectiveQueryPolicyKey( mcpOverrides: { readonly allowedTools?: ReadonlyArray; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + readonly sdkSettings?: ClaudeSdkSettings; }, ): string { return JSON.stringify({ @@ -3696,6 +3738,8 @@ export function claudeEffectiveQueryPolicyKey( : { allowedTools: mcpOverrides.allowedTools }), }), mcpServers: mcpOverrides.mcpServers, + // Skill switches load at process start, so a change reopens the query. + sdkSettings: mcpOverrides.sdkSettings, }); } @@ -13240,6 +13284,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? {} : { mcpServers: mcpOverrides.mcpServers }), deviceToolsAvailable: mcpSession?.capabilities?.has("device") === true, + ...(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 3dd9c17c1eca7..046a941906e1f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2581,6 +2581,90 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("adds Settings → Tools servers and skill switches as their own config keys", () => + Effect.gen(function* () { + const scenario = "user-mcp-servers"; + yield* (yield* McpProviderSessions.McpProviderSessions).set({ + environmentId: EnvironmentId.make("environment-codex-user-tools"), + threadId: ThreadId.make(`thread-${scenario}`), + providerSessionId: `provider-session-${scenario}`, + 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 requests: Array<{ readonly config: Record }> = []; + yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario, + // The thread's skill switches are owned config, which replay checks. + entries: codexReplayPreamble({ + nativeThreadId: "user-mcp-thread", + nativeTurnId: "unused", + prompt: "unused", + }) + .slice(0, 5) + .map((entry) => + entry.type === "expect_outbound" && entry.label === "thread/start" + ? { + ...entry, + frame: { + id: 2, + method: "thread/start", + params: { + config: { + ...CodexAdapterV2.CODEX_THREAD_CONFIG, + skills: { config: [{ name: "grill-me", enabled: false }] }, + }, + }, + }, + } + : entry, + ), + }), + () => Effect.void, + (method, params) => + Effect.sync(() => { + if (method === "thread/start") { + requests.push(params as { readonly config: Record }); + } + }), + ); + const config = requests[0]?.config ?? {}; + // One key per server, so launch-argument servers survive like with t3-code. + assert.deepEqual(config["mcp_servers.linear"], { + url: "https://mcp.linear.app/mcp", + http_headers: { Authorization: "Bearer lin" }, + }); + assert.isUndefined(config.mcp_servers); + assert.deepEqual(config.skills, { config: [{ name: "grill-me", enabled: false }] }); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #15839 launch-arg MCP servers survive the thread's t3-code server it.effect("replays historical and dotted MCP config while enforcing other thread config", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 5b594563efa58..107b344d17571 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -36,6 +36,7 @@ import { defaultInstanceIdForDriver, isOrchestrationV2WorkActive, type OrchestrationV2GoalCommand, + mcpServerVariableRecord, OrchestrationV2ProviderGoal, parseGoalCommand, ProviderDriverKind, @@ -83,6 +84,7 @@ import type { ProviderThreadId, ProviderTurnId, ProviderInstanceId, + ResolvedMcpServer, RuntimeMode, } from "@t3tools/contracts"; import * as CodexClient from "effect-codex-app-server/client"; @@ -1574,6 +1576,7 @@ function codexThreadRuntimeParams(input: { tool_timeout_sec: CODEX_T3_MCP_TOOL_TIMEOUT_SEC, http_headers: { Authorization: mcpSession.authorizationHeader }, }; + 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 }), @@ -1595,7 +1598,9 @@ function codexThreadRuntimeParams(input: { ...(t3Server === undefined ? {} : { - // Override only T3's servers so launch-argument MCP servers survive. + // Override only T3's servers so launch-argument MCP servers survive; + // Settings → Tools servers go in the same way, one key each. + ...codexUserMcpServers(tools.servers), "mcp_servers.t3-code": { ...t3Server, disabled_tools: CODEX_DIRECT_ONLY_T3_TOOLS }, // Code Mode runs a blocking wait or delegate wait as a nested call, and the model // keeps polling it. A second, direct-only registration makes it a plain tool call. @@ -1605,10 +1610,40 @@ function codexThreadRuntimeParams(input: { omit_tools_from: ["code_mode", "deferred"], }, }), + // 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 })), + }, + }), }, }; } +/** Settings → Tools servers as `mcp_servers.` keys, which leave other servers alone. */ +function codexUserMcpServers( + servers: ReadonlyArray, +): Record { + return Object.fromEntries( + servers.map((server) => [ + `mcp_servers.${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 5dbaf3628b11d..bd8d2c62db0d4 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -97,6 +97,7 @@ const durable = { durable: { aggregateID: SESSION, seq: 1, version: 1 } }; const mcpRules = [ { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" }, + { action: "t3u-*", resource: "*", effect: "deny" }, ]; const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules]; const TITLE = "Prime check"; @@ -5484,6 +5485,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { { action: "*", resource: "*", effect: "allow" }, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: `${server}_*`, resource: "*", effect: "allow" }, + { action: "t3u-*", resource: "*", effect: "deny" }, ], }), ), @@ -7076,6 +7078,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { { action: "*", resource: "*", effect: "allow" }, { action: "t3-code-*", resource: "*", effect: "deny" }, { action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" }, + { action: "t3u-*", resource: "*", effect: "deny" }, ], }), reply("session.update", null), diff --git a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts index 8681ce4333cb4..1d21aee9da561 100644 --- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts +++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts @@ -60,10 +60,14 @@ const event = (type: string, data: Record): ProviderReplayEntry }); const labelled = (entry: ProviderReplayEntry, label: string): ProviderReplayEntry => entry.type === "runtime_exit" ? entry : { ...entry, label }; -/** MCP rules are last-match-wins; allow this thread after denying all T3 servers. */ +/** + * MCP rules are last-match-wins; allow this thread after denying all T3 servers. + * 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/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 027c65011dc94..1669678fdfb0f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -401,6 +401,98 @@ it.effect( }).pipe(Effect.provide(layerTest)), ); +it.effect("a change to a thread's tool presets waits for its work and replaces its session", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const outbox = yield* EffectOutbox.EffectOutboxV2; + const threadId = ThreadId.make("thread:tool-presets"); + const sessionId = ProviderSessionId.make("session:tool-presets"); + const now = yield* DateTime.now; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-tool-presets"), + threadId, + projectId: ProjectId.make("project:tool-presets"), + title: "Tools", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* projections.apply({ + id: EventId.make("session:tool-presets"), + type: "provider-session.attached", + threadId, + occurredAt: now, + payload: { + id: sessionId, + driver: adapter.driver, + providerInstanceId: instanceId, + status: "ready", + cwd: "/repo", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + }); + const request = (status: "pending" | "resolved") => + projections.apply({ + id: EventId.make(`request:tool-presets:${status}`), + type: "runtime-request.updated", + threadId, + occurredAt: now, + payload: { + id: RuntimeRequestId.make("tool-presets"), + nodeId: NodeId.make("node:tool-presets"), + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status, + responseCapability: { + type: "live", + providerSessionId: sessionId, + supportsFeedback: false, + }, + createdAt: now, + resolvedAt: status === "resolved" ? now : null, + }, + }); + const setPresets = (commandId: CommandId) => + orchestrator.dispatch({ + type: "thread.tool-presets.set", + commandId, + threadId, + toolPresets: { frontend: true }, + }); + + yield* request("pending"); + const busy = CommandId.make("tool-presets:busy"); + assert.isTrue(Result.isFailure(yield* setPresets(busy).pipe(Effect.result))); + assert.deepEqual(yield* outbox.listByCommandId(busy), []); + + yield* request("resolved"); + const changed = CommandId.make("tool-presets:changed"); + yield* setPresets(changed); + assert.deepEqual((yield* projections.getThreadProjection(threadId)).thread.toolPresets, { + frontend: true, + }); + assert.deepEqual( + (yield* outbox.listByCommandId(changed)).map((effect) => effect.request), + [{ type: "provider-session.detach", providerSessionId: sessionId, detail: "Tools changed." }], + ); + // The same switches again leave the session alone. + const unchanged = CommandId.make("tool-presets:unchanged"); + yield* setPresets(unchanged); + assert.deepEqual(yield* outbox.listByCommandId(unchanged), []); + }).pipe(Effect.provide(layerTest)), +); + it.effect("marks a never-visited thread's first completion unread", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7179e297b1c9c..c92ad41f3797d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -83,6 +83,7 @@ import { managedRuntimeModeCeilingMessage, } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; +import { threadToolPresetsEqual } from "@t3tools/shared/agentTools"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; import { modelSwitchSince } from "./modelSwitch.ts"; @@ -650,6 +651,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.pin.reorder": case "thread.active.reorder": case "thread.tag.set": + case "thread.tool-presets.set": case "thread.visit": case "thread.mark-unread": case "thread.metadata.update": @@ -4010,6 +4012,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio interactionMode: command.interactionMode, branch: command.branch, worktreePath: command.worktreePath, + ...(command.toolPresets === undefined ? {} : { toolPresets: command.toolPresets }), activeProviderThreadId: null, pullRequests: [], ...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }), @@ -4343,6 +4346,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio | "thread.unpin" | "thread.pin.reorder" | "thread.tag.set" + | "thread.tool-presets.set" | "thread.active.reorder" | "thread.mark-unread" | "thread.metadata.update" @@ -4659,7 +4663,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } + const toolPresetsChanged = + command.type === "thread.tool-presets.set" && + !threadToolPresetsEqual(command.toolPresets, thread.toolPresets); const needsProviderState = + toolPresetsChanged || command.type === "thread.runtime-mode.set" || command.type === "thread.model-selection.set" || command.type === "provider.switch" || @@ -4727,7 +4735,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (session) => !session.capabilities.sessions.supportsRuntimeModeSwitchInSession, ) .map((session) => session.id) - : (providerSwitchPlan?.releaseProviderSessionIds ?? []), + : toolPresetsChanged + ? (providerContext?.providerSessions ?? []).map((session) => session.id) + : (providerSwitchPlan?.releaseProviderSessionIds ?? []), ); const liveSessions = (providerContext?.providerSessions ?? []).filter( (session) => @@ -4760,6 +4770,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const now = yield* DateTime.now; + if (toolPresetsChanged) { + const projection = yield* loadProjectionForCommand(command, ["runs", "runtimeRequests"], { + turnItemTypes: [], + }); + // A session's tools are fixed when it opens, and replacing it would end the run. + if (threadHasUnfinishedWork(projection)) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Tools can change once the thread's current work finishes.", + }); + } + } if (command.type === "thread.metadata.update" && command.limitRecovery != null) { const projection = yield* loadProjectionForCommand( command, @@ -5022,6 +5045,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: thread.updatedAt, }; } + case "thread.tool-presets.set": + return { ...thread, toolPresets: command.toolPresets }; case "thread.tag.set": { const current = thread.tags ?? []; return { @@ -5493,6 +5518,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return "thread.active-reordered" as const; case "thread.tag.set": return "thread.tags-updated" as const; + case "thread.tool-presets.set": + return "thread.tool-presets-updated" as const; case "thread.mark-unread": return "thread.marked-unread" as const; case "thread.metadata.update": @@ -5723,7 +5750,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? "Workspace changed." : command.type === "thread.runtime-mode.set" ? "Runtime mode changed." - : "Provider or model selection changed.", + : command.type === "thread.tool-presets.set" + ? "Tools changed." + : "Provider or model selection changed.", }, }); const pendingEffect = { @@ -5742,7 +5771,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? "Workspace changed." : command.type === "thread.runtime-mode.set" ? "Runtime mode changed." - : "Provider or model selection changed.", + : command.type === "thread.tool-presets.set" + ? "Tools changed." + : "Provider or model selection changed.", // Terminal detaches revoke MCP credentials; reattachments need other detach reasons to preserve them. ...(command.type === "thread.archive" ? { revokeMcpCredential: true } : {}), }, @@ -15680,6 +15711,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pin.reorder": case "thread.active.reorder": case "thread.tag.set": + case "thread.tool-presets.set": case "thread.mark-unread": case "thread.pull-request.link": case "thread.pull-request.unlink": diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a30893bc4ca8f..5a80e2fa901aa 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1064,6 +1064,7 @@ export function applyToProjection( // Reordering and PR refreshes preserve the orchestrator's activity timestamp. case "thread.active-reordered": case "thread.tags-updated": + case "thread.tool-presets-updated": case "thread.pull-request-synced": case "thread.issue-synced": return { @@ -2002,6 +2003,9 @@ export function threadShellFromProjection( autoSettleDisabledAt: projection.thread.autoSettleDisabledAt ?? null, pinOrderKey: projection.thread.pinOrderKey ?? null, ...(projection.thread.tags?.length ? { tags: projection.thread.tags } : {}), + ...(projection.thread.toolPresets === undefined + ? {} + : { toolPresets: projection.thread.toolPresets }), lastVisitedAt: projection.thread.lastVisitedAt, opens: projection.thread.opens ?? null, titleRegeneration: projection.thread.titleRegeneration ?? null, @@ -2300,6 +2304,9 @@ function shellFromState(input: { autoSettleDisabledAt: input.state.thread.autoSettleDisabledAt ?? null, pinOrderKey: input.state.thread.pinOrderKey ?? null, ...(input.state.thread.tags?.length ? { tags: input.state.thread.tags } : {}), + ...(input.state.thread.toolPresets === undefined + ? {} + : { toolPresets: input.state.thread.toolPresets }), lastVisitedAt: input.state.thread.lastVisitedAt, opens: input.state.thread.opens ?? null, titleRegeneration: input.state.thread.titleRegeneration ?? null, @@ -2503,6 +2510,7 @@ export const layer: Layer.Layer = case "thread.pin-reordered": case "thread.active-reordered": case "thread.tags-updated": + case "thread.tool-presets-updated": case "thread.visited": case "thread.marked-unread": case "thread.metadata-updated": @@ -3356,6 +3364,7 @@ export const layer: Layer.Layer = event.type !== "thread.pin-reordered" && event.type !== "thread.active-reordered" && event.type !== "thread.tags-updated" && + event.type !== "thread.tool-presets-updated" && event.type !== "thread.visited" && event.type !== "thread.visit-recorded" && event.type !== "thread.marked-unread" && diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index a495ec7be1630..c06d5dbe85f1c 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -52,6 +52,8 @@ import { ProviderWorkspaceMissingError } from "../provider/Errors.ts"; import * as ProviderInstallationGate from "../provider/ProviderInstallationGate.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import { EMPTY_MCP_PROVIDER_SESSION_TOOLS } 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 EventSink from "./EventSink.ts"; @@ -463,7 +465,12 @@ export const layerWithOptions = ( ); 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); @@ -485,19 +492,27 @@ export const layerWithOptions = ( settings.enableDeviceSupport && !deviceOverridden && settings.enableAgentDeviceAccess, + tools: resolveAgentTools(settings, null, thread.toolPresets), }; } const effective = resolveProjectSettings(settings, thread.projectId).settings; return { browser: effective.enableAgentBrowserAccess, device: settings.enableDeviceSupport && effective.enableAgentDeviceAccess, + tools: resolveAgentTools(settings, thread.projectId, thread.toolPresets), }; }).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, + }), + ), ), ); }, @@ -575,8 +590,11 @@ export const layerWithOptions = ( threadId, Effect.gen(function* () { // Live providers build MCP clients once; reuse credentials across workspace handoffs. - 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", "issues"]); @@ -621,6 +639,9 @@ export const layerWithOptions = ( // A credential issued while the lineage read failed is replaced once it works. (resolved.thread.subagent === true) === subagent ) { + // 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, tools }); return { mcpCredentialId: existing.providerSessionId, issued: false }; } dropMcpCredentialReservation(threadId, existing.providerSessionId); @@ -635,6 +656,7 @@ export const layerWithOptions = ( }); yield* mcpSessions.set({ ...credential.config, + tools, hasPendingWake: projectionStore .getThreadRecords(threadId, ["runs", "subagents"]) .pipe( diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index a7397febc0ff4..f270f35468ea2 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -15,6 +15,7 @@ import { type OrchestrationV2ThreadProjection, type ProviderDriverKind, type ProviderInteractionMode, + type ThreadToolPresets, ProjectId, type RunId, type RuntimeMode, @@ -100,6 +101,7 @@ export interface ThreadLaunchInput { readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; + readonly toolPresets?: ThreadToolPresets; readonly workspaceStrategy: ThreadLaunchWorkspaceStrategy; readonly initialMessage?: ThreadLaunchInitialMessage; readonly importedNativeThread?: { @@ -1382,6 +1384,7 @@ const make = Effect.gen(function* () { interactionMode: input.interactionMode, branch: initialBranch, worktreePath: initialWorktreePath, + ...(input.toolPresets === undefined ? {} : { toolPresets: input.toolPresets }), ...(input.importedNativeThread === undefined ? {} : { importedNativeThread: input.importedNativeThread }), diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b20feef64eadd..49c1f454f9a3e 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -676,6 +676,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: Effect.andThen(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/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 15ac7ecb8d3fe..92fe8e19169e7 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -155,6 +155,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray"}, "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/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index c0a11aa3e6114..53823af728974 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -42,6 +42,7 @@ import { PullRequestService } from "../pullRequest/PullRequestService.ts"; import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts"; import { SecretRequests } from "../secrets/SecretRequests.ts"; import { ServerSettingsService } from "../serverSettings.ts"; +import { SkillLibrary } from "../skills/SkillLibrary.ts"; import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; import { GitVcsDriver } from "../vcs/GitVcsDriver.ts"; import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts"; @@ -80,6 +81,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(RemoteDelegation)({}), Layer.mock(ScheduledTaskService)({}), Layer.mock(SecretRequests)({}), + Layer.mock(SkillLibrary)({}), ServerConfig.layerTest(process.cwd(), { prefix: "t3-agent-context-budget-" }), Layer.mock(ServerEnvironment)({}), Layer.mock(ServerSecretStore)({}), @@ -163,3 +165,12 @@ it.effect("agent context matches the committed budget", () => ).toEqual(budget); }).pipe(Effect.provide(layerAdvertisedTools)), ); + +// Settings → Tools lists t3-code's tools from T3_MCP_TOOLKITS, without a session. +it.effect("Settings → Tools lists every tool the T3 MCP server registers", () => + Effect.gen(function* () { + const mcp = yield* McpServer.McpServer; + const listed = McpHttpServer.T3_MCP_TOOLKITS.flatMap((toolkit) => Object.keys(toolkit.tools)); + expect(listed.toSorted()).toEqual(mcp.tools.map(({ tool }) => tool.name).toSorted()); + }).pipe(Effect.provide(layerAdvertisedTools)), +); diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index e4ec16b77dde0..5fd9c4a077452 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -435,6 +435,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/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index aa4cc9f365389..66ffbecfca54e 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 58405 + "mcpToolListJsonBytes": 60499 } diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 2eed87a8033bd..b69af5188e79f 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -118,6 +118,7 @@ function shouldPublishAgentAwarenessEvent( case "thread.pin-reordered": case "thread.active-reordered": case "thread.tags-updated": + case "thread.tool-presets-updated": case "thread.visited": case "thread.visit-recorded": case "thread.marked-unread": diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index c838cfc2b7872..b5836d204dda5 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -99,6 +99,7 @@ import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerMcpClient from "./peer/PeerMcpClient.ts"; import * as PeerThreadRelay from "./peer/PeerThreadRelay.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"; @@ -130,6 +131,7 @@ import * as ProviderInstallationGate from "./provider/ProviderInstallationGate.t 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"; @@ -738,6 +740,8 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ProviderInstallation.layer, 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 f837fd8ca9722..e649aabd49cc3 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1979,6 +1979,228 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }), ); + 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, { + secretReferences: true, + }); + 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, { + secretReferences: true, + }); + 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 d4ddfd8b5c0c1..8ce62ea3441b7 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -62,6 +62,12 @@ import { readSecretFieldValues, sourceControlHostSecretName, } from "./sourceControl/sourceControlHostSecrets.ts"; +import { + materializeMcpServerSecrets, + mcpServerSecretNames, + planMcpServerSecrets, + redactMcpServerSecrets, +} from "./mcpServerSecrets.ts"; import { mapSettingsSecrets, @@ -156,7 +162,10 @@ export function redactServerSettingsForClient( : mapSettingsSecretValues(redacted, (value) => isSecretReference(value) ? SECRET_REDACTED : value, ); - return { ...shaped, secretProviders: withoutUnknownSecretProviderConfigs(shaped) }; + return redactMcpServerSecrets({ + ...shaped, + secretProviders: withoutUnknownSecretProviderConfigs(shaped), + }); } /** A client shown a reference as a saved secret sends that marker back; it keeps the reference. */ @@ -268,6 +277,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, @@ -330,6 +347,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* () { @@ -970,13 +991,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 value = yield* secretStore + .get(secretName) + .pipe( + Effect.mapError( + (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }), + ), + ); + if (Option.isSome(value)) mcpSecrets.set(secretName, textDecoder.decode(value.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, + ); }, ); @@ -1028,6 +1063,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" } ); @@ -1104,13 +1141,26 @@ const make = Effect.gen(function* () { : {}), }); } - return { - settings, - // A redacted row still claims its stored secret, so a duplicate row must not remove it. - changes: changes.filter( - (change) => change.kind === "write" || !keptSecretNames.has(change.secretName), - ), - }; + // A redacted row still claims its stored secret, so a duplicate row must not remove it. + const kept = changes.filter( + (change) => change.kind === "write" || !keptSecretNames.has(change.secretName), + ); + // MCP server variables keep their own secret names, which follow a rename. + const mcp = planMcpServerSecrets(current, settings); + for (const change of mcp.changes) { + kept.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: kept }; }); const rollbackSettingsSecretWrites = ( @@ -1147,51 +1197,75 @@ 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), ); }; + /** `patchOf` may build the patch from the latest settings, read inside the write lock. */ const updateAndPersistSettings = ( - patch: ServerSettingsPatch, - update: (current: ServerSettings) => Effect.Effect, + patchOf: ServerSettingsPatch | ((current: ServerSettings) => ServerSettingsPatch), + update: ( + current: ServerSettings, + patch: ServerSettingsPatch, + ) => Effect.Effect, ): Effect.Effect => writeSemaphore.withPermits(1)( Effect.gen(function* () { @@ -1203,11 +1277,12 @@ const make = Effect.gen(function* () { cause: parseFailure.value, }); } + const patch = typeof patchOf === "function" ? patchOf(current) : patchOf; // An older client echoes a reference as the redacted marker; restore it before vetting so // a removed provider's reference is cleared below rather than restored by persistence. const updated = withoutRedirectedSimlockTokens( current, - withEchoedSecretReferences(current, yield* update(current)), + withEchoedSecretReferences(current, yield* update(current, patch)), ); // Vet before secrets: a variable the policy hides from clients is not one they removed. const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch); @@ -1420,6 +1495,12 @@ const make = Effect.gen(function* () { Effect.as(applyServerSettingsPatch(current, patch)), ), ), + updateSettingsWith: (patchOf) => + updateAndPersistSettings(patchOf, (current, patch) => + ensureSecretProviderWritesAllowed(patch, settingsPath).pipe( + Effect.as(applyServerSettingsPatch(current, patch)), + ), + ), updateProviderInstance: (mutation, patch = {}) => updateAndPersistSettings(patch, (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..874499a61461b --- /dev/null +++ b/apps/server/src/skills/SkillLibrary.test.ts @@ -0,0 +1,547 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +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(Layer.mergeAll(NodeServices.layer, NodeCrypto.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)), + ), +); + +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)), + ), +); + +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"); + }), + ), +); + +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)), + ), +); + +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)), + ), +); + +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)), + ), +); + +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)), + ), +); + +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)), + ), +); + +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)), + ), +); + +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..d77ff3c216276 --- /dev/null +++ b/apps/server/src/skills/SkillLibrary.ts @@ -0,0 +1,855 @@ +/** + * Installs skills through the `skills` CLI (SkillsCli.ts) and describes the folders agents + * report. The CLI's lock files say where each install came from, which groups skills by + * source and limits Update to what it installed. On/off switches stay in settings. + */ +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 Digest from "effect/crypto/Digest"; +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* Digest.Digest; + 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 = Effect.fn("SkillLibrary.refreshAgents")(function* ( + target: SkillInstallTarget, + ) { + 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 other agents' snapshots of its folder, and a scan whose + // starting snapshot changed is discarded. So per folder only the first agent scans + // fresh and the rest follow one at a time; 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(Digest.sha256, 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 = Effect.fn("SkillLibrary.installInto")(function* ( + target: SkillInstallTarget, + source: string, + skills: ReadonlyArray, + fullDepth = false, + ) { + 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 = Effect.fn("SkillLibrary.updateLocked")(function* ( + target: SkillInstallTarget, + name: string, + ) { + 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 = Effect.fn("SkillLibrary.removeLocked")(function* ( + target: SkillInstallTarget, + name: string, + ) { + 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 = Effect.fn("SkillLibrary.removeUnlocked")(function* ( + target: SkillInstallTarget, + name: string, + ) { + 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 = Effect.fn("SkillLibrary.reportedFolder")(function* ( + target: SkillInstallTarget, + name: string, + ) { + 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 = Effect.fn("SkillLibrary.importLocked")(function* ( + target: SkillInstallTarget, + bundle: SkillBundle, + ) { + 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..12abb7bb66eb8 --- /dev/null +++ b/apps/server/src/skills/SkillsCli.ts @@ -0,0 +1,142 @@ +/** + * Runs the bundled `skills` CLI through the hidden `t3 skills-cli` subcommand, so installs + * write what `npx skills` would. Arguments come from typed input only; telemetry is off, + * git never prompts and stdin is closed, so the CLI can't wait on anyone. + */ +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 7839ff2c04c22..dd71bc536dd6b 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -147,6 +147,8 @@ import * as TerminalManager from "./terminal/Manager.ts"; import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as McpServerTools from "./mcpServers/McpServerTools.ts"; +import * as SkillLibrary from "./skills/SkillLibrary.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; @@ -881,6 +883,8 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ScheduledTasks.ScheduledTaskService)({}), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(SecretResolver.SecretResolver)({}), + Layer.mock(SkillLibrary.SkillLibrary)({}), + Layer.mock(McpServerTools.McpServerTools)({}), Layer.mock(GuestShareService.GuestShareService)({}), Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}), Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 67c4b02d4fa86..08da599f6c63e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -216,6 +216,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"; @@ -1569,6 +1571,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()); @@ -2219,6 +2223,9 @@ export const layerWsRpc = ( modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, + ...(input.toolPresets === undefined + ? {} + : { toolPresets: input.toolPresets }), workspaceStrategy: input.workspaceStrategy, ...(input.initialMessage === undefined ? {} @@ -3033,6 +3040,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( @@ -3642,6 +3657,7 @@ export const layer = Layer.unwrap( const peerThreadRelay = yield* PeerThreadRelay.PeerThreadRelay; const peerClientPairing = yield* PeerClientPairing.PeerClientPairing; const sql = yield* SqlClient.SqlClient; + const serverSettingsService = yield* ServerSettings.ServerSettingsService; return HttpRouter.add( "GET", "/ws", @@ -3687,21 +3703,25 @@ export const layer = Layer.unwrap( Effect.provideService(RpcServer.Protocol, withOutputWindow(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, + (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); + }, + serverSettingsService.getSettings.pipe(Effect.orElseSucceed(() => undefined)), + ), rpcInstrumentationLayer, ), ), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 11258afd7ba18..ce9bdbff40b4c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3740,6 +3740,7 @@ export default function ChatView(props: ChatViewProps) { draftId={draftId} activeThreadId={activeThreadId} activeThread={activeThread} + activeThreadShell={activeThreadShell} activeThreadRuns={serverProjection?.runs ?? EMPTY_RUNS} promptHistoryEntries={timelineEntries} forceExpandedOnMobile={ @@ -3822,6 +3823,7 @@ export default function ChatView(props: ChatViewProps) { getShortcutContext={getShortcutContextStable} 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 bcd4a11e5d2f1..93d7da5826de0 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -255,7 +255,7 @@ import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; -import { isVideoAttachment, type SessionPhase, type Thread } from "../../types"; +import { isVideoAttachment, type SessionPhase, type Thread, type ThreadShell } from "../../types"; import { type ComposerPromptHistoryPosition } from "./composerPromptHistory"; import { usePendingUserInputDraft } from "./usePendingThreadRequests"; import type { PendingApproval, PendingUserInput, TimelineEntry } from "../../session-logic"; @@ -268,6 +268,7 @@ import { resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "@t3tools/client-runtime/providerSkills"; +import { mergeProjectDisabledSkills } from "@t3tools/shared/projectSettings"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import { Kbd } from "../ui/kbd"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; @@ -290,6 +291,7 @@ import { useSubmitAfterPreparingImages, } from "./preparingComposerImages"; import { ComposerControlsBar } from "./ComposerControlsBar"; +import { useComposerToolPresets } from "./ComposerToolPresets"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { usePromptSuggestion } from "./usePromptSuggestion"; import { useFreshSessionArmed } from "./freshSessionArms"; @@ -377,6 +379,7 @@ export interface ChatComposerProps { activeThreadId: ThreadId | null; activeThread: Thread | undefined; + activeThreadShell: ThreadShell | null; activeThreadRuns: ReadonlyArray; promptHistoryEntries: ReadonlyArray; forceExpandedOnMobile: boolean; @@ -432,6 +435,8 @@ export interface ChatComposerProps { getShortcutContext: (eventTarget: EventTarget | null) => ShortcutMatchContext; 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; @@ -548,6 +553,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) getShortcutContext, terminalOpen, gitCwd, + skillsProjectId, pullRequestProjectId, pullRequestRepository, threadPullRequests, @@ -961,12 +967,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (multipleModelSelections === null ? providerSendBlockReason : null))); const isSendDisabled = sendDisabledReason !== null; const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null; - 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())); + const providerSlashCommands = selectedProviderStatus ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd) : NO_PROVIDER_SLASH_COMMANDS; + // Claude also lists each skill as a slash command; a disabled one leaves both. + const selectedProviderSlashCommands = + disabledSkillNames.size === 0 + ? providerSlashCommands + : providerSlashCommands.filter( + (command) => !disabledSkillNames.has(command.name.toLowerCase()), + ); const { refresh: refreshWorkspaceSnapshotOnTyping, scanning: workspaceSkillsScanning } = useProviderWorkspaceSnapshotRefresh({ environmentId, @@ -2501,6 +2528,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : composerControlsCollapsed ? 0 : expandedControlsIconOnlyBlockCount; + const toolPresets = useComposerToolPresets({ + environmentId, + projectId: activeProjectId, + cwd: gitCwd, + routeKind, + routeThreadRef, + draftId, + threadShell: props.activeThreadShell, + running: + phase === "running" || + (props.activeThreadShell?.hasPendingApprovals ?? false) || + (props.activeThreadShell?.hasPendingUserInput ?? false), + }); const composerControls = ( ); // An open question owns the space above the composer. Only a machine problem, diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx index 54bf591b28ce9..11ccb3ace2eaf 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx @@ -2,16 +2,19 @@ import type { RuntimeMode } from "@t3tools/contracts"; import { useGT } from "gt-react"; import { memo, useRef } from "react"; import { EllipsisIcon } from "lucide-react"; -import { Menu, MenuPopup, MenuTrigger } from "../ui/menu"; +import { Menu, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu"; import { ComposerControl, ComposerControlIcon } from "./ComposerControl"; import { focusRequestedPermission, useComposerMenuProps } from "./composerEventScope"; import { useComposerMenuState } from "./useComposerMenuState"; import { ComposerPermissionsSection, type RuntimeModeOption } from "./ComposerFooterControls"; +import { type ComposerToolPresets, ComposerToolPresetsSection } from "./ComposerToolPresets"; export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: { runtimeMode: RuntimeMode; runtimeModeOptions: ReadonlyArray; showPermissions: boolean; + /** The tool presets, when their chip moved into this menu. */ + toolPresets?: ComposerToolPresets | null; size?: "sm" | "xs"; /** Close the portaled popup when its trigger hides. */ hidden?: boolean; @@ -50,6 +53,12 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls onRuntimeModeChange={props.onRuntimeModeChange} /> ) : null} + {props.toolPresets ? ( + <> + {props.showPermissions ? : null} + + + ) : null} ); diff --git a/apps/web/src/components/chat/ComposerControlsBar.tsx b/apps/web/src/components/chat/ComposerControlsBar.tsx index 0688cdfe2b2ad..3d801e7c134cc 100644 --- a/apps/web/src/components/chat/ComposerControlsBar.tsx +++ b/apps/web/src/components/chat/ComposerControlsBar.tsx @@ -31,6 +31,7 @@ import { } from "./ComposerModelEffort"; import type { useComposerProviderModel } from "./useComposerProviderModel"; import { resolveComposerControlsOwnership } from "./composerControlsOwnership"; +import { type ComposerToolPresets, ComposerToolPresetsControl } from "./ComposerToolPresets"; /** * The composer footer controls: the model picker (which also holds effort, speed and @@ -87,6 +88,8 @@ export function ComposerControlsBar(props: { onModelPickerOpenChange: (open: boolean) => void; modelPickerIconClassName: string | undefined; getModelDisabledReason: ChatComposerProps["getModelDisabledReason"]; + /** Null while the environment has no presets. */ + toolPresets: ComposerToolPresets | null; }) { const { environmentId, @@ -131,6 +134,7 @@ export function ComposerControlsBar(props: { onModelPickerOpenChange, modelPickerIconClassName, getModelDisabledReason, + toolPresets, } = props; const accessMatchesDefault = compatibleRuntimeMode === defaultRuntimeMode; const { @@ -138,10 +142,13 @@ export function ComposerControlsBar(props: { showModeBlock, hiddenBlockCount: restingHiddenBlockCount, hiddenBlockIds: hiddenRestingBlockIds, + modeHidden, + toolsHidden, overflowShowsPermissions, pickerOwnsModeShortcut, } = resolveComposerControlsOwnership({ matchesDefault: accessMatchesDefault || props.permissionsShownInStrip, + toolsBlock: toolPresets !== null, collapsed: composerControlsCollapsed, measuredHiddenBlockCount, }); @@ -165,24 +172,40 @@ export function ComposerControlsBar(props: { onPromptEdit, }); const effort = describeComposerEffort(traitsInput, props.effortDisplay, controlSize, m); - const restingBlockDefs = showModeBlock - ? [ - { - id: "mode", - content: ( -