@within-7/minto 0.1.7 → 0.3.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 +73 -49
- 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 +85 -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 +157 -0
- package/dist/commands/export.js.map +7 -0
- package/dist/commands/mcp-interactive.js +28 -18
- package/dist/commands/mcp-interactive.js.map +2 -2
- package/dist/commands/model.js +9 -7
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/permissions.js +87 -0
- package/dist/commands/permissions.js.map +7 -0
- package/dist/commands/plugin/AddMarketplaceForm.js +3 -2
- package/dist/commands/plugin/AddMarketplaceForm.js.map +2 -2
- package/dist/commands/plugin/ConfirmDialog.js +2 -1
- package/dist/commands/plugin/ConfirmDialog.js.map +2 -2
- package/dist/commands/plugin/ErrorView.js +2 -1
- package/dist/commands/plugin/ErrorView.js.map +2 -2
- package/dist/commands/plugin/InstalledPluginsByMarketplace.js +5 -4
- package/dist/commands/plugin/InstalledPluginsByMarketplace.js.map +2 -2
- package/dist/commands/plugin/InstalledPluginsManager.js +5 -4
- package/dist/commands/plugin/InstalledPluginsManager.js.map +2 -2
- package/dist/commands/plugin/MainMenu.js +2 -1
- package/dist/commands/plugin/MainMenu.js.map +2 -2
- package/dist/commands/plugin/MarketplaceManager.js +5 -4
- package/dist/commands/plugin/MarketplaceManager.js.map +2 -2
- package/dist/commands/plugin/MarketplaceSelector.js +4 -3
- package/dist/commands/plugin/MarketplaceSelector.js.map +2 -2
- package/dist/commands/plugin/PlaceholderScreen.js +3 -2
- package/dist/commands/plugin/PlaceholderScreen.js.map +2 -2
- package/dist/commands/plugin/PluginBrowser.js +6 -5
- package/dist/commands/plugin/PluginBrowser.js.map +2 -2
- package/dist/commands/plugin/PluginDetailsInstall.js +5 -4
- package/dist/commands/plugin/PluginDetailsInstall.js.map +2 -2
- package/dist/commands/plugin/PluginDetailsManage.js +4 -3
- package/dist/commands/plugin/PluginDetailsManage.js.map +2 -2
- package/dist/commands/plugin.js +16 -15
- package/dist/commands/plugin.js.map +2 -2
- package/dist/commands/quit.js +3 -1
- package/dist/commands/quit.js.map +2 -2
- package/dist/commands/sandbox.js +105 -0
- package/dist/commands/sandbox.js.map +7 -0
- package/dist/commands/setup.js +2 -1
- package/dist/commands/setup.js.map +2 -2
- package/dist/commands/status.js +59 -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/undo.js +245 -0
- package/dist/commands/undo.js.map +7 -0
- package/dist/commands.js +22 -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/AsciiLogo.js +7 -8
- package/dist/components/AsciiLogo.js.map +2 -2
- package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js +3 -2
- package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js.map +2 -2
- package/dist/components/AskUserQuestionDialog/QuestionView.js +2 -1
- package/dist/components/AskUserQuestionDialog/QuestionView.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 +15 -0
- package/dist/components/CollapsibleHint.js.map +7 -0
- package/dist/components/Config.js +3 -2
- package/dist/components/Config.js.map +2 -2
- package/dist/components/ConsoleOAuthFlow.js +2 -1
- package/dist/components/ConsoleOAuthFlow.js.map +2 -2
- package/dist/components/Cost.js +2 -1
- package/dist/components/Cost.js.map +2 -2
- package/dist/components/FileEditToolUpdatedMessage.js +1 -1
- package/dist/components/FileEditToolUpdatedMessage.js.map +2 -2
- package/dist/components/HeaderBar.js +13 -8
- package/dist/components/HeaderBar.js.map +2 -2
- package/dist/components/HistorySearchOverlay.js +4 -3
- package/dist/components/HistorySearchOverlay.js.map +2 -2
- package/dist/components/HotkeyHelpPanel.js +134 -0
- package/dist/components/HotkeyHelpPanel.js.map +7 -0
- package/dist/components/InvalidConfigDialog.js +2 -1
- package/dist/components/InvalidConfigDialog.js.map +2 -2
- package/dist/components/Logo.js +24 -68
- package/dist/components/Logo.js.map +2 -2
- package/dist/components/MCPServerApprovalDialog.js +2 -1
- package/dist/components/MCPServerApprovalDialog.js.map +2 -2
- package/dist/components/MCPServerDialogCopy.js +2 -1
- package/dist/components/MCPServerDialogCopy.js.map +2 -2
- package/dist/components/MCPServerMultiselectDialog.js +2 -1
- package/dist/components/MCPServerMultiselectDialog.js.map +2 -2
- package/dist/components/Message.js +23 -7
- package/dist/components/Message.js.map +3 -3
- package/dist/components/MessageSelector.js +4 -3
- package/dist/components/MessageSelector.js.map +2 -2
- package/dist/components/ModeIndicator.js +2 -1
- package/dist/components/ModeIndicator.js.map +2 -2
- package/dist/components/ModelConfig.js +20 -6
- package/dist/components/ModelConfig.js.map +2 -2
- package/dist/components/ModelListManager.js +7 -6
- package/dist/components/ModelListManager.js.map +2 -2
- package/dist/components/ModelSelector/ModelSelector.js +27 -14
- package/dist/components/ModelSelector/ModelSelector.js.map +2 -2
- package/dist/components/Onboarding.js +22 -16
- package/dist/components/Onboarding.js.map +2 -2
- package/dist/components/OperationSummary.js +130 -0
- package/dist/components/OperationSummary.js.map +7 -0
- package/dist/components/ProgressBar.js +74 -0
- package/dist/components/ProgressBar.js.map +7 -0
- package/dist/components/PromptInput.js +210 -87
- 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/SensitiveFileWarning.js +31 -0
- package/dist/components/SensitiveFileWarning.js.map +7 -0
- package/dist/components/Spinner.js +141 -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/StructuredDiff.js +6 -8
- package/dist/components/StructuredDiff.js.map +2 -2
- package/dist/components/SubagentBlock.js +5 -3
- package/dist/components/SubagentBlock.js.map +2 -2
- package/dist/components/SubagentProgress.js +17 -15
- package/dist/components/SubagentProgress.js.map +2 -2
- package/dist/components/TaskCard.js +30 -24
- package/dist/components/TaskCard.js.map +2 -2
- package/dist/components/TextInput.js +9 -1
- package/dist/components/TextInput.js.map +2 -2
- package/dist/components/TodoChangeBlock.js +1 -1
- package/dist/components/TodoChangeBlock.js.map +2 -2
- package/dist/components/TodoPanel.js +140 -31
- 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/ToolUseLoader.js +2 -2
- package/dist/components/ToolUseLoader.js.map +2 -2
- package/dist/components/TreeConnector.js +26 -0
- package/dist/components/TreeConnector.js.map +7 -0
- package/dist/components/TrustDialog.js +2 -1
- package/dist/components/TrustDialog.js.map +2 -2
- package/dist/components/TurnCompletionIndicator.js +18 -0
- package/dist/components/TurnCompletionIndicator.js.map +7 -0
- package/dist/components/binary-feedback/BinaryFeedbackView.js +2 -1
- package/dist/components/binary-feedback/BinaryFeedbackView.js.map +2 -2
- package/dist/components/messages/AssistantTextMessage.js +20 -9
- 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 +17 -10
- package/dist/components/messages/AssistantToolUseMessage.js.map +2 -2
- package/dist/components/messages/GroupRenderer.js +54 -0
- package/dist/components/messages/GroupRenderer.js.map +7 -0
- package/dist/components/messages/NestedTasksPreview.js +24 -0
- package/dist/components/messages/NestedTasksPreview.js.map +7 -0
- package/dist/components/messages/ParallelTasksGroupView.js +93 -0
- package/dist/components/messages/ParallelTasksGroupView.js.map +7 -0
- package/dist/components/messages/TaskInModuleView.js +218 -0
- package/dist/components/messages/TaskInModuleView.js.map +7 -0
- package/dist/components/messages/TaskOutputContent.js +56 -0
- package/dist/components/messages/TaskOutputContent.js.map +7 -0
- package/dist/components/messages/UserPromptMessage.js +2 -2
- 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 +120 -54
- 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/constants/toolInputExamples.js +84 -0
- package/dist/constants/toolInputExamples.js.map +7 -0
- package/dist/core/backupManager.js +321 -0
- package/dist/core/backupManager.js.map +7 -0
- 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 +129 -0
- package/dist/core/costTracker.js.map +7 -0
- package/dist/core/gitAutoCommit.js +287 -0
- package/dist/core/gitAutoCommit.js.map +7 -0
- package/dist/core/index.js +8 -0
- package/dist/core/index.js.map +7 -0
- package/dist/core/operationTracker.js +212 -0
- package/dist/core/operationTracker.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 +296 -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 +173 -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 +345 -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/tokenStats.js +9 -0
- package/dist/core/tokenStats.js.map +7 -0
- package/dist/core/tokenStatsManager.js +331 -0
- package/dist/core/tokenStatsManager.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 +158 -130
- 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/useAgentTokenStats.js +72 -0
- package/dist/hooks/useAgentTokenStats.js.map +7 -0
- package/dist/hooks/useAgentTranscripts.js +140 -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/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 +29 -2
- 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 +348 -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 +348 -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/permissions.js +28 -1
- package/dist/permissions.js.map +2 -2
- package/dist/query.js +253 -21
- package/dist/query.js.map +3 -3
- package/dist/screens/REPL.js +523 -194
- 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 +192 -14
- 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 +338 -43
- 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 +341 -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 +6 -2
- package/dist/tools/AskExpertModelTool/AskExpertModelTool.js.map +2 -2
- package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js +2 -1
- 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 +79 -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 +336 -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/FileEditTool/prompt.js +6 -3
- package/dist/tools/FileEditTool/prompt.js.map +2 -2
- package/dist/tools/FileWriteTool/FileWriteTool.js +5 -5
- package/dist/tools/FileWriteTool/FileWriteTool.js.map +2 -2
- package/dist/tools/FileWriteTool/prompt.js +4 -2
- package/dist/tools/FileWriteTool/prompt.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/MultiEditTool/prompt.js +5 -3
- package/dist/tools/MultiEditTool/prompt.js.map +2 -2
- package/dist/tools/NotebookEditTool/NotebookEditTool.js +7 -2
- package/dist/tools/NotebookEditTool/NotebookEditTool.js.map +2 -2
- package/dist/tools/NotebookReadTool/NotebookReadTool.js.map +2 -2
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js +75 -0
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js.map +7 -0
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js +109 -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 +10 -4
- package/dist/tools/SkillTool/SkillTool.js.map +2 -2
- package/dist/tools/SkillTool/prompt.js +1 -1
- package/dist/tools/SkillTool/prompt.js.map +1 -1
- 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 +190 -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 +310 -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/CircuitBreaker.js +242 -0
- package/dist/utils/CircuitBreaker.js.map +7 -0
- 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/ask.js +2 -0
- package/dist/utils/ask.js.map +2 -2
- 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 +108 -10
- 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/credentials/CredentialStore.js +1 -0
- package/dist/utils/credentials/CredentialStore.js.map +7 -0
- package/dist/utils/credentials/EncryptedFileStore.js +157 -0
- package/dist/utils/credentials/EncryptedFileStore.js.map +7 -0
- package/dist/utils/credentials/index.js +37 -0
- package/dist/utils/credentials/index.js.map +7 -0
- package/dist/utils/credentials/migration.js +82 -0
- package/dist/utils/credentials/migration.js.map +7 -0
- 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/markdown.js +13 -1
- package/dist/utils/markdown.js.map +2 -2
- 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 +162 -6
- 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/safePath.js +132 -0
- package/dist/utils/safePath.js.map +7 -0
- 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/sensitiveFiles.js +125 -0
- package/dist/utils/sensitiveFiles.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/theme.js +6 -6
- package/dist/utils/theme.js.map +1 -1
- package/dist/utils/todoStorage.js +92 -2
- package/dist/utils/todoStorage.js.map +2 -2
- package/dist/utils/toolRiskClassification.js +207 -0
- package/dist/utils/toolRiskClassification.js.map +7 -0
- package/dist/utils/toolTimeout.js +136 -0
- package/dist/utils/toolTimeout.js.map +7 -0
- package/dist/utils/tooling/safeRender.js +116 -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 +17 -5
- 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/hooks/useCancelRequest.js +0 -28
- package/dist/hooks/useCancelRequest.js.map +0 -7
- package/dist/screens/Doctor.js +0 -22
- package/dist/screens/Doctor.js.map +0 -7
|
@@ -18,12 +18,21 @@ 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";
|
|
25
27
|
import { logMCPError } from "../utils/log.js";
|
|
26
28
|
import { PRODUCT_COMMAND } from "../constants/product.js";
|
|
29
|
+
import { CircuitBreakerRegistry, CircuitOpenError } from "../utils/CircuitBreaker.js";
|
|
30
|
+
const mcpCircuitBreakers = new CircuitBreakerRegistry({
|
|
31
|
+
failureThreshold: 5,
|
|
32
|
+
successThreshold: 2,
|
|
33
|
+
openTimeout: 3e4
|
|
34
|
+
// 30 seconds before trying again
|
|
35
|
+
});
|
|
27
36
|
function parseEnvVars(rawEnvArgs) {
|
|
28
37
|
const parsedEnv = {};
|
|
29
38
|
if (rawEnvArgs) {
|
|
@@ -216,6 +225,126 @@ function getMcprcServerStatus(serverName) {
|
|
|
216
225
|
return "pending";
|
|
217
226
|
}
|
|
218
227
|
let connectedClients = [];
|
|
228
|
+
const DEFAULT_POOL_CONFIG = {
|
|
229
|
+
maxConnections: 10,
|
|
230
|
+
connectionTimeout: 5e3,
|
|
231
|
+
healthCheckInterval: 3e4,
|
|
232
|
+
retryFailed: true,
|
|
233
|
+
maxRetries: 3
|
|
234
|
+
};
|
|
235
|
+
let poolConfig = { ...DEFAULT_POOL_CONFIG };
|
|
236
|
+
let healthCheckTimer = null;
|
|
237
|
+
let connectionLock = null;
|
|
238
|
+
let pendingRefresh = false;
|
|
239
|
+
async function acquireConnectionLock() {
|
|
240
|
+
while (connectionLock) {
|
|
241
|
+
await connectionLock;
|
|
242
|
+
}
|
|
243
|
+
let release;
|
|
244
|
+
connectionLock = new Promise((resolve) => {
|
|
245
|
+
release = () => {
|
|
246
|
+
connectionLock = null;
|
|
247
|
+
resolve();
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
return release;
|
|
251
|
+
}
|
|
252
|
+
function configureMcpPool(config) {
|
|
253
|
+
poolConfig = { ...poolConfig, ...config };
|
|
254
|
+
if (config.healthCheckInterval !== void 0) {
|
|
255
|
+
stopHealthCheck();
|
|
256
|
+
if (poolConfig.healthCheckInterval > 0) {
|
|
257
|
+
startHealthCheck();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function getMcpPoolConfig() {
|
|
262
|
+
return { ...poolConfig };
|
|
263
|
+
}
|
|
264
|
+
const connectionHealth = /* @__PURE__ */ new Map();
|
|
265
|
+
async function checkConnectionHealth(client) {
|
|
266
|
+
const startTime = Date.now();
|
|
267
|
+
try {
|
|
268
|
+
await client.client.getServerCapabilities();
|
|
269
|
+
const latencyMs = Date.now() - startTime;
|
|
270
|
+
return {
|
|
271
|
+
name: client.name,
|
|
272
|
+
status: "healthy",
|
|
273
|
+
lastCheck: Date.now(),
|
|
274
|
+
latencyMs
|
|
275
|
+
};
|
|
276
|
+
} catch (error) {
|
|
277
|
+
return {
|
|
278
|
+
name: client.name,
|
|
279
|
+
status: "unhealthy",
|
|
280
|
+
lastCheck: Date.now(),
|
|
281
|
+
error: error instanceof Error ? error.message : String(error)
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
async function runHealthCheck() {
|
|
286
|
+
const clients = await getClients();
|
|
287
|
+
const healthResults = [];
|
|
288
|
+
for (const client of clients) {
|
|
289
|
+
if (client.type === "connected") {
|
|
290
|
+
const health = await checkConnectionHealth(client);
|
|
291
|
+
connectionHealth.set(client.name, health);
|
|
292
|
+
healthResults.push(health);
|
|
293
|
+
} else {
|
|
294
|
+
const health = {
|
|
295
|
+
name: client.name,
|
|
296
|
+
status: "unhealthy",
|
|
297
|
+
lastCheck: Date.now(),
|
|
298
|
+
error: "Connection failed"
|
|
299
|
+
};
|
|
300
|
+
connectionHealth.set(client.name, health);
|
|
301
|
+
healthResults.push(health);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return healthResults;
|
|
305
|
+
}
|
|
306
|
+
function getConnectionHealth() {
|
|
307
|
+
return Array.from(connectionHealth.values());
|
|
308
|
+
}
|
|
309
|
+
function getServerHealth(serverName) {
|
|
310
|
+
return connectionHealth.get(serverName) || null;
|
|
311
|
+
}
|
|
312
|
+
function getServerCircuitBreaker(serverName) {
|
|
313
|
+
return mcpCircuitBreakers.getOrCreate(serverName);
|
|
314
|
+
}
|
|
315
|
+
function getAllCircuitBreakerStats() {
|
|
316
|
+
const stats = {};
|
|
317
|
+
for (const [name, breaker] of mcpCircuitBreakers.getAll().entries()) {
|
|
318
|
+
stats[name] = breaker.getStats();
|
|
319
|
+
}
|
|
320
|
+
return stats;
|
|
321
|
+
}
|
|
322
|
+
function startHealthCheck() {
|
|
323
|
+
if (healthCheckTimer) return;
|
|
324
|
+
if (poolConfig.healthCheckInterval <= 0) return;
|
|
325
|
+
healthCheckTimer = setInterval(async () => {
|
|
326
|
+
try {
|
|
327
|
+
await runHealthCheck();
|
|
328
|
+
} catch {
|
|
329
|
+
}
|
|
330
|
+
}, poolConfig.healthCheckInterval);
|
|
331
|
+
}
|
|
332
|
+
function stopHealthCheck() {
|
|
333
|
+
if (healthCheckTimer) {
|
|
334
|
+
clearInterval(healthCheckTimer);
|
|
335
|
+
healthCheckTimer = null;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function getPoolStats() {
|
|
339
|
+
const health = getConnectionHealth();
|
|
340
|
+
return {
|
|
341
|
+
totalConnections: connectedClients.length,
|
|
342
|
+
connectedCount: connectedClients.filter((c) => c.type === "connected").length,
|
|
343
|
+
failedCount: connectedClients.filter((c) => c.type === "failed").length,
|
|
344
|
+
healthyCount: health.filter((h) => h.status === "healthy").length,
|
|
345
|
+
unhealthyCount: health.filter((h) => h.status === "unhealthy").length
|
|
346
|
+
};
|
|
347
|
+
}
|
|
219
348
|
const getClients = memoize(async () => {
|
|
220
349
|
if (process.env.CI && process.env.NODE_ENV !== "test") {
|
|
221
350
|
return [];
|
|
@@ -295,8 +424,20 @@ const getMCPTools = memoize(async () => {
|
|
|
295
424
|
ListToolsResultSchema,
|
|
296
425
|
"tools"
|
|
297
426
|
);
|
|
298
|
-
return toolsList.flatMap(
|
|
299
|
-
|
|
427
|
+
return toolsList.flatMap(({ client, result: { tools } }) => {
|
|
428
|
+
const validTools = tools.filter(
|
|
429
|
+
(tool) => {
|
|
430
|
+
if (!tool || typeof tool.name !== "string" || tool.name.length === 0) {
|
|
431
|
+
logMCPError(
|
|
432
|
+
`Invalid MCP tool from ${client.name}: missing or invalid name`,
|
|
433
|
+
new Error("Tool validation failed")
|
|
434
|
+
);
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
);
|
|
440
|
+
return validTools.map(
|
|
300
441
|
(tool) => ({
|
|
301
442
|
...MCPTool,
|
|
302
443
|
name: "mcp__" + client.name + "__" + tool.name,
|
|
@@ -322,45 +463,117 @@ const getMCPTools = memoize(async () => {
|
|
|
322
463
|
return `${client.name}:${tool.name} (MCP)`;
|
|
323
464
|
}
|
|
324
465
|
})
|
|
325
|
-
)
|
|
326
|
-
);
|
|
466
|
+
);
|
|
467
|
+
});
|
|
327
468
|
});
|
|
469
|
+
async function withTimeout(promise, timeoutMs, operationName) {
|
|
470
|
+
let timeoutId;
|
|
471
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
472
|
+
timeoutId = setTimeout(() => {
|
|
473
|
+
reject(
|
|
474
|
+
new Error(
|
|
475
|
+
`MCP operation "${operationName}" timed out after ${timeoutMs}ms`
|
|
476
|
+
)
|
|
477
|
+
);
|
|
478
|
+
}, timeoutMs);
|
|
479
|
+
});
|
|
480
|
+
try {
|
|
481
|
+
const result = await Promise.race([promise, timeoutPromise]);
|
|
482
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
483
|
+
return result;
|
|
484
|
+
} catch (error) {
|
|
485
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
function isTimeoutError(error) {
|
|
490
|
+
if (error instanceof Error) {
|
|
491
|
+
return error.name === "TimeoutError" || error.message.includes("timed out") || error.message.includes("timeout");
|
|
492
|
+
}
|
|
493
|
+
if (error instanceof DOMException) {
|
|
494
|
+
return error.name === "TimeoutError";
|
|
495
|
+
}
|
|
496
|
+
return false;
|
|
497
|
+
}
|
|
498
|
+
const MCP_TOOL_TIMEOUT_MS = 12e4;
|
|
499
|
+
const MCP_TOOL_MAX_RETRIES = 2;
|
|
328
500
|
async function callMCPTool({
|
|
329
501
|
client: { client, name },
|
|
330
502
|
tool,
|
|
331
503
|
args
|
|
332
504
|
}) {
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
505
|
+
const breaker = mcpCircuitBreakers.getOrCreate(name);
|
|
506
|
+
let lastError;
|
|
507
|
+
const maxRetries = MCP_TOOL_MAX_RETRIES;
|
|
508
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
509
|
+
try {
|
|
510
|
+
const result = await breaker.executeWithTimeout(async () => {
|
|
511
|
+
const callPromise = client.callTool(
|
|
512
|
+
{
|
|
513
|
+
name: tool,
|
|
514
|
+
arguments: args
|
|
515
|
+
},
|
|
516
|
+
CallToolResultSchema
|
|
517
|
+
);
|
|
518
|
+
return await withTimeout(
|
|
519
|
+
callPromise,
|
|
520
|
+
MCP_TOOL_TIMEOUT_MS,
|
|
521
|
+
`${name}:${tool}`
|
|
522
|
+
);
|
|
523
|
+
}, MCP_TOOL_TIMEOUT_MS);
|
|
524
|
+
if ("isError" in result && result.isError) {
|
|
525
|
+
const errorMessage = `Error calling tool ${tool}: ${result.error}`;
|
|
526
|
+
logMCPError(name, errorMessage);
|
|
527
|
+
throw Error(errorMessage);
|
|
528
|
+
}
|
|
529
|
+
if ("toolResult" in result) {
|
|
530
|
+
return String(result.toolResult);
|
|
531
|
+
}
|
|
532
|
+
if ("content" in result && Array.isArray(result.content)) {
|
|
533
|
+
return result.content.map((item) => {
|
|
534
|
+
if (item.type === "image") {
|
|
535
|
+
return {
|
|
536
|
+
type: "image",
|
|
537
|
+
source: {
|
|
538
|
+
type: "base64",
|
|
539
|
+
data: String(item.data),
|
|
540
|
+
media_type: item.mimeType
|
|
541
|
+
}
|
|
542
|
+
};
|
|
357
543
|
}
|
|
358
|
-
|
|
544
|
+
return item;
|
|
545
|
+
});
|
|
359
546
|
}
|
|
360
|
-
|
|
361
|
-
})
|
|
547
|
+
throw Error(`Unexpected response format from tool ${tool}`);
|
|
548
|
+
} catch (error) {
|
|
549
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
550
|
+
if (lastError instanceof CircuitOpenError) {
|
|
551
|
+
logMCPError(
|
|
552
|
+
name,
|
|
553
|
+
`Circuit breaker is open for server "${name}". ${lastError.message}`
|
|
554
|
+
);
|
|
555
|
+
throw lastError;
|
|
556
|
+
}
|
|
557
|
+
if (isTimeoutError(error) && attempt < maxRetries) {
|
|
558
|
+
logMCPError(
|
|
559
|
+
name,
|
|
560
|
+
`Tool "${tool}" timed out (attempt ${attempt + 1}/${maxRetries + 1}), retrying...`
|
|
561
|
+
);
|
|
562
|
+
await new Promise(
|
|
563
|
+
(resolve) => setTimeout(resolve, 1e3 * Math.pow(2, attempt))
|
|
564
|
+
);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
if (isTimeoutError(error)) {
|
|
568
|
+
logMCPError(
|
|
569
|
+
name,
|
|
570
|
+
`Tool "${tool}" failed after ${maxRetries + 1} attempts due to timeout`
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
throw lastError;
|
|
574
|
+
}
|
|
362
575
|
}
|
|
363
|
-
throw Error(`
|
|
576
|
+
throw lastError || new Error(`MCP tool ${tool} failed with unknown error`);
|
|
364
577
|
}
|
|
365
578
|
const getMCPCommands = memoize(async () => {
|
|
366
579
|
const results = await requestAll(
|
|
@@ -424,15 +637,31 @@ async function runCommand({ name, client }, args) {
|
|
|
424
637
|
throw error;
|
|
425
638
|
}
|
|
426
639
|
}
|
|
427
|
-
function refreshMCPConnections() {
|
|
428
|
-
if (
|
|
429
|
-
|
|
430
|
-
}
|
|
431
|
-
if (typeof getMCPTools.cache?.clear === "function") {
|
|
432
|
-
getMCPTools.cache.clear();
|
|
640
|
+
async function refreshMCPConnections() {
|
|
641
|
+
if (pendingRefresh) {
|
|
642
|
+
return;
|
|
433
643
|
}
|
|
434
|
-
|
|
435
|
-
|
|
644
|
+
pendingRefresh = true;
|
|
645
|
+
const release = await acquireConnectionLock();
|
|
646
|
+
try {
|
|
647
|
+
if (typeof getClients.cache?.clear === "function") {
|
|
648
|
+
getClients.cache.clear();
|
|
649
|
+
}
|
|
650
|
+
if (typeof getMCPTools.cache?.clear === "function") {
|
|
651
|
+
getMCPTools.cache.clear();
|
|
652
|
+
}
|
|
653
|
+
if (typeof getMCPCommands.cache?.clear === "function") {
|
|
654
|
+
getMCPCommands.cache.clear();
|
|
655
|
+
}
|
|
656
|
+
mcpCircuitBreakers.resetAll();
|
|
657
|
+
try {
|
|
658
|
+
const { invalidateToolsCache } = await import("../tools.js");
|
|
659
|
+
invalidateToolsCache();
|
|
660
|
+
} catch {
|
|
661
|
+
}
|
|
662
|
+
} finally {
|
|
663
|
+
pendingRefresh = false;
|
|
664
|
+
release();
|
|
436
665
|
}
|
|
437
666
|
}
|
|
438
667
|
async function shutdownMCPClients() {
|
|
@@ -456,21 +685,87 @@ async function shutdownMCPClients() {
|
|
|
456
685
|
} catch {
|
|
457
686
|
}
|
|
458
687
|
connectedClients = [];
|
|
459
|
-
refreshMCPConnections();
|
|
688
|
+
await refreshMCPConnections();
|
|
689
|
+
}
|
|
690
|
+
async function listMCPResources(serverFilter) {
|
|
691
|
+
const results = await requestAll(
|
|
692
|
+
{
|
|
693
|
+
method: "resources/list"
|
|
694
|
+
},
|
|
695
|
+
ListResourcesResultSchema,
|
|
696
|
+
"resources"
|
|
697
|
+
);
|
|
698
|
+
return results.filter(({ client }) => !serverFilter || client.name === serverFilter).flatMap(
|
|
699
|
+
({ client, result }) => (result.resources || []).map((resource) => ({
|
|
700
|
+
uri: resource.uri,
|
|
701
|
+
name: resource.name,
|
|
702
|
+
description: resource.description,
|
|
703
|
+
mimeType: resource.mimeType,
|
|
704
|
+
serverName: client.name
|
|
705
|
+
}))
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
async function readMCPResource(uri, serverName) {
|
|
709
|
+
const clients = await getClients();
|
|
710
|
+
const targetClients = serverName ? clients.filter(
|
|
711
|
+
(c) => c.type === "connected" && c.name === serverName
|
|
712
|
+
) : clients.filter((c) => c.type === "connected");
|
|
713
|
+
for (const client of targetClients) {
|
|
714
|
+
try {
|
|
715
|
+
const capabilities = await client.client.getServerCapabilities();
|
|
716
|
+
if (!capabilities?.resources) {
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
const result = await client.client.request(
|
|
720
|
+
{
|
|
721
|
+
method: "resources/read",
|
|
722
|
+
params: { uri }
|
|
723
|
+
},
|
|
724
|
+
ReadResourceResultSchema
|
|
725
|
+
);
|
|
726
|
+
if (result.contents && result.contents.length > 0) {
|
|
727
|
+
const content = result.contents[0];
|
|
728
|
+
return {
|
|
729
|
+
uri: content.uri,
|
|
730
|
+
mimeType: content.mimeType,
|
|
731
|
+
text: "text" in content ? String(content.text) : void 0,
|
|
732
|
+
blob: "blob" in content ? String(content.blob) : void 0
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
} catch (error) {
|
|
736
|
+
logMCPError(
|
|
737
|
+
client.name,
|
|
738
|
+
`Failed to read resource '${uri}': ${error instanceof Error ? error.message : String(error)}`
|
|
739
|
+
);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
return null;
|
|
460
743
|
}
|
|
461
744
|
export {
|
|
462
745
|
addMcpServer,
|
|
746
|
+
configureMcpPool,
|
|
463
747
|
ensureConfigScope,
|
|
748
|
+
getAllCircuitBreakerStats,
|
|
464
749
|
getClients,
|
|
750
|
+
getConnectionHealth,
|
|
465
751
|
getMCPCommands,
|
|
466
752
|
getMCPTools,
|
|
753
|
+
getMcpPoolConfig,
|
|
467
754
|
getMcpServer,
|
|
468
755
|
getMcprcServerStatus,
|
|
756
|
+
getPoolStats,
|
|
757
|
+
getServerCircuitBreaker,
|
|
758
|
+
getServerHealth,
|
|
759
|
+
listMCPResources,
|
|
469
760
|
listMCPServers,
|
|
470
761
|
parseEnvVars,
|
|
762
|
+
readMCPResource,
|
|
471
763
|
refreshMCPConnections,
|
|
472
764
|
removeMcpServer,
|
|
473
765
|
runCommand,
|
|
474
|
-
|
|
766
|
+
runHealthCheck,
|
|
767
|
+
shutdownMCPClients,
|
|
768
|
+
startHealthCheck,
|
|
769
|
+
stopHealthCheck
|
|
475
770
|
};
|
|
476
771
|
//# 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;AACA,SAAO;AACT;AAEA,MAAM,eAAe,CAAC,WAAW,UAAU,OAAO;AAElD,MAAM,kBAAkB,CAAC,WAAW,QAAQ;AAErC,SAAS,kBAAkB,OAA6B;AAC7D,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,gBACJ,QAAQ,IAAI,cAAc,aAAa,kBAAkB;AAE3D,MAAI,CAAC,cAAc,SAAS,KAAoB,GAAG;AACjD,UAAM,IAAI;AAAA,MACR,kBAAkB,KAAK,qBAAqB,cAAc,KAAK,IAAI,CAAC;AAAA,IACtE;AAAA,EACF;AA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,IAAI;AAAA,cACjC,YAAY,QAAQ,QACjB;AAAA,cACH,MAAM;AAAA,YACR;AAAA,UACF;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd;AAAA,MACE,OAAO;AAAA,MACP,0BAA0B,IAAI,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAC5F;AACA,UAAM;AAAA,EACR;AACF;AAMO,SAAS,wBAA8B;AAE5C,MAAI,OAAO,WAAW,OAAO,UAAU,YAAY;AACjD,eAAW,MAAM,MAAM;AAAA,EACzB;AACA,MAAI,OAAO,YAAY,OAAO,UAAU,YAAY;AAClD,gBAAY,MAAM,MAAM;AAAA,EAC1B;AACA,MAAI,OAAO,eAAe,OAAO,UAAU,YAAY;AACrD,mBAAe,MAAM,MAAM;AAAA,EAC7B;AACF;AAMA,eAAsB,qBAAoC;AACxD,MAAI,iBAAiB,WAAW,GAAG;AACjC;AAAA,EACF;AAGA,QAAM,gBAAgB,iBAAiB,IAAI,OAAM,kBAAiB;AAChE,QAAI,cAAc,SAAS,aAAa;AACtC,UAAI;AACF,cAAM,cAAc,OAAO,MAAM;AAAA,MACnC,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF,CAAC;AAGD,QAAM,sBAAsB;AAC5B,MAAI;AACF,UAAM,QAAQ,KAAK;AAAA,MACjB,QAAQ,WAAW,aAAa;AAAA,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'\nimport { CircuitBreakerRegistry, CircuitOpenError } from '@utils/CircuitBreaker'\n\ntype McpName = string\n\n/**\n * Circuit breaker registry for MCP server connections\n * Each server gets its own circuit breaker to prevent cascading failures\n */\nconst mcpCircuitBreakers = new CircuitBreakerRegistry({\n failureThreshold: 5,\n successThreshold: 2,\n openTimeout: 30000, // 30 seconds before trying again\n})\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// Connection lock mechanism to prevent concurrent refreshMCPConnections calls\nlet connectionLock: Promise<void> | null = null\nlet pendingRefresh = false\n\n/**\n * Acquires the connection lock for exclusive access to MCP connection refresh\n * Waits until any existing lock is released before creating a new one\n */\nasync function acquireConnectionLock(): Promise<() => void> {\n while (connectionLock) {\n await connectionLock\n }\n\n let release: () => void\n connectionLock = new Promise(resolve => {\n release = () => {\n connectionLock = null\n resolve()\n }\n })\n\n return release!\n}\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 * Get circuit breaker for an MCP server\n * Used to check breaker status and manually control it\n */\nexport function getServerCircuitBreaker(serverName: string) {\n return mcpCircuitBreakers.getOrCreate(serverName)\n}\n\n/**\n * Get circuit breaker stats for all servers\n */\nexport function getAllCircuitBreakerStats() {\n const stats: Record<string, any> = {}\n for (const [name, breaker] of mcpCircuitBreakers.getAll().entries()) {\n stats[name] = breaker.getStats()\n }\n return stats\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 const breaker = mcpCircuitBreakers.getOrCreate(name)\n let lastError: Error | undefined\n const maxRetries = MCP_TOOL_MAX_RETRIES\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n // Check circuit breaker before attempting the call\n const result = await breaker.executeWithTimeout(async () => {\n const callPromise = client.callTool(\n {\n name: tool,\n arguments: args,\n },\n CallToolResultSchema,\n )\n\n // Wrap with timeout protection\n return await withTimeout(\n callPromise,\n MCP_TOOL_TIMEOUT_MS,\n `${name}:${tool}`,\n )\n }, MCP_TOOL_TIMEOUT_MS)\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 // Circuit breaker is open - fail fast without retries\n if (lastError instanceof CircuitOpenError) {\n logMCPError(\n name,\n `Circuit breaker is open for server \"${name}\". ${lastError.message}`,\n )\n throw lastError\n }\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 * Uses an async lock to prevent concurrent execution and race conditions\n * Also resets circuit breakers to allow reconnection attempts\n */\nexport async function refreshMCPConnections(): Promise<void> {\n // Early return if refresh is already pending to avoid request accumulation\n if (pendingRefresh) {\n return\n }\n\n pendingRefresh = true\n\n const release = await acquireConnectionLock()\n\n try {\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 // Reset circuit breakers to allow reconnection attempts\n mcpCircuitBreakers.resetAll()\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 try {\n const { invalidateToolsCache } = await import('../tools')\n invalidateToolsCache()\n } catch {\n // Ignore errors - tools.ts may not be loaded yet\n }\n } finally {\n pendingRefresh = false\n release()\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 await 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;AAChC,SAAS,wBAAwB,wBAAwB;AAQzD,MAAM,qBAAqB,IAAI,uBAAuB;AAAA,EACpD,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,aAAa;AAAA;AACf,CAAC;AAEM,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;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