@within-7/minto 0.1.7 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.js +155 -37
- package/dist/Tool.js +38 -0
- package/dist/Tool.js.map +3 -3
- package/dist/commands/agents/AgentsCommand.js +52 -26
- package/dist/commands/agents/AgentsCommand.js.map +2 -2
- package/dist/commands/agents/constants.js +1 -1
- package/dist/commands/agents/constants.js.map +1 -1
- package/dist/commands/agents/index.js +1 -1
- package/dist/commands/bug.js +74 -7
- package/dist/commands/bug.js.map +3 -3
- package/dist/commands/clear.js +3 -0
- package/dist/commands/clear.js.map +2 -2
- package/dist/commands/compact.js +37 -0
- package/dist/commands/compact.js.map +2 -2
- package/dist/commands/context.js +84 -0
- package/dist/commands/context.js.map +7 -0
- package/dist/commands/ctx_viz.js +18 -10
- package/dist/commands/ctx_viz.js.map +2 -2
- package/dist/commands/doctor.js +158 -12
- package/dist/commands/doctor.js.map +2 -2
- package/dist/commands/export.js +156 -0
- package/dist/commands/export.js.map +7 -0
- package/dist/commands/mcp-interactive.js +21 -12
- package/dist/commands/mcp-interactive.js.map +2 -2
- package/dist/commands/model.js +6 -5
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/permissions.js +86 -0
- package/dist/commands/permissions.js.map +7 -0
- package/dist/commands/quit.js +3 -1
- package/dist/commands/quit.js.map +2 -2
- package/dist/commands/sandbox.js +104 -0
- package/dist/commands/sandbox.js.map +7 -0
- package/dist/commands/status.js +58 -0
- package/dist/commands/status.js.map +7 -0
- package/dist/commands/tasks.js +108 -0
- package/dist/commands/tasks.js.map +7 -0
- package/dist/commands/todos.js +123 -0
- package/dist/commands/todos.js.map +7 -0
- package/dist/commands.js +20 -2
- package/dist/commands.js.map +2 -2
- package/dist/components/AgentThinkingBlock.js +10 -18
- package/dist/components/AgentThinkingBlock.js.map +2 -2
- package/dist/components/BackgroundTasksPanel.js +78 -29
- package/dist/components/BackgroundTasksPanel.js.map +2 -2
- package/dist/components/BashStreamingProgress.js +24 -0
- package/dist/components/BashStreamingProgress.js.map +7 -0
- package/dist/components/CollapsibleHint.js +14 -0
- package/dist/components/CollapsibleHint.js.map +7 -0
- package/dist/components/FileEditToolUpdatedMessage.js +1 -1
- package/dist/components/FileEditToolUpdatedMessage.js.map +2 -2
- package/dist/components/HotkeyHelpPanel.js +137 -0
- package/dist/components/HotkeyHelpPanel.js.map +7 -0
- package/dist/components/Logo.js +5 -5
- package/dist/components/Logo.js.map +2 -2
- package/dist/components/Message.js +23 -7
- package/dist/components/Message.js.map +3 -3
- package/dist/components/ModelConfig.js +16 -3
- package/dist/components/ModelConfig.js.map +2 -2
- package/dist/components/ModelListManager.js +3 -3
- package/dist/components/ModelListManager.js.map +2 -2
- package/dist/components/ModelSelector/ModelSelector.js +1 -1
- package/dist/components/Onboarding.js +19 -14
- package/dist/components/Onboarding.js.map +2 -2
- package/dist/components/ProgressBar.js +74 -0
- package/dist/components/ProgressBar.js.map +7 -0
- package/dist/components/PromptInput.js +156 -46
- package/dist/components/PromptInput.js.map +2 -2
- package/dist/components/RequestStatusIndicator.js +194 -0
- package/dist/components/RequestStatusIndicator.js.map +7 -0
- package/dist/components/Spinner.js +92 -27
- package/dist/components/Spinner.js.map +2 -2
- package/dist/components/SpinnerSymbol.js +21 -27
- package/dist/components/SpinnerSymbol.js.map +2 -2
- package/dist/components/StreamingBashOutput.js +9 -8
- package/dist/components/StreamingBashOutput.js.map +2 -2
- package/dist/components/SubagentBlock.js +1 -1
- package/dist/components/SubagentBlock.js.map +1 -1
- package/dist/components/SubagentProgress.js +10 -11
- package/dist/components/SubagentProgress.js.map +2 -2
- package/dist/components/TaskCard.js +16 -13
- package/dist/components/TaskCard.js.map +2 -2
- package/dist/components/TodoChangeBlock.js +1 -1
- package/dist/components/TodoChangeBlock.js.map +2 -2
- package/dist/components/TodoPanel.js +120 -29
- package/dist/components/TodoPanel.js.map +3 -3
- package/dist/components/TokenCounter.js +74 -0
- package/dist/components/TokenCounter.js.map +7 -0
- package/dist/components/TokenWarning.js +2 -1
- package/dist/components/TokenWarning.js.map +2 -2
- package/dist/components/TreeConnector.js +25 -0
- package/dist/components/TreeConnector.js.map +7 -0
- package/dist/components/TurnCompletionIndicator.js +18 -0
- package/dist/components/TurnCompletionIndicator.js.map +7 -0
- package/dist/components/messages/AssistantTextMessage.js +5 -2
- package/dist/components/messages/AssistantTextMessage.js.map +2 -2
- package/dist/components/messages/AssistantThinkingMessage.js +18 -3
- package/dist/components/messages/AssistantThinkingMessage.js.map +2 -2
- package/dist/components/messages/AssistantToolUseMessage.js +11 -8
- package/dist/components/messages/AssistantToolUseMessage.js.map +2 -2
- package/dist/components/messages/GroupRenderer.js +53 -0
- package/dist/components/messages/GroupRenderer.js.map +7 -0
- package/dist/components/messages/NestedTasksPreview.js +12 -0
- package/dist/components/messages/NestedTasksPreview.js.map +7 -0
- package/dist/components/messages/ParallelTasksGroupView.js +92 -0
- package/dist/components/messages/ParallelTasksGroupView.js.map +7 -0
- package/dist/components/messages/TaskInModuleView.js +198 -0
- package/dist/components/messages/TaskInModuleView.js.map +7 -0
- package/dist/components/messages/TaskOutputContent.js +53 -0
- package/dist/components/messages/TaskOutputContent.js.map +7 -0
- package/dist/components/messages/UserPromptMessage.js +1 -1
- package/dist/components/messages/UserPromptMessage.js.map +2 -2
- package/dist/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +2 -3
- package/dist/components/messages/UserToolResultMessage/UserToolSuccessMessage.js.map +2 -2
- package/dist/components/permissions/FallbackPermissionRequest.js +4 -4
- package/dist/components/permissions/FallbackPermissionRequest.js.map +2 -2
- package/dist/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +4 -4
- package/dist/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js.map +2 -2
- package/dist/constants/colors.js +48 -0
- package/dist/constants/colors.js.map +2 -2
- package/dist/constants/formatRules.js +102 -0
- package/dist/constants/formatRules.js.map +7 -0
- package/dist/constants/prompts.js +12 -34
- package/dist/constants/prompts.js.map +2 -2
- package/dist/constants/symbols.js +64 -6
- package/dist/constants/symbols.js.map +2 -2
- package/dist/constants/timing.js +5 -0
- package/dist/constants/timing.js.map +2 -2
- package/dist/core/config/defaults.js +84 -0
- package/dist/core/config/defaults.js.map +7 -0
- package/dist/core/config/index.js +111 -0
- package/dist/core/config/index.js.map +7 -0
- package/dist/core/config/loader.js +221 -0
- package/dist/core/config/loader.js.map +7 -0
- package/dist/core/config/migrations.js +128 -0
- package/dist/core/config/migrations.js.map +7 -0
- package/dist/core/config/schema.js +178 -0
- package/dist/core/config/schema.js.map +7 -0
- package/dist/core/costTracker.js +138 -0
- package/dist/core/costTracker.js.map +7 -0
- package/dist/core/index.js +5 -0
- package/dist/core/index.js.map +7 -0
- package/dist/core/permissions/auditLog.js +204 -0
- package/dist/core/permissions/auditLog.js.map +7 -0
- package/dist/core/permissions/engine/index.js +3 -0
- package/dist/core/permissions/engine/index.js.map +7 -0
- package/dist/core/permissions/engine/permissionEngine.js +106 -0
- package/dist/core/permissions/engine/permissionEngine.js.map +7 -0
- package/dist/core/permissions/engine/types.js +1 -0
- package/dist/core/permissions/engine/types.js.map +7 -0
- package/dist/core/permissions/index.js +84 -0
- package/dist/core/permissions/index.js.map +7 -0
- package/dist/core/permissions/ruleEngine.js +259 -0
- package/dist/core/permissions/ruleEngine.js.map +7 -0
- package/dist/core/permissions/rules/allowedToolsRule.js +62 -0
- package/dist/core/permissions/rules/allowedToolsRule.js.map +7 -0
- package/dist/core/permissions/rules/autoEscalationRule.js +291 -0
- package/dist/core/permissions/rules/autoEscalationRule.js.map +7 -0
- package/dist/core/permissions/rules/index.js +46 -0
- package/dist/core/permissions/rules/index.js.map +7 -0
- package/dist/core/permissions/rules/planModeRule.js +55 -0
- package/dist/core/permissions/rules/planModeRule.js.map +7 -0
- package/dist/core/permissions/rules/projectBoundaryRule.js +168 -0
- package/dist/core/permissions/rules/projectBoundaryRule.js.map +7 -0
- package/dist/core/permissions/rules/safeModeRule.js +65 -0
- package/dist/core/permissions/rules/safeModeRule.js.map +7 -0
- package/dist/core/permissions/rules/sensitivePathsRule.js +340 -0
- package/dist/core/permissions/rules/sensitivePathsRule.js.map +7 -0
- package/dist/core/permissions/types.js +127 -0
- package/dist/core/permissions/types.js.map +7 -0
- package/dist/core/tools/executor.js +143 -0
- package/dist/core/tools/executor.js.map +7 -0
- package/dist/core/tools/index.js +15 -0
- package/dist/core/tools/index.js.map +7 -0
- package/dist/core/tools/registry.js +183 -0
- package/dist/core/tools/registry.js.map +7 -0
- package/dist/core/tools/types.js +1 -0
- package/dist/core/tools/types.js.map +7 -0
- package/dist/cost-tracker.js +23 -15
- package/dist/cost-tracker.js.map +2 -2
- package/dist/entrypoints/cli.js +43 -43
- package/dist/entrypoints/cli.js.map +2 -2
- package/dist/entrypoints/mcp.js +12 -4
- package/dist/entrypoints/mcp.js.map +2 -2
- package/dist/history.js +14 -3
- package/dist/history.js.map +2 -2
- package/dist/hooks/useAgentTranscripts.js +116 -0
- package/dist/hooks/useAgentTranscripts.js.map +7 -0
- package/dist/hooks/useAnimationSync.js +53 -0
- package/dist/hooks/useAnimationSync.js.map +7 -0
- package/dist/hooks/useArrowKeyHistory.js +4 -2
- package/dist/hooks/useArrowKeyHistory.js.map +2 -2
- package/dist/hooks/useCanUseTool.js +3 -1
- package/dist/hooks/useCanUseTool.js.map +2 -2
- package/dist/hooks/useCancelRequest.js +4 -1
- package/dist/hooks/useCancelRequest.js.map +2 -2
- package/dist/hooks/useExitOnCtrlCD.js +9 -5
- package/dist/hooks/useExitOnCtrlCD.js.map +2 -2
- package/dist/hooks/useHookStatus.js +40 -0
- package/dist/hooks/useHookStatus.js.map +7 -0
- package/dist/hooks/useLogMessages.js +17 -1
- package/dist/hooks/useLogMessages.js.map +2 -2
- package/dist/hooks/useMessageGroups.js +43 -0
- package/dist/hooks/useMessageGroups.js.map +7 -0
- package/dist/hooks/useTerminalSize.js +62 -6
- package/dist/hooks/useTerminalSize.js.map +2 -2
- package/dist/hooks/useUnifiedCompletion.js +69 -0
- package/dist/hooks/useUnifiedCompletion.js.map +2 -2
- package/dist/i18n/index.js +109 -0
- package/dist/i18n/index.js.map +7 -0
- package/dist/i18n/locales/en.js +347 -0
- package/dist/i18n/locales/en.js.map +7 -0
- package/dist/i18n/locales/index.js +7 -0
- package/dist/i18n/locales/index.js.map +7 -0
- package/dist/i18n/locales/zh-CN.js +347 -0
- package/dist/i18n/locales/zh-CN.js.map +7 -0
- package/dist/i18n/types.js +8 -0
- package/dist/i18n/types.js.map +7 -0
- package/dist/query.js +175 -17
- package/dist/query.js.map +3 -3
- package/dist/screens/REPL.js +501 -192
- package/dist/screens/REPL.js.map +3 -3
- package/dist/services/adapters/chatCompletions.js +3 -1
- package/dist/services/adapters/chatCompletions.js.map +2 -2
- package/dist/services/adapters/messageNormalizer.js +354 -0
- package/dist/services/adapters/messageNormalizer.js.map +7 -0
- package/dist/services/adapters/responsesAPI.js +6 -3
- package/dist/services/adapters/responsesAPI.js.map +2 -2
- package/dist/services/checkpointManager.js +386 -0
- package/dist/services/checkpointManager.js.map +7 -0
- package/dist/services/claude.js +138 -11
- package/dist/services/claude.js.map +3 -3
- package/dist/services/compressionService.js +50 -1
- package/dist/services/compressionService.js.map +2 -2
- package/dist/services/contextMonitor.js +162 -0
- package/dist/services/contextMonitor.js.map +7 -0
- package/dist/services/customCommands.js +60 -41
- package/dist/services/customCommands.js.map +2 -2
- package/dist/services/hookExecutor.js +173 -1
- package/dist/services/hookExecutor.js.map +2 -2
- package/dist/services/intelligentCompactor.js +281 -0
- package/dist/services/intelligentCompactor.js.map +7 -0
- package/dist/services/lspConfig.js +109 -0
- package/dist/services/lspConfig.js.map +7 -0
- package/dist/services/mcpClient.js +273 -34
- package/dist/services/mcpClient.js.map +2 -2
- package/dist/services/modelOrchestrator.js +310 -0
- package/dist/services/modelOrchestrator.js.map +7 -0
- package/dist/services/openai.js +8 -1
- package/dist/services/openai.js.map +2 -2
- package/dist/services/outputStyles.js +138 -0
- package/dist/services/outputStyles.js.map +7 -0
- package/dist/services/plugins/index.js +5 -0
- package/dist/services/plugins/index.js.map +7 -0
- package/dist/services/plugins/lspServers.js +188 -0
- package/dist/services/plugins/lspServers.js.map +7 -0
- package/dist/services/plugins/pluginRuntime.js +229 -0
- package/dist/services/plugins/pluginRuntime.js.map +7 -0
- package/dist/services/plugins/pluginValidation.js +219 -0
- package/dist/services/plugins/pluginValidation.js.map +7 -0
- package/dist/services/plugins/skillMarketplace.js +556 -0
- package/dist/services/plugins/skillMarketplace.js.map +7 -0
- package/dist/services/responseStateManager.js +37 -3
- package/dist/services/responseStateManager.js.map +2 -2
- package/dist/services/sandbox/filesystemBoundary.js +300 -0
- package/dist/services/sandbox/filesystemBoundary.js.map +7 -0
- package/dist/services/sandbox/index.js +14 -0
- package/dist/services/sandbox/index.js.map +7 -0
- package/dist/services/sandbox/networkProxy.js +293 -0
- package/dist/services/sandbox/networkProxy.js.map +7 -0
- package/dist/services/sandbox/sandboxController.js +574 -0
- package/dist/services/sandbox/sandboxController.js.map +7 -0
- package/dist/services/sandbox/types.js +50 -0
- package/dist/services/sandbox/types.js.map +7 -0
- package/dist/services/sessionMemory.js +266 -0
- package/dist/services/sessionMemory.js.map +7 -0
- package/dist/services/taskRouter.js +324 -0
- package/dist/services/taskRouter.js.map +7 -0
- package/dist/tools/ArchitectTool/ArchitectTool.js +7 -1
- package/dist/tools/ArchitectTool/ArchitectTool.js.map +2 -2
- package/dist/tools/AskExpertModelTool/AskExpertModelTool.js +3 -0
- package/dist/tools/AskExpertModelTool/AskExpertModelTool.js.map +2 -2
- package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js.map +2 -2
- package/dist/tools/BaseTool.js +72 -0
- package/dist/tools/BaseTool.js.map +7 -0
- package/dist/tools/BashOutputTool/BashOutputToolResultMessage.js +3 -0
- package/dist/tools/BashOutputTool/BashOutputToolResultMessage.js.map +2 -2
- package/dist/tools/BashTool/BashTool.js +60 -3
- package/dist/tools/BashTool/BashTool.js.map +2 -2
- package/dist/tools/BashTool/BashToolResultMessage.js +3 -0
- package/dist/tools/BashTool/BashToolResultMessage.js.map +2 -2
- package/dist/tools/BashTool/OutputLine.js +54 -0
- package/dist/tools/BashTool/OutputLine.js.map +2 -2
- package/dist/tools/BashTool/prompt.js +192 -3
- package/dist/tools/BashTool/prompt.js.map +2 -2
- package/dist/tools/FileEditTool/FileEditTool.js +29 -4
- package/dist/tools/FileEditTool/FileEditTool.js.map +2 -2
- package/dist/tools/FileWriteTool/FileWriteTool.js +5 -5
- package/dist/tools/FileWriteTool/FileWriteTool.js.map +2 -2
- package/dist/tools/GlobTool/GlobTool.js +4 -2
- package/dist/tools/GlobTool/GlobTool.js.map +2 -2
- package/dist/tools/GrepTool/GrepTool.js +36 -7
- package/dist/tools/GrepTool/GrepTool.js.map +2 -2
- package/dist/tools/KillShellTool/KillShellToolResultMessage.js +3 -0
- package/dist/tools/KillShellTool/KillShellToolResultMessage.js.map +2 -2
- package/dist/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +109 -0
- package/dist/tools/ListMcpResourcesTool/ListMcpResourcesTool.js.map +7 -0
- package/dist/tools/ListMcpResourcesTool/prompt.js +19 -0
- package/dist/tools/ListMcpResourcesTool/prompt.js.map +7 -0
- package/dist/tools/LspTool/LspTool.js +664 -0
- package/dist/tools/LspTool/LspTool.js.map +7 -0
- package/dist/tools/LspTool/prompt.js +27 -0
- package/dist/tools/LspTool/prompt.js.map +7 -0
- package/dist/tools/MCPTool/MCPTool.js +9 -1
- package/dist/tools/MCPTool/MCPTool.js.map +2 -2
- package/dist/tools/MemoryReadTool/MemoryReadTool.js +19 -6
- package/dist/tools/MemoryReadTool/MemoryReadTool.js.map +2 -2
- package/dist/tools/MemoryWriteTool/MemoryWriteTool.js +6 -6
- package/dist/tools/MemoryWriteTool/MemoryWriteTool.js.map +2 -2
- package/dist/tools/MultiEditTool/MultiEditTool.js +19 -2
- package/dist/tools/MultiEditTool/MultiEditTool.js.map +2 -2
- package/dist/tools/NotebookEditTool/NotebookEditTool.js +5 -1
- package/dist/tools/NotebookEditTool/NotebookEditTool.js.map +2 -2
- package/dist/tools/NotebookReadTool/NotebookReadTool.js.map +2 -2
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js +74 -0
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js.map +7 -0
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js +108 -0
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js.map +7 -0
- package/dist/tools/PlanModeTool/prompt.js +94 -0
- package/dist/tools/PlanModeTool/prompt.js.map +7 -0
- package/dist/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +130 -0
- package/dist/tools/ReadMcpResourceTool/ReadMcpResourceTool.js.map +7 -0
- package/dist/tools/ReadMcpResourceTool/prompt.js +17 -0
- package/dist/tools/ReadMcpResourceTool/prompt.js.map +7 -0
- package/dist/tools/SkillTool/SkillTool.js +6 -1
- package/dist/tools/SkillTool/SkillTool.js.map +2 -2
- package/dist/tools/SlashCommandTool/SlashCommandTool.js +260 -0
- package/dist/tools/SlashCommandTool/SlashCommandTool.js.map +7 -0
- package/dist/tools/SlashCommandTool/prompt.js +35 -0
- package/dist/tools/SlashCommandTool/prompt.js.map +7 -0
- package/dist/tools/TaskOutputTool/TaskOutputTool.js +189 -0
- package/dist/tools/TaskOutputTool/TaskOutputTool.js.map +7 -0
- package/dist/tools/TaskOutputTool/prompt.js +15 -0
- package/dist/tools/TaskOutputTool/prompt.js.map +7 -0
- package/dist/tools/TaskTool/TaskTool.js +302 -104
- package/dist/tools/TaskTool/TaskTool.js.map +2 -2
- package/dist/tools/TaskTool/prompt.js.map +2 -2
- package/dist/tools/TodoWriteTool/TodoWriteTool.js +42 -77
- package/dist/tools/TodoWriteTool/TodoWriteTool.js.map +2 -2
- package/dist/tools/URLFetcherTool/URLFetcherTool.js +4 -1
- package/dist/tools/URLFetcherTool/URLFetcherTool.js.map +2 -2
- package/dist/tools/URLFetcherTool/cache.js +55 -8
- package/dist/tools/URLFetcherTool/cache.js.map +2 -2
- package/dist/tools.js +31 -2
- package/dist/tools.js.map +2 -2
- package/dist/types/hooks.js +4 -0
- package/dist/types/hooks.js.map +2 -2
- package/dist/types/marketplace.js.map +2 -2
- package/dist/types/messageGroup.js +36 -0
- package/dist/types/messageGroup.js.map +7 -0
- package/dist/types/plugin.js.map +2 -2
- package/dist/types/thinking.js +1 -0
- package/dist/types/thinking.js.map +7 -0
- package/dist/utils/BackgroundShellManager.js +136 -39
- package/dist/utils/BackgroundShellManager.js.map +2 -2
- package/dist/utils/MessageBatchBuffer.js +102 -0
- package/dist/utils/MessageBatchBuffer.js.map +7 -0
- package/dist/utils/PersistentShell.js +151 -1
- package/dist/utils/PersistentShell.js.map +2 -2
- package/dist/utils/agentLoader.js +1 -23
- package/dist/utils/agentLoader.js.map +2 -2
- package/dist/utils/agentTranscripts.js +641 -0
- package/dist/utils/agentTranscripts.js.map +7 -0
- package/dist/utils/animationManager.js +213 -0
- package/dist/utils/animationManager.js.map +7 -0
- package/dist/utils/animationSync.js +110 -0
- package/dist/utils/animationSync.js.map +7 -0
- package/dist/utils/asyncFile.js +215 -0
- package/dist/utils/asyncFile.js.map +7 -0
- package/dist/utils/backgroundAgentManager.js +231 -0
- package/dist/utils/backgroundAgentManager.js.map +7 -0
- package/dist/utils/config.js +63 -7
- package/dist/utils/config.js.map +2 -2
- package/dist/utils/conversationRecovery.js +19 -0
- package/dist/utils/conversationRecovery.js.map +2 -2
- package/dist/utils/exit.js +73 -0
- package/dist/utils/exit.js.map +7 -0
- package/dist/utils/format.js +73 -5
- package/dist/utils/format.js.map +2 -2
- package/dist/utils/generators.js +76 -6
- package/dist/utils/generators.js.map +2 -2
- package/dist/utils/globalErrorHandler.js +149 -0
- package/dist/utils/globalErrorHandler.js.map +7 -0
- package/dist/utils/groupHandlers/index.js +8 -0
- package/dist/utils/groupHandlers/index.js.map +7 -0
- package/dist/utils/groupHandlers/parallelTasksHandler.js +140 -0
- package/dist/utils/groupHandlers/parallelTasksHandler.js.map +7 -0
- package/dist/utils/groupHandlers/taskHandler.js +104 -0
- package/dist/utils/groupHandlers/taskHandler.js.map +7 -0
- package/dist/utils/groupHandlers/types.js +1 -0
- package/dist/utils/groupHandlers/types.js.map +7 -0
- package/dist/utils/logRotation.js +224 -0
- package/dist/utils/logRotation.js.map +7 -0
- package/dist/utils/marketplaceManager.js +3 -5
- package/dist/utils/marketplaceManager.js.map +2 -2
- package/dist/utils/memSafety.js +264 -0
- package/dist/utils/memSafety.js.map +7 -0
- package/dist/utils/messageGroupManager.js +274 -0
- package/dist/utils/messageGroupManager.js.map +7 -0
- package/dist/utils/messages.js +13 -4
- package/dist/utils/messages.js.map +2 -2
- package/dist/utils/model.js +119 -15
- package/dist/utils/model.js.map +3 -3
- package/dist/utils/permissions/filesystem.js +157 -5
- package/dist/utils/permissions/filesystem.js.map +2 -2
- package/dist/utils/plan/planMode.js +143 -0
- package/dist/utils/plan/planMode.js.map +7 -0
- package/dist/utils/pluginLoader.js +17 -21
- package/dist/utils/pluginLoader.js.map +2 -2
- package/dist/utils/ripgrep.js +55 -2
- package/dist/utils/ripgrep.js.map +2 -2
- package/dist/utils/sanitizeInput.js +32 -0
- package/dist/utils/sanitizeInput.js.map +7 -0
- package/dist/utils/secureKeyStorage.js +312 -0
- package/dist/utils/secureKeyStorage.js.map +7 -0
- package/dist/utils/session/sessionPlugins.js +67 -0
- package/dist/utils/session/sessionPlugins.js.map +7 -0
- package/dist/utils/taskDisplayUtils.js +257 -0
- package/dist/utils/taskDisplayUtils.js.map +7 -0
- package/dist/utils/teamConfig.js +2 -1
- package/dist/utils/teamConfig.js.map +2 -2
- package/dist/utils/todoStorage.js +92 -2
- package/dist/utils/todoStorage.js.map +2 -2
- package/dist/utils/toolTimeout.js +136 -0
- package/dist/utils/toolTimeout.js.map +7 -0
- package/dist/utils/tooling/safeRender.js +115 -0
- package/dist/utils/tooling/safeRender.js.map +7 -0
- package/dist/utils/userFriendlyError.js +346 -0
- package/dist/utils/userFriendlyError.js.map +7 -0
- package/dist/utils/vendor/ripgrep/arm64-darwin/rg +0 -0
- package/dist/version.js +2 -2
- package/dist/version.js.map +1 -1
- package/package.json +14 -4
- package/scripts/postinstall.js +128 -38
- package/dist/commands/agents.js +0 -2086
- package/dist/commands/agents.js.map +0 -7
- package/dist/commands/build.js +0 -74
- package/dist/commands/build.js.map +0 -7
- package/dist/commands/compression.js +0 -57
- package/dist/commands/compression.js.map +0 -7
- package/dist/commands/listen.js +0 -37
- package/dist/commands/listen.js.map +0 -7
- package/dist/commands/login.js +0 -37
- package/dist/commands/login.js.map +0 -7
- package/dist/commands/logout.js +0 -33
- package/dist/commands/logout.js.map +0 -7
- package/dist/commands/mcp.js +0 -40
- package/dist/commands/mcp.js.map +0 -7
- package/dist/commands/mcp_refresh.js +0 -40
- package/dist/commands/mcp_refresh.js.map +0 -7
- package/dist/commands/modelstatus.js +0 -21
- package/dist/commands/modelstatus.js.map +0 -7
- package/dist/commands/onboarding.js +0 -36
- package/dist/commands/onboarding.js.map +0 -7
- package/dist/commands/plugin-interactive.js +0 -446
- package/dist/commands/plugin-interactive.js.map +0 -7
- package/dist/commands/pr_comments.js +0 -61
- package/dist/commands/pr_comments.js.map +0 -7
- package/dist/commands/release-notes.js +0 -30
- package/dist/commands/release-notes.js.map +0 -7
- package/dist/commands/review.js +0 -51
- package/dist/commands/review.js.map +0 -7
- package/dist/components/Bug.js +0 -147
- package/dist/components/Bug.js.map +0 -7
- package/dist/components/ModelSelector.js +0 -2062
- package/dist/components/ModelSelector.js.map +0 -7
- package/dist/components/ModelStatusDisplay.js +0 -87
- package/dist/components/ModelStatusDisplay.js.map +0 -7
- package/dist/entrypoints/cli-wrapper.js +0 -61
- package/dist/entrypoints/cli-wrapper.js.map +0 -7
- package/dist/screens/Doctor.js +0 -22
- package/dist/screens/Doctor.js.map +0 -7
|
@@ -18,7 +18,9 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
|
18
18
|
import {
|
|
19
19
|
CallToolResultSchema,
|
|
20
20
|
ListPromptsResultSchema,
|
|
21
|
-
ListToolsResultSchema
|
|
21
|
+
ListToolsResultSchema,
|
|
22
|
+
ListResourcesResultSchema,
|
|
23
|
+
ReadResourceResultSchema
|
|
22
24
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
23
25
|
import { memoize, pickBy } from "lodash-es";
|
|
24
26
|
import { MCPTool } from "../tools/MCPTool/MCPTool.js";
|
|
@@ -216,6 +218,101 @@ function getMcprcServerStatus(serverName) {
|
|
|
216
218
|
return "pending";
|
|
217
219
|
}
|
|
218
220
|
let connectedClients = [];
|
|
221
|
+
const DEFAULT_POOL_CONFIG = {
|
|
222
|
+
maxConnections: 10,
|
|
223
|
+
connectionTimeout: 5e3,
|
|
224
|
+
healthCheckInterval: 3e4,
|
|
225
|
+
retryFailed: true,
|
|
226
|
+
maxRetries: 3
|
|
227
|
+
};
|
|
228
|
+
let poolConfig = { ...DEFAULT_POOL_CONFIG };
|
|
229
|
+
let healthCheckTimer = null;
|
|
230
|
+
function configureMcpPool(config) {
|
|
231
|
+
poolConfig = { ...poolConfig, ...config };
|
|
232
|
+
if (config.healthCheckInterval !== void 0) {
|
|
233
|
+
stopHealthCheck();
|
|
234
|
+
if (poolConfig.healthCheckInterval > 0) {
|
|
235
|
+
startHealthCheck();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
function getMcpPoolConfig() {
|
|
240
|
+
return { ...poolConfig };
|
|
241
|
+
}
|
|
242
|
+
const connectionHealth = /* @__PURE__ */ new Map();
|
|
243
|
+
async function checkConnectionHealth(client) {
|
|
244
|
+
const startTime = Date.now();
|
|
245
|
+
try {
|
|
246
|
+
await client.client.getServerCapabilities();
|
|
247
|
+
const latencyMs = Date.now() - startTime;
|
|
248
|
+
return {
|
|
249
|
+
name: client.name,
|
|
250
|
+
status: "healthy",
|
|
251
|
+
lastCheck: Date.now(),
|
|
252
|
+
latencyMs
|
|
253
|
+
};
|
|
254
|
+
} catch (error) {
|
|
255
|
+
return {
|
|
256
|
+
name: client.name,
|
|
257
|
+
status: "unhealthy",
|
|
258
|
+
lastCheck: Date.now(),
|
|
259
|
+
error: error instanceof Error ? error.message : String(error)
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async function runHealthCheck() {
|
|
264
|
+
const clients = await getClients();
|
|
265
|
+
const healthResults = [];
|
|
266
|
+
for (const client of clients) {
|
|
267
|
+
if (client.type === "connected") {
|
|
268
|
+
const health = await checkConnectionHealth(client);
|
|
269
|
+
connectionHealth.set(client.name, health);
|
|
270
|
+
healthResults.push(health);
|
|
271
|
+
} else {
|
|
272
|
+
const health = {
|
|
273
|
+
name: client.name,
|
|
274
|
+
status: "unhealthy",
|
|
275
|
+
lastCheck: Date.now(),
|
|
276
|
+
error: "Connection failed"
|
|
277
|
+
};
|
|
278
|
+
connectionHealth.set(client.name, health);
|
|
279
|
+
healthResults.push(health);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return healthResults;
|
|
283
|
+
}
|
|
284
|
+
function getConnectionHealth() {
|
|
285
|
+
return Array.from(connectionHealth.values());
|
|
286
|
+
}
|
|
287
|
+
function getServerHealth(serverName) {
|
|
288
|
+
return connectionHealth.get(serverName) || null;
|
|
289
|
+
}
|
|
290
|
+
function startHealthCheck() {
|
|
291
|
+
if (healthCheckTimer) return;
|
|
292
|
+
if (poolConfig.healthCheckInterval <= 0) return;
|
|
293
|
+
healthCheckTimer = setInterval(async () => {
|
|
294
|
+
try {
|
|
295
|
+
await runHealthCheck();
|
|
296
|
+
} catch {
|
|
297
|
+
}
|
|
298
|
+
}, poolConfig.healthCheckInterval);
|
|
299
|
+
}
|
|
300
|
+
function stopHealthCheck() {
|
|
301
|
+
if (healthCheckTimer) {
|
|
302
|
+
clearInterval(healthCheckTimer);
|
|
303
|
+
healthCheckTimer = null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function getPoolStats() {
|
|
307
|
+
const health = getConnectionHealth();
|
|
308
|
+
return {
|
|
309
|
+
totalConnections: connectedClients.length,
|
|
310
|
+
connectedCount: connectedClients.filter((c) => c.type === "connected").length,
|
|
311
|
+
failedCount: connectedClients.filter((c) => c.type === "failed").length,
|
|
312
|
+
healthyCount: health.filter((h) => h.status === "healthy").length,
|
|
313
|
+
unhealthyCount: health.filter((h) => h.status === "unhealthy").length
|
|
314
|
+
};
|
|
315
|
+
}
|
|
219
316
|
const getClients = memoize(async () => {
|
|
220
317
|
if (process.env.CI && process.env.NODE_ENV !== "test") {
|
|
221
318
|
return [];
|
|
@@ -295,8 +392,20 @@ const getMCPTools = memoize(async () => {
|
|
|
295
392
|
ListToolsResultSchema,
|
|
296
393
|
"tools"
|
|
297
394
|
);
|
|
298
|
-
return toolsList.flatMap(
|
|
299
|
-
|
|
395
|
+
return toolsList.flatMap(({ client, result: { tools } }) => {
|
|
396
|
+
const validTools = tools.filter(
|
|
397
|
+
(tool) => {
|
|
398
|
+
if (!tool || typeof tool.name !== "string" || tool.name.length === 0) {
|
|
399
|
+
logMCPError(
|
|
400
|
+
`Invalid MCP tool from ${client.name}: missing or invalid name`,
|
|
401
|
+
new Error("Tool validation failed")
|
|
402
|
+
);
|
|
403
|
+
return false;
|
|
404
|
+
}
|
|
405
|
+
return true;
|
|
406
|
+
}
|
|
407
|
+
);
|
|
408
|
+
return validTools.map(
|
|
300
409
|
(tool) => ({
|
|
301
410
|
...MCPTool,
|
|
302
411
|
name: "mcp__" + client.name + "__" + tool.name,
|
|
@@ -322,45 +431,107 @@ const getMCPTools = memoize(async () => {
|
|
|
322
431
|
return `${client.name}:${tool.name} (MCP)`;
|
|
323
432
|
}
|
|
324
433
|
})
|
|
325
|
-
)
|
|
326
|
-
);
|
|
434
|
+
);
|
|
435
|
+
});
|
|
327
436
|
});
|
|
437
|
+
async function withTimeout(promise, timeoutMs, operationName) {
|
|
438
|
+
let timeoutId;
|
|
439
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
440
|
+
timeoutId = setTimeout(() => {
|
|
441
|
+
reject(
|
|
442
|
+
new Error(
|
|
443
|
+
`MCP operation "${operationName}" timed out after ${timeoutMs}ms`
|
|
444
|
+
)
|
|
445
|
+
);
|
|
446
|
+
}, timeoutMs);
|
|
447
|
+
});
|
|
448
|
+
try {
|
|
449
|
+
const result = await Promise.race([promise, timeoutPromise]);
|
|
450
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
451
|
+
return result;
|
|
452
|
+
} catch (error) {
|
|
453
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
454
|
+
throw error;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
function isTimeoutError(error) {
|
|
458
|
+
if (error instanceof Error) {
|
|
459
|
+
return error.name === "TimeoutError" || error.message.includes("timed out") || error.message.includes("timeout");
|
|
460
|
+
}
|
|
461
|
+
if (error instanceof DOMException) {
|
|
462
|
+
return error.name === "TimeoutError";
|
|
463
|
+
}
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
const MCP_TOOL_TIMEOUT_MS = 12e4;
|
|
467
|
+
const MCP_TOOL_MAX_RETRIES = 2;
|
|
328
468
|
async function callMCPTool({
|
|
329
469
|
client: { client, name },
|
|
330
470
|
tool,
|
|
331
471
|
args
|
|
332
472
|
}) {
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
473
|
+
let lastError;
|
|
474
|
+
const maxRetries = MCP_TOOL_MAX_RETRIES;
|
|
475
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
476
|
+
try {
|
|
477
|
+
const callPromise = client.callTool(
|
|
478
|
+
{
|
|
479
|
+
name: tool,
|
|
480
|
+
arguments: args
|
|
481
|
+
},
|
|
482
|
+
CallToolResultSchema
|
|
483
|
+
);
|
|
484
|
+
const result = await withTimeout(
|
|
485
|
+
callPromise,
|
|
486
|
+
MCP_TOOL_TIMEOUT_MS,
|
|
487
|
+
`${name}:${tool}`
|
|
488
|
+
);
|
|
489
|
+
if ("isError" in result && result.isError) {
|
|
490
|
+
const errorMessage = `Error calling tool ${tool}: ${result.error}`;
|
|
491
|
+
logMCPError(name, errorMessage);
|
|
492
|
+
throw Error(errorMessage);
|
|
493
|
+
}
|
|
494
|
+
if ("toolResult" in result) {
|
|
495
|
+
return String(result.toolResult);
|
|
496
|
+
}
|
|
497
|
+
if ("content" in result && Array.isArray(result.content)) {
|
|
498
|
+
return result.content.map((item) => {
|
|
499
|
+
if (item.type === "image") {
|
|
500
|
+
return {
|
|
501
|
+
type: "image",
|
|
502
|
+
source: {
|
|
503
|
+
type: "base64",
|
|
504
|
+
data: String(item.data),
|
|
505
|
+
media_type: item.mimeType
|
|
506
|
+
}
|
|
507
|
+
};
|
|
357
508
|
}
|
|
358
|
-
|
|
509
|
+
return item;
|
|
510
|
+
});
|
|
359
511
|
}
|
|
360
|
-
|
|
361
|
-
})
|
|
512
|
+
throw Error(`Unexpected response format from tool ${tool}`);
|
|
513
|
+
} catch (error) {
|
|
514
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
515
|
+
if (isTimeoutError(error) && attempt < maxRetries) {
|
|
516
|
+
logMCPError(
|
|
517
|
+
name,
|
|
518
|
+
`Tool "${tool}" timed out (attempt ${attempt + 1}/${maxRetries + 1}), retrying...`
|
|
519
|
+
);
|
|
520
|
+
await new Promise(
|
|
521
|
+
(resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt))
|
|
522
|
+
);
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (isTimeoutError(error)) {
|
|
526
|
+
logMCPError(
|
|
527
|
+
name,
|
|
528
|
+
`Tool "${tool}" failed after ${maxRetries + 1} attempts due to timeout`
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
throw lastError;
|
|
532
|
+
}
|
|
362
533
|
}
|
|
363
|
-
throw Error(`
|
|
534
|
+
throw lastError || new Error(`MCP tool ${tool} failed with unknown error`);
|
|
364
535
|
}
|
|
365
536
|
const getMCPCommands = memoize(async () => {
|
|
366
537
|
const results = await requestAll(
|
|
@@ -434,6 +605,10 @@ function refreshMCPConnections() {
|
|
|
434
605
|
if (typeof getMCPCommands.cache?.clear === "function") {
|
|
435
606
|
getMCPCommands.cache.clear();
|
|
436
607
|
}
|
|
608
|
+
import("../tools.js").then(({ invalidateToolsCache }) => {
|
|
609
|
+
invalidateToolsCache();
|
|
610
|
+
}).catch(() => {
|
|
611
|
+
});
|
|
437
612
|
}
|
|
438
613
|
async function shutdownMCPClients() {
|
|
439
614
|
if (connectedClients.length === 0) {
|
|
@@ -458,19 +633,83 @@ async function shutdownMCPClients() {
|
|
|
458
633
|
connectedClients = [];
|
|
459
634
|
refreshMCPConnections();
|
|
460
635
|
}
|
|
636
|
+
async function listMCPResources(serverFilter) {
|
|
637
|
+
const results = await requestAll(
|
|
638
|
+
{
|
|
639
|
+
method: "resources/list"
|
|
640
|
+
},
|
|
641
|
+
ListResourcesResultSchema,
|
|
642
|
+
"resources"
|
|
643
|
+
);
|
|
644
|
+
return results.filter(({ client }) => !serverFilter || client.name === serverFilter).flatMap(
|
|
645
|
+
({ client, result }) => (result.resources || []).map((resource) => ({
|
|
646
|
+
uri: resource.uri,
|
|
647
|
+
name: resource.name,
|
|
648
|
+
description: resource.description,
|
|
649
|
+
mimeType: resource.mimeType,
|
|
650
|
+
serverName: client.name
|
|
651
|
+
}))
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
async function readMCPResource(uri, serverName) {
|
|
655
|
+
const clients = await getClients();
|
|
656
|
+
const targetClients = serverName ? clients.filter(
|
|
657
|
+
(c) => c.type === "connected" && c.name === serverName
|
|
658
|
+
) : clients.filter((c) => c.type === "connected");
|
|
659
|
+
for (const client of targetClients) {
|
|
660
|
+
try {
|
|
661
|
+
const capabilities = await client.client.getServerCapabilities();
|
|
662
|
+
if (!capabilities?.resources) {
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
const result = await client.client.request(
|
|
666
|
+
{
|
|
667
|
+
method: "resources/read",
|
|
668
|
+
params: { uri }
|
|
669
|
+
},
|
|
670
|
+
ReadResourceResultSchema
|
|
671
|
+
);
|
|
672
|
+
if (result.contents && result.contents.length > 0) {
|
|
673
|
+
const content = result.contents[0];
|
|
674
|
+
return {
|
|
675
|
+
uri: content.uri,
|
|
676
|
+
mimeType: content.mimeType,
|
|
677
|
+
text: "text" in content ? String(content.text) : void 0,
|
|
678
|
+
blob: "blob" in content ? String(content.blob) : void 0
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
} catch (error) {
|
|
682
|
+
logMCPError(
|
|
683
|
+
client.name,
|
|
684
|
+
`Failed to read resource '${uri}': ${error instanceof Error ? error.message : String(error)}`
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
461
690
|
export {
|
|
462
691
|
addMcpServer,
|
|
692
|
+
configureMcpPool,
|
|
463
693
|
ensureConfigScope,
|
|
464
694
|
getClients,
|
|
695
|
+
getConnectionHealth,
|
|
465
696
|
getMCPCommands,
|
|
466
697
|
getMCPTools,
|
|
698
|
+
getMcpPoolConfig,
|
|
467
699
|
getMcpServer,
|
|
468
700
|
getMcprcServerStatus,
|
|
701
|
+
getPoolStats,
|
|
702
|
+
getServerHealth,
|
|
703
|
+
listMCPResources,
|
|
469
704
|
listMCPServers,
|
|
470
705
|
parseEnvVars,
|
|
706
|
+
readMCPResource,
|
|
471
707
|
refreshMCPConnections,
|
|
472
708
|
removeMcpServer,
|
|
473
709
|
runCommand,
|
|
474
|
-
|
|
710
|
+
runHealthCheck,
|
|
711
|
+
shutdownMCPClients,
|
|
712
|
+
startHealthCheck,
|
|
713
|
+
stopHealthCheck
|
|
475
714
|
};
|
|
476
715
|
//# sourceMappingURL=mcpClient.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/mcpClient.ts"],
|
|
4
|
-
"sourcesContent": ["import { zipObject } from 'lodash-es'\nimport {\n getCurrentProjectConfig,\n McpServerConfig,\n saveCurrentProjectConfig,\n getGlobalConfig,\n saveGlobalConfig,\n getMcprcConfig,\n addMcprcServerForTesting,\n removeMcprcServerForTesting,\n} from '@utils/config'\nimport { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\nimport { getCwd } from '@utils/state'\nimport { safeParseJSON } from '@utils/json'\nimport {\n ImageBlockParam,\n MessageParam,\n ToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/index.mjs'\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'\nimport {\n CallToolResultSchema,\n ClientRequest,\n ListPromptsResult,\n ListPromptsResultSchema,\n ListToolsResult,\n ListToolsResultSchema,\n Result,\n ResultSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { memoize, pickBy } from 'lodash-es'\nimport type { Tool } from '@tool'\nimport { MCPTool } from '@tools/MCPTool/MCPTool'\nimport { logMCPError } from '@utils/log'\nimport { Command } from '@commands'\nimport { PRODUCT_COMMAND } from '@constants/product'\n\ntype McpName = string\n\nexport function parseEnvVars(\n rawEnvArgs: string[] | undefined,\n): Record<string, string> {\n const parsedEnv: Record<string, string> = {}\n\n // Parse individual env vars\n if (rawEnvArgs) {\n for (const envStr of rawEnvArgs) {\n const [key, ...valueParts] = envStr.split('=')\n if (!key || valueParts.length === 0) {\n throw new Error(\n `Invalid environment variable format: ${envStr}, environment variables should be added as: -e KEY1=value1 -e KEY2=value2`,\n )\n }\n parsedEnv[key] = valueParts.join('=')\n }\n }\n return parsedEnv\n}\n\nconst VALID_SCOPES = ['project', 'global', 'mcprc'] as const\ntype ConfigScope = (typeof VALID_SCOPES)[number]\nconst EXTERNAL_SCOPES = ['project', 'global'] as ConfigScope[]\n\nexport function ensureConfigScope(scope?: string): ConfigScope {\n if (!scope) return 'project'\n\n const scopesToCheck =\n process.env.USER_TYPE === 'external' ? EXTERNAL_SCOPES : VALID_SCOPES\n\n if (!scopesToCheck.includes(scope as ConfigScope)) {\n throw new Error(\n `Invalid scope: ${scope}. Must be one of: ${scopesToCheck.join(', ')}`,\n )\n }\n\n return scope as ConfigScope\n}\n\nexport function addMcpServer(\n name: McpName,\n server: McpServerConfig,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n addMcprcServerForTesting(name, server)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n let mcprcConfig: Record<string, McpServerConfig> = {}\n\n // Read existing config if present\n if (existsSync(mcprcPath)) {\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const existingConfig = safeParseJSON(mcprcContent)\n if (existingConfig && typeof existingConfig === 'object') {\n mcprcConfig = existingConfig as Record<string, McpServerConfig>\n }\n } catch {\n // If we can't read/parse, start with empty config\n }\n }\n\n // Add the server\n mcprcConfig[name] = server\n\n // Write back to .mcprc\n try {\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n throw new Error(`Failed to write to .mcprc: ${error}`)\n }\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function removeMcpServer(\n name: McpName,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n removeMcprcServerForTesting(name)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n if (!existsSync(mcprcPath)) {\n throw new Error('No .mcprc file found in this directory')\n }\n\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const mcprcConfig = safeParseJSON(mcprcContent) as Record<\n string,\n McpServerConfig\n > | null\n\n if (\n !mcprcConfig ||\n typeof mcprcConfig !== 'object' ||\n !mcprcConfig[name]\n ) {\n throw new Error(`No MCP server found with name: ${name} in .mcprc`)\n }\n\n delete mcprcConfig[name]\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n if (error instanceof Error) {\n throw error\n }\n throw new Error(`Failed to remove from .mcprc: ${error}`)\n }\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No global MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No local MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function listMCPServers(): Record<string, McpServerConfig> {\n const globalConfig = getGlobalConfig()\n const mcprcConfig = getMcprcConfig()\n const projectConfig = getCurrentProjectConfig()\n return {\n ...(globalConfig.mcpServers ?? {}),\n ...(mcprcConfig ?? {}), // mcprc configs override global ones\n ...(projectConfig.mcpServers ?? {}), // Project configs override mcprc ones\n }\n}\n\nexport type ScopedMcpServerConfig = McpServerConfig & {\n scope: ConfigScope\n}\n\nexport function getMcpServer(name: McpName): ScopedMcpServerConfig | undefined {\n const projectConfig = getCurrentProjectConfig()\n const mcprcConfig = getMcprcConfig()\n const globalConfig = getGlobalConfig()\n\n // Check each scope in order of precedence\n if (projectConfig.mcpServers?.[name]) {\n return { ...projectConfig.mcpServers[name], scope: 'project' }\n }\n\n if (mcprcConfig?.[name]) {\n return { ...mcprcConfig[name], scope: 'mcprc' }\n }\n\n if (globalConfig.mcpServers?.[name]) {\n return { ...globalConfig.mcpServers[name], scope: 'global' }\n }\n\n return undefined\n}\n\nasync function connectToServer(\n name: string,\n serverRef: McpServerConfig,\n): Promise<Client> {\n const transport =\n serverRef.type === 'sse'\n ? new SSEClientTransport(new URL(serverRef.url))\n : new StdioClientTransport({\n command: serverRef.command,\n args: serverRef.args,\n env: {\n ...process.env,\n ...serverRef.env,\n } as Record<string, string>,\n stderr: 'pipe', // prevents error output from the MCP server from printing to the UI\n })\n\n const client = new Client(\n {\n name: PRODUCT_COMMAND,\n version: '0.1.0',\n },\n {\n capabilities: {},\n },\n )\n\n // Add a timeout to connection attempts to prevent tests from hanging indefinitely\n const CONNECTION_TIMEOUT_MS = 5000\n const connectPromise = client.connect(transport)\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutId = setTimeout(() => {\n reject(\n new Error(\n `Connection to MCP server \"${name}\" timed out after ${CONNECTION_TIMEOUT_MS}ms`,\n ),\n )\n }, CONNECTION_TIMEOUT_MS)\n\n // Clean up timeout if connect resolves or rejects\n connectPromise.then(\n () => clearTimeout(timeoutId),\n () => clearTimeout(timeoutId),\n )\n })\n\n await Promise.race([connectPromise, timeoutPromise])\n\n if (serverRef.type === 'stdio') {\n ;(transport as StdioClientTransport).stderr?.on('data', (data: Buffer) => {\n const errorText = data.toString().trim()\n if (errorText) {\n logMCPError(name, `Server stderr: ${errorText}`)\n }\n })\n }\n return client\n}\n\ntype ConnectedClient = {\n client: Client\n name: string\n type: 'connected'\n}\ntype FailedClient = {\n name: string\n type: 'failed'\n}\nexport type WrappedClient = ConnectedClient | FailedClient\n\nexport function getMcprcServerStatus(\n serverName: string,\n): 'approved' | 'rejected' | 'pending' {\n const config = getCurrentProjectConfig()\n if (config.approvedMcprcServers?.includes(serverName)) {\n return 'approved'\n }\n if (config.rejectedMcprcServers?.includes(serverName)) {\n return 'rejected'\n }\n return 'pending'\n}\n\n// Store connected clients for cleanup on shutdown\nlet connectedClients: WrappedClient[] = []\n\nexport const getClients = memoize(async (): Promise<WrappedClient[]> => {\n // TODO: This is a temporary fix for a hang during npm run verify in CI.\n // We need to investigate why MCP client connections hang in CI verify but not in CI tests.\n if (process.env.CI && process.env.NODE_ENV !== 'test') {\n return []\n }\n\n const globalServers = getGlobalConfig().mcpServers ?? {}\n const mcprcServers = getMcprcConfig()\n const projectServers = getCurrentProjectConfig().mcpServers ?? {}\n\n // Filter mcprc servers to only include approved ones\n const approvedMcprcServers = pickBy(\n mcprcServers,\n (_, name) => getMcprcServerStatus(name) === 'approved',\n )\n\n const allServers = {\n ...globalServers,\n ...approvedMcprcServers, // Approved .mcprc servers override global ones\n ...projectServers, // Project servers take highest precedence\n }\n\n // Filter out disabled servers\n const enabledServers = pickBy(\n allServers,\n server => server.enabled !== false, // Default to enabled if not specified\n )\n\n const clients = await Promise.all(\n Object.entries(enabledServers).map(async ([name, serverRef]) => {\n try {\n const client = await connectToServer(name, serverRef as McpServerConfig)\n return { name, client, type: 'connected' as const }\n } catch (error) {\n logMCPError(\n name,\n `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n return { name, type: 'failed' as const }\n }\n }),\n )\n\n // Store reference for shutdown cleanup\n connectedClients = clients\n return clients\n})\n\nasync function requestAll<\n ResultT extends Result,\n ResultSchemaT extends typeof ResultSchema,\n>(\n req: ClientRequest,\n resultSchema: ResultSchemaT,\n requiredCapability: string,\n): Promise<{ client: ConnectedClient; result: ResultT }[]> {\n const clients = await getClients()\n const results = await Promise.allSettled(\n clients.map(async client => {\n if (client.type === 'failed') return null\n\n try {\n const capabilities = await client.client.getServerCapabilities()\n if (!capabilities?.[requiredCapability]) {\n return null\n }\n return {\n client,\n result: (await client.client.request(req, resultSchema)) as ResultT,\n }\n } catch (error) {\n if (client.type === 'connected') {\n logMCPError(\n client.name,\n `Failed to request '${req.method}': ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n return null\n }\n }),\n )\n return results\n .filter(\n (\n result,\n ): result is PromiseFulfilledResult<{\n client: ConnectedClient\n result: ResultT\n } | null> => result.status === 'fulfilled',\n )\n .map(result => result.value)\n .filter(\n (result): result is { client: ConnectedClient; result: ResultT } =>\n result !== null,\n )\n}\n\nexport const getMCPTools = memoize(async (): Promise<Tool[]> => {\n const toolsList = await requestAll<\n ListToolsResult,\n typeof ListToolsResultSchema\n >(\n {\n method: 'tools/list',\n },\n ListToolsResultSchema,\n 'tools',\n )\n\n // TODO: Add zod schema validation\n return toolsList.flatMap(({ client, result: { tools } }) =>\n tools.map(\n (tool): Tool => ({\n ...MCPTool,\n name: 'mcp__' + client.name + '__' + tool.name,\n async description() {\n return tool.description ?? ''\n },\n async prompt() {\n return tool.description ?? ''\n },\n inputJSONSchema: tool.inputSchema as Tool['inputJSONSchema'],\n async validateInput(input, context) {\n // MCP tools handle their own validation through their schemas\n return { result: true }\n },\n async *call(args: Record<string, unknown>, context) {\n const data = await callMCPTool({ client, tool: tool.name, args })\n yield {\n type: 'result' as const,\n data,\n resultForAssistant: data,\n }\n },\n userFacingName() {\n return `${client.name}:${tool.name} (MCP)`\n },\n }),\n ),\n )\n})\n\nasync function callMCPTool({\n client: { client, name },\n tool,\n args,\n}: {\n client: ConnectedClient\n tool: string\n args: Record<string, unknown>\n}): Promise<ToolResultBlockParam['content']> {\n const result = await client.callTool(\n {\n name: tool,\n arguments: args,\n },\n CallToolResultSchema,\n )\n\n if ('isError' in result && result.isError) {\n const errorMessage = `Error calling tool ${tool}: ${result.error}`\n logMCPError(name, errorMessage)\n throw Error(errorMessage)\n }\n\n // Handle toolResult-type response\n if ('toolResult' in result) {\n return String(result.toolResult)\n }\n\n // Handle content array response\n if ('content' in result && Array.isArray(result.content)) {\n return result.content.map(item => {\n if (item.type === 'image') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: String(item.data),\n media_type: item.mimeType as ImageBlockParam.Source['media_type'],\n },\n }\n }\n return item\n })\n }\n\n throw Error(`Unexpected response format from tool ${tool}`)\n}\n\nexport const getMCPCommands = memoize(async (): Promise<Command[]> => {\n const results = await requestAll<\n ListPromptsResult,\n typeof ListPromptsResultSchema\n >(\n {\n method: 'prompts/list',\n },\n ListPromptsResultSchema,\n 'prompts',\n )\n\n return results.flatMap(({ client, result }) =>\n result.prompts?.map(_ => {\n const argNames = Object.values(_.arguments ?? {}).map(k => k.name)\n return {\n type: 'prompt',\n name: 'mcp__' + client.name + '__' + _.name,\n description: _.description ?? '',\n isEnabled: true,\n isHidden: false,\n progressMessage: 'running',\n userFacingName() {\n return `${client.name}:${_.name} (MCP)`\n },\n argNames,\n async getPromptForCommand(args: string) {\n const argsArray = args.split(' ')\n return await runCommand(\n { name: _.name, client },\n zipObject(argNames, argsArray),\n )\n },\n }\n }),\n )\n})\n\nexport async function runCommand(\n { name, client }: { name: string; client: ConnectedClient },\n args: Record<string, string>,\n): Promise<MessageParam[]> {\n try {\n const result = await client.client.getPrompt({ name, arguments: args })\n // TODO: Support type == resource\n return result.messages.map(\n (message): MessageParam => ({\n role: message.role,\n content: [\n message.content.type === 'text'\n ? {\n type: 'text',\n text: message.content.text,\n }\n : {\n type: 'image',\n source: {\n data: String(message.content.data),\n media_type: message.content\n .mimeType as ImageBlockParam.Source['media_type'],\n type: 'base64',\n },\n },\n ],\n }),\n )\n } catch (error) {\n logMCPError(\n client.name,\n `Error running command '${name}': ${error instanceof Error ? error.message : String(error)}`,\n )\n throw error\n }\n}\n\n/**\n * Refreshes MCP connections by clearing memoization cache and reconnecting\n * Useful when MCP configuration changes or servers become available after app startup\n */\nexport function refreshMCPConnections(): void {\n // Clear memoization caches\n if (typeof getClients.cache?.clear === 'function') {\n getClients.cache.clear()\n }\n if (typeof getMCPTools.cache?.clear === 'function') {\n getMCPTools.cache.clear()\n }\n if (typeof getMCPCommands.cache?.clear === 'function') {\n getMCPCommands.cache.clear()\n }\n}\n\n/**\n * Shuts down all MCP client connections gracefully\n * Should be called when the application is exiting\n */\nexport async function shutdownMCPClients(): Promise<void> {\n if (connectedClients.length === 0) {\n return\n }\n\n // Close all connected clients\n const closePromises = connectedClients.map(async wrappedClient => {\n if (wrappedClient.type === 'connected') {\n try {\n await wrappedClient.client.close()\n } catch {\n // Ignore errors during shutdown - the process is exiting anyway\n }\n }\n })\n\n // Wait for all clients to close with a timeout\n const SHUTDOWN_TIMEOUT_MS = 3000\n try {\n await Promise.race([\n Promise.allSettled(closePromises),\n new Promise(resolve => setTimeout(resolve, SHUTDOWN_TIMEOUT_MS)),\n ])\n } catch {\n // Ignore timeout errors during shutdown\n }\n\n // Clear references\n connectedClients = []\n refreshMCPConnections()\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAM9B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EAGA;AAAA,EAEA;AAAA,OAGK;AACP,SAAS,SAAS,cAAc;AAEhC,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAE5B,SAAS,uBAAuB;AAIzB,SAAS,aACd,YACwB;AACxB,QAAM,YAAoC,CAAC;AAG3C,MAAI,YAAY;AACd,eAAW,UAAU,YAAY;AAC/B,YAAM,CAAC,KAAK,GAAG,UAAU,IAAI,OAAO,MAAM,GAAG;AAC7C,UAAI,CAAC,OAAO,WAAW,WAAW,GAAG;AACnC,cAAM,IAAI;AAAA,UACR,wCAAwC,MAAM;AAAA,QAChD;AAAA,MACF;AACA,gBAAU,GAAG,IAAI,WAAW,KAAK,GAAG;AAAA,IACtC;AAAA,EACF;A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,MAChC,IAAI,QAAQ,aAAW,WAAW,SAAS,mBAAmB,CAAC;AAAA,IACjE,CAAC;AAAA,EACH,QAAQ;AAAA,EAER;AAGA,qBAAmB,CAAC;AACpB,wBAAsB;AACxB;",
|
|
4
|
+
"sourcesContent": ["import { zipObject } from 'lodash-es'\nimport {\n getCurrentProjectConfig,\n McpServerConfig,\n saveCurrentProjectConfig,\n getGlobalConfig,\n saveGlobalConfig,\n getMcprcConfig,\n addMcprcServerForTesting,\n removeMcprcServerForTesting,\n} from '@utils/config'\nimport { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\nimport { getCwd } from '@utils/state'\nimport { safeParseJSON } from '@utils/json'\nimport {\n ImageBlockParam,\n MessageParam,\n ToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/index.mjs'\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'\nimport {\n CallToolResultSchema,\n ClientRequest,\n ListPromptsResult,\n ListPromptsResultSchema,\n ListToolsResult,\n ListToolsResultSchema,\n ListResourcesResult,\n ListResourcesResultSchema,\n ReadResourceResult,\n ReadResourceResultSchema,\n Result,\n ResultSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { memoize, pickBy } from 'lodash-es'\nimport type { Tool } from '@tool'\nimport { MCPTool } from '@tools/MCPTool/MCPTool'\nimport { logMCPError } from '@utils/log'\nimport { Command } from '@commands'\nimport { PRODUCT_COMMAND } from '@constants/product'\n\ntype McpName = string\n\nexport function parseEnvVars(\n rawEnvArgs: string[] | undefined,\n): Record<string, string> {\n const parsedEnv: Record<string, string> = {}\n\n // Parse individual env vars\n if (rawEnvArgs) {\n for (const envStr of rawEnvArgs) {\n const [key, ...valueParts] = envStr.split('=')\n if (!key || valueParts.length === 0) {\n throw new Error(\n `Invalid environment variable format: ${envStr}, environment variables should be added as: -e KEY1=value1 -e KEY2=value2`,\n )\n }\n parsedEnv[key] = valueParts.join('=')\n }\n }\n return parsedEnv\n}\n\nconst VALID_SCOPES = ['project', 'global', 'mcprc'] as const\ntype ConfigScope = (typeof VALID_SCOPES)[number]\nconst EXTERNAL_SCOPES = ['project', 'global'] as ConfigScope[]\n\nexport function ensureConfigScope(scope?: string): ConfigScope {\n if (!scope) return 'project'\n\n const scopesToCheck =\n process.env.USER_TYPE === 'external' ? EXTERNAL_SCOPES : VALID_SCOPES\n\n if (!scopesToCheck.includes(scope as ConfigScope)) {\n throw new Error(\n `Invalid scope: ${scope}. Must be one of: ${scopesToCheck.join(', ')}`,\n )\n }\n\n return scope as ConfigScope\n}\n\nexport function addMcpServer(\n name: McpName,\n server: McpServerConfig,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n addMcprcServerForTesting(name, server)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n let mcprcConfig: Record<string, McpServerConfig> = {}\n\n // Read existing config if present\n if (existsSync(mcprcPath)) {\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const existingConfig = safeParseJSON(mcprcContent)\n if (existingConfig && typeof existingConfig === 'object') {\n mcprcConfig = existingConfig as Record<string, McpServerConfig>\n }\n } catch {\n // If we can't read/parse, start with empty config\n }\n }\n\n // Add the server\n mcprcConfig[name] = server\n\n // Write back to .mcprc\n try {\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n throw new Error(`Failed to write to .mcprc: ${error}`)\n }\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function removeMcpServer(\n name: McpName,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n removeMcprcServerForTesting(name)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n if (!existsSync(mcprcPath)) {\n throw new Error('No .mcprc file found in this directory')\n }\n\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const mcprcConfig = safeParseJSON(mcprcContent) as Record<\n string,\n McpServerConfig\n > | null\n\n if (\n !mcprcConfig ||\n typeof mcprcConfig !== 'object' ||\n !mcprcConfig[name]\n ) {\n throw new Error(`No MCP server found with name: ${name} in .mcprc`)\n }\n\n delete mcprcConfig[name]\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n if (error instanceof Error) {\n throw error\n }\n throw new Error(`Failed to remove from .mcprc: ${error}`)\n }\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No global MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No local MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function listMCPServers(): Record<string, McpServerConfig> {\n const globalConfig = getGlobalConfig()\n const mcprcConfig = getMcprcConfig()\n const projectConfig = getCurrentProjectConfig()\n return {\n ...(globalConfig.mcpServers ?? {}),\n ...(mcprcConfig ?? {}), // mcprc configs override global ones\n ...(projectConfig.mcpServers ?? {}), // Project configs override mcprc ones\n }\n}\n\nexport type ScopedMcpServerConfig = McpServerConfig & {\n scope: ConfigScope\n}\n\nexport function getMcpServer(name: McpName): ScopedMcpServerConfig | undefined {\n const projectConfig = getCurrentProjectConfig()\n const mcprcConfig = getMcprcConfig()\n const globalConfig = getGlobalConfig()\n\n // Check each scope in order of precedence\n if (projectConfig.mcpServers?.[name]) {\n return { ...projectConfig.mcpServers[name], scope: 'project' }\n }\n\n if (mcprcConfig?.[name]) {\n return { ...mcprcConfig[name], scope: 'mcprc' }\n }\n\n if (globalConfig.mcpServers?.[name]) {\n return { ...globalConfig.mcpServers[name], scope: 'global' }\n }\n\n return undefined\n}\n\nasync function connectToServer(\n name: string,\n serverRef: McpServerConfig,\n): Promise<Client> {\n const transport =\n serverRef.type === 'sse'\n ? new SSEClientTransport(new URL(serverRef.url))\n : new StdioClientTransport({\n command: serverRef.command,\n args: serverRef.args,\n env: {\n ...process.env,\n ...serverRef.env,\n } as Record<string, string>,\n stderr: 'pipe', // prevents error output from the MCP server from printing to the UI\n })\n\n const client = new Client(\n {\n name: PRODUCT_COMMAND,\n version: '0.1.0',\n },\n {\n capabilities: {},\n },\n )\n\n // Add a timeout to connection attempts to prevent tests from hanging indefinitely\n const CONNECTION_TIMEOUT_MS = 5000\n const connectPromise = client.connect(transport)\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutId = setTimeout(() => {\n reject(\n new Error(\n `Connection to MCP server \"${name}\" timed out after ${CONNECTION_TIMEOUT_MS}ms`,\n ),\n )\n }, CONNECTION_TIMEOUT_MS)\n\n // Clean up timeout if connect resolves or rejects\n connectPromise.then(\n () => clearTimeout(timeoutId),\n () => clearTimeout(timeoutId),\n )\n })\n\n await Promise.race([connectPromise, timeoutPromise])\n\n if (serverRef.type === 'stdio') {\n ;(transport as StdioClientTransport).stderr?.on('data', (data: Buffer) => {\n const errorText = data.toString().trim()\n if (errorText) {\n logMCPError(name, `Server stderr: ${errorText}`)\n }\n })\n }\n return client\n}\n\ntype ConnectedClient = {\n client: Client\n name: string\n type: 'connected'\n}\ntype FailedClient = {\n name: string\n type: 'failed'\n}\nexport type WrappedClient = ConnectedClient | FailedClient\n\nexport function getMcprcServerStatus(\n serverName: string,\n): 'approved' | 'rejected' | 'pending' {\n const config = getCurrentProjectConfig()\n if (config.approvedMcprcServers?.includes(serverName)) {\n return 'approved'\n }\n if (config.rejectedMcprcServers?.includes(serverName)) {\n return 'rejected'\n }\n return 'pending'\n}\n\n// Store connected clients for cleanup on shutdown\nlet connectedClients: WrappedClient[] = []\n\n// Connection pool configuration\nexport interface McpConnectionPoolConfig {\n /** Maximum concurrent connections (default: 10) */\n maxConnections: number\n /** Connection timeout in ms (default: 5000) */\n connectionTimeout: number\n /** Health check interval in ms (default: 30000, 0 to disable) */\n healthCheckInterval: number\n /** Retry failed connections (default: true) */\n retryFailed: boolean\n /** Max retry attempts (default: 3) */\n maxRetries: number\n}\n\nconst DEFAULT_POOL_CONFIG: McpConnectionPoolConfig = {\n maxConnections: 10,\n connectionTimeout: 5000,\n healthCheckInterval: 30000,\n retryFailed: true,\n maxRetries: 3,\n}\n\nlet poolConfig: McpConnectionPoolConfig = { ...DEFAULT_POOL_CONFIG }\nlet healthCheckTimer: ReturnType<typeof setInterval> | null = null\n\n/**\n * Configure MCP connection pool settings\n */\nexport function configureMcpPool(\n config: Partial<McpConnectionPoolConfig>,\n): void {\n poolConfig = { ...poolConfig, ...config }\n\n // Restart health check with new interval if changed\n if (config.healthCheckInterval !== undefined) {\n stopHealthCheck()\n if (poolConfig.healthCheckInterval > 0) {\n startHealthCheck()\n }\n }\n}\n\n/**\n * Get current pool configuration\n */\nexport function getMcpPoolConfig(): McpConnectionPoolConfig {\n return { ...poolConfig }\n}\n\n/**\n * Connection health status\n */\nexport interface McpConnectionHealth {\n name: string\n status: 'healthy' | 'unhealthy' | 'unknown'\n lastCheck: number\n latencyMs?: number\n error?: string\n}\n\n// Track connection health\nconst connectionHealth: Map<string, McpConnectionHealth> = new Map()\n\n/**\n * Check health of a single MCP connection\n */\nasync function checkConnectionHealth(\n client: ConnectedClient,\n): Promise<McpConnectionHealth> {\n const startTime = Date.now()\n try {\n // Try to get server capabilities as a health check\n await client.client.getServerCapabilities()\n const latencyMs = Date.now() - startTime\n\n return {\n name: client.name,\n status: 'healthy',\n lastCheck: Date.now(),\n latencyMs,\n }\n } catch (error) {\n return {\n name: client.name,\n status: 'unhealthy',\n lastCheck: Date.now(),\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\n/**\n * Run health check on all connections\n */\nexport async function runHealthCheck(): Promise<McpConnectionHealth[]> {\n const clients = await getClients()\n const healthResults: McpConnectionHealth[] = []\n\n for (const client of clients) {\n if (client.type === 'connected') {\n const health = await checkConnectionHealth(client)\n connectionHealth.set(client.name, health)\n healthResults.push(health)\n } else {\n const health: McpConnectionHealth = {\n name: client.name,\n status: 'unhealthy',\n lastCheck: Date.now(),\n error: 'Connection failed',\n }\n connectionHealth.set(client.name, health)\n healthResults.push(health)\n }\n }\n\n return healthResults\n}\n\n/**\n * Get cached health status for all connections\n */\nexport function getConnectionHealth(): McpConnectionHealth[] {\n return Array.from(connectionHealth.values())\n}\n\n/**\n * Get health status for a specific server\n */\nexport function getServerHealth(\n serverName: string,\n): McpConnectionHealth | null {\n return connectionHealth.get(serverName) || null\n}\n\n/**\n * Start periodic health checks\n */\nexport function startHealthCheck(): void {\n if (healthCheckTimer) return\n if (poolConfig.healthCheckInterval <= 0) return\n\n healthCheckTimer = setInterval(async () => {\n try {\n await runHealthCheck()\n } catch {\n // Silently ignore health check errors\n }\n }, poolConfig.healthCheckInterval)\n}\n\n/**\n * Stop periodic health checks\n */\nexport function stopHealthCheck(): void {\n if (healthCheckTimer) {\n clearInterval(healthCheckTimer)\n healthCheckTimer = null\n }\n}\n\n/**\n * Get connection pool statistics\n */\nexport function getPoolStats(): {\n totalConnections: number\n connectedCount: number\n failedCount: number\n healthyCount: number\n unhealthyCount: number\n} {\n const health = getConnectionHealth()\n return {\n totalConnections: connectedClients.length,\n connectedCount: connectedClients.filter(c => c.type === 'connected').length,\n failedCount: connectedClients.filter(c => c.type === 'failed').length,\n healthyCount: health.filter(h => h.status === 'healthy').length,\n unhealthyCount: health.filter(h => h.status === 'unhealthy').length,\n }\n}\n\nexport const getClients = memoize(async (): Promise<WrappedClient[]> => {\n // TODO: This is a temporary fix for a hang during npm run verify in CI.\n // We need to investigate why MCP client connections hang in CI verify but not in CI tests.\n if (process.env.CI && process.env.NODE_ENV !== 'test') {\n return []\n }\n\n const globalServers = getGlobalConfig().mcpServers ?? {}\n const mcprcServers = getMcprcConfig()\n const projectServers = getCurrentProjectConfig().mcpServers ?? {}\n\n // Filter mcprc servers to only include approved ones\n const approvedMcprcServers = pickBy(\n mcprcServers,\n (_, name) => getMcprcServerStatus(name) === 'approved',\n )\n\n const allServers = {\n ...globalServers,\n ...approvedMcprcServers, // Approved .mcprc servers override global ones\n ...projectServers, // Project servers take highest precedence\n }\n\n // Filter out disabled servers\n const enabledServers = pickBy(\n allServers,\n server => server.enabled !== false, // Default to enabled if not specified\n )\n\n const clients = await Promise.all(\n Object.entries(enabledServers).map(async ([name, serverRef]) => {\n try {\n const client = await connectToServer(name, serverRef as McpServerConfig)\n return { name, client, type: 'connected' as const }\n } catch (error) {\n logMCPError(\n name,\n `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n return { name, type: 'failed' as const }\n }\n }),\n )\n\n // Store reference for shutdown cleanup\n connectedClients = clients\n return clients\n})\n\nasync function requestAll<\n ResultT extends Result,\n ResultSchemaT extends typeof ResultSchema,\n>(\n req: ClientRequest,\n resultSchema: ResultSchemaT,\n requiredCapability: string,\n): Promise<{ client: ConnectedClient; result: ResultT }[]> {\n const clients = await getClients()\n const results = await Promise.allSettled(\n clients.map(async client => {\n if (client.type === 'failed') return null\n\n try {\n const capabilities = await client.client.getServerCapabilities()\n if (!capabilities?.[requiredCapability]) {\n return null\n }\n return {\n client,\n result: (await client.client.request(req, resultSchema)) as ResultT,\n }\n } catch (error) {\n if (client.type === 'connected') {\n logMCPError(\n client.name,\n `Failed to request '${req.method}': ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n return null\n }\n }),\n )\n return results\n .filter(\n (\n result,\n ): result is PromiseFulfilledResult<{\n client: ConnectedClient\n result: ResultT\n } | null> => result.status === 'fulfilled',\n )\n .map(result => result.value)\n .filter(\n (result): result is { client: ConnectedClient; result: ResultT } =>\n result !== null,\n )\n}\n\nexport const getMCPTools = memoize(async (): Promise<Tool[]> => {\n const toolsList = await requestAll<\n ListToolsResult,\n typeof ListToolsResultSchema\n >(\n {\n method: 'tools/list',\n },\n ListToolsResultSchema,\n 'tools',\n )\n\n return toolsList.flatMap(({ client, result: { tools } }) => {\n // Validate tool structure before processing\n const validTools = tools.filter(\n (tool): tool is typeof tool & { name: string } => {\n if (!tool || typeof tool.name !== 'string' || tool.name.length === 0) {\n logMCPError(\n `Invalid MCP tool from ${client.name}: missing or invalid name`,\n new Error('Tool validation failed'),\n )\n return false\n }\n return true\n },\n )\n\n return validTools.map(\n (tool): Tool => ({\n ...MCPTool,\n name: 'mcp__' + client.name + '__' + tool.name,\n async description() {\n return tool.description ?? ''\n },\n async prompt() {\n return tool.description ?? ''\n },\n inputJSONSchema: tool.inputSchema as Tool['inputJSONSchema'],\n async validateInput(input, context) {\n // MCP tools handle their own validation through their schemas\n return { result: true }\n },\n async *call(args: Record<string, unknown>, context) {\n const data = await callMCPTool({ client, tool: tool.name, args })\n yield {\n type: 'result' as const,\n data,\n resultForAssistant: data,\n }\n },\n userFacingName() {\n return `${client.name}:${tool.name} (MCP)`\n },\n }),\n )\n })\n})\n\n/**\n * Wraps a promise with a timeout.\n * If the promise doesn't resolve/reject within the timeout, rejects with a TimeoutError.\n */\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n operationName: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(\n new Error(\n `MCP operation \"${operationName}\" timed out after ${timeoutMs}ms`,\n ),\n )\n }, timeoutMs)\n })\n\n try {\n const result = await Promise.race([promise, timeoutPromise])\n if (timeoutId) clearTimeout(timeoutId)\n return result\n } catch (error) {\n if (timeoutId) clearTimeout(timeoutId)\n throw error\n }\n}\n\n/**\n * Checks if an error is a timeout-related error.\n */\nfunction isTimeoutError(error: unknown): boolean {\n if (error instanceof Error) {\n return (\n error.name === 'TimeoutError' ||\n error.message.includes('timed out') ||\n error.message.includes('timeout')\n )\n }\n if (error instanceof DOMException) {\n return error.name === 'TimeoutError'\n }\n return false\n}\n\n// Import timing constants - use dynamic value or fallback\nconst MCP_TOOL_TIMEOUT_MS = 120000 // 2 minutes\nconst MCP_TOOL_MAX_RETRIES = 2\n\nasync function callMCPTool({\n client: { client, name },\n tool,\n args,\n}: {\n client: ConnectedClient\n tool: string\n args: Record<string, unknown>\n}): Promise<ToolResultBlockParam['content']> {\n let lastError: Error | undefined\n const maxRetries = MCP_TOOL_MAX_RETRIES\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const callPromise = client.callTool(\n {\n name: tool,\n arguments: args,\n },\n CallToolResultSchema,\n )\n\n // Wrap with timeout protection\n const result = await withTimeout(\n callPromise,\n MCP_TOOL_TIMEOUT_MS,\n `${name}:${tool}`,\n )\n\n if ('isError' in result && result.isError) {\n const errorMessage = `Error calling tool ${tool}: ${result.error}`\n logMCPError(name, errorMessage)\n throw Error(errorMessage)\n }\n\n // Handle toolResult-type response\n if ('toolResult' in result) {\n return String(result.toolResult)\n }\n\n // Handle content array response\n if ('content' in result && Array.isArray(result.content)) {\n return result.content.map(item => {\n if (item.type === 'image') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: String(item.data),\n media_type:\n item.mimeType as ImageBlockParam.Source['media_type'],\n },\n }\n }\n return item\n })\n }\n\n throw Error(`Unexpected response format from tool ${tool}`)\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error))\n\n // Only retry on timeout errors, not on other errors\n if (isTimeoutError(error) && attempt < maxRetries) {\n logMCPError(\n name,\n `Tool \"${tool}\" timed out (attempt ${attempt + 1}/${maxRetries + 1}), retrying...`,\n )\n // Exponential backoff: 1s, 2s, 4s...\n await new Promise(resolve =>\n setTimeout(resolve, 1000 * Math.pow(2, attempt)),\n )\n continue\n }\n\n // Log and throw for non-retryable errors or after all retries exhausted\n if (isTimeoutError(error)) {\n logMCPError(\n name,\n `Tool \"${tool}\" failed after ${maxRetries + 1} attempts due to timeout`,\n )\n }\n throw lastError\n }\n }\n\n // This should never be reached, but TypeScript needs it\n throw lastError || new Error(`MCP tool ${tool} failed with unknown error`)\n}\n\nexport const getMCPCommands = memoize(async (): Promise<Command[]> => {\n const results = await requestAll<\n ListPromptsResult,\n typeof ListPromptsResultSchema\n >(\n {\n method: 'prompts/list',\n },\n ListPromptsResultSchema,\n 'prompts',\n )\n\n return results.flatMap(({ client, result }) =>\n result.prompts?.map(_ => {\n const argNames = Object.values(_.arguments ?? {}).map(k => k.name)\n return {\n type: 'prompt',\n name: 'mcp__' + client.name + '__' + _.name,\n description: _.description ?? '',\n isEnabled: true,\n isHidden: false,\n progressMessage: 'running',\n userFacingName() {\n return `${client.name}:${_.name} (MCP)`\n },\n argNames,\n async getPromptForCommand(args: string) {\n const argsArray = args.split(' ')\n return await runCommand(\n { name: _.name, client },\n zipObject(argNames, argsArray),\n )\n },\n }\n }),\n )\n})\n\nexport async function runCommand(\n { name, client }: { name: string; client: ConnectedClient },\n args: Record<string, string>,\n): Promise<MessageParam[]> {\n try {\n const result = await client.client.getPrompt({ name, arguments: args })\n // TODO: Support type == resource\n return result.messages.map(\n (message): MessageParam => ({\n role: message.role,\n content: [\n message.content.type === 'text'\n ? {\n type: 'text',\n text: message.content.text,\n }\n : {\n type: 'image',\n source: {\n data: String(message.content.data),\n media_type: message.content\n .mimeType as ImageBlockParam.Source['media_type'],\n type: 'base64',\n },\n },\n ],\n }),\n )\n } catch (error) {\n logMCPError(\n client.name,\n `Error running command '${name}': ${error instanceof Error ? error.message : String(error)}`,\n )\n throw error\n }\n}\n\n/**\n * Refreshes MCP connections by clearing memoization cache and reconnecting\n * Useful when MCP configuration changes or servers become available after app startup\n */\nexport function refreshMCPConnections(): void {\n // Clear memoization caches\n if (typeof getClients.cache?.clear === 'function') {\n getClients.cache.clear()\n }\n if (typeof getMCPTools.cache?.clear === 'function') {\n getMCPTools.cache.clear()\n }\n if (typeof getMCPCommands.cache?.clear === 'function') {\n getMCPCommands.cache.clear()\n }\n\n // Also invalidate the main tools cache since MCP tools are part of it\n // This is imported lazily to avoid circular dependencies\n import('../tools')\n .then(({ invalidateToolsCache }) => {\n invalidateToolsCache()\n })\n .catch(() => {\n // Ignore errors - tools.ts may not be loaded yet\n })\n}\n\n/**\n * Shuts down all MCP client connections gracefully\n * Should be called when the application is exiting\n */\nexport async function shutdownMCPClients(): Promise<void> {\n if (connectedClients.length === 0) {\n return\n }\n\n // Close all connected clients\n const closePromises = connectedClients.map(async wrappedClient => {\n if (wrappedClient.type === 'connected') {\n try {\n await wrappedClient.client.close()\n } catch {\n // Ignore errors during shutdown - the process is exiting anyway\n }\n }\n })\n\n // Wait for all clients to close with a timeout\n const SHUTDOWN_TIMEOUT_MS = 3000\n try {\n await Promise.race([\n Promise.allSettled(closePromises),\n new Promise(resolve => setTimeout(resolve, SHUTDOWN_TIMEOUT_MS)),\n ])\n } catch {\n // Ignore timeout errors during shutdown\n }\n\n // Clear references\n connectedClients = []\n refreshMCPConnections()\n}\n\n/**\n * MCP Resource type for listing\n */\nexport type McpResource = {\n uri: string\n name: string\n description?: string\n mimeType?: string\n serverName: string\n}\n\n/**\n * List all resources from MCP servers\n * @param serverFilter Optional server name to filter resources from a specific server\n */\nexport async function listMCPResources(\n serverFilter?: string,\n): Promise<McpResource[]> {\n const results = await requestAll<\n ListResourcesResult,\n typeof ListResourcesResultSchema\n >(\n {\n method: 'resources/list',\n },\n ListResourcesResultSchema,\n 'resources',\n )\n\n return results\n .filter(({ client }) => !serverFilter || client.name === serverFilter)\n .flatMap(({ client, result }) =>\n (result.resources || []).map(resource => ({\n uri: resource.uri,\n name: resource.name,\n description: resource.description,\n mimeType: resource.mimeType,\n serverName: client.name,\n })),\n )\n}\n\n/**\n * MCP Resource content type\n */\nexport type McpResourceContent = {\n uri: string\n mimeType?: string\n text?: string\n blob?: string // Base64 encoded binary data\n}\n\n/**\n * Read a specific resource from an MCP server\n * @param uri The resource URI to read\n * @param serverName Optional server name to target a specific server\n */\nexport async function readMCPResource(\n uri: string,\n serverName?: string,\n): Promise<McpResourceContent | null> {\n const clients = await getClients()\n\n // Find the appropriate client\n const targetClients = serverName\n ? (clients.filter(\n c => c.type === 'connected' && c.name === serverName,\n ) as ConnectedClient[])\n : (clients.filter(c => c.type === 'connected') as ConnectedClient[])\n\n for (const client of targetClients) {\n try {\n // Check if this server has resources capability\n const capabilities = await client.client.getServerCapabilities()\n if (!capabilities?.resources) {\n continue\n }\n\n // Try to read the resource\n const result = (await client.client.request(\n {\n method: 'resources/read',\n params: { uri },\n },\n ReadResourceResultSchema,\n )) as ReadResourceResult\n\n if (result.contents && result.contents.length > 0) {\n const content = result.contents[0]\n return {\n uri: content.uri,\n mimeType: content.mimeType,\n text: 'text' in content ? String(content.text) : undefined,\n blob: 'blob' in content ? String(content.blob) : undefined,\n }\n }\n } catch (error) {\n // Log but continue trying other servers\n logMCPError(\n client.name,\n `Failed to read resource '${uri}': ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n return null\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAM9B,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EAGA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OAGK;AACP,SAAS,SAAS,cAAc;AAEhC,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAE5B,SAAS,uBAAuB;AAIzB,SAAS,aACd,YACwB;AACxB,QAAM,YAAoC,CAAC;AAG3C,MAAI,YAAY;AACd,eAAW,UAA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