@shareai-lab/kode 1.0.70 → 1.0.71

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.
Files changed (253) hide show
  1. package/README.md +202 -76
  2. package/README.zh-CN.md +246 -0
  3. package/cli.js +62 -0
  4. package/package.json +45 -25
  5. package/scripts/postinstall.js +56 -0
  6. package/src/ProjectOnboarding.tsx +180 -0
  7. package/src/Tool.ts +53 -0
  8. package/src/commands/approvedTools.ts +53 -0
  9. package/src/commands/bug.tsx +20 -0
  10. package/src/commands/clear.ts +43 -0
  11. package/src/commands/compact.ts +120 -0
  12. package/src/commands/config.tsx +19 -0
  13. package/src/commands/cost.ts +18 -0
  14. package/src/commands/ctx_viz.ts +209 -0
  15. package/src/commands/doctor.ts +24 -0
  16. package/src/commands/help.tsx +19 -0
  17. package/src/commands/init.ts +37 -0
  18. package/src/commands/listen.ts +42 -0
  19. package/src/commands/login.tsx +51 -0
  20. package/src/commands/logout.tsx +40 -0
  21. package/src/commands/mcp.ts +41 -0
  22. package/src/commands/model.tsx +40 -0
  23. package/src/commands/modelstatus.tsx +20 -0
  24. package/src/commands/onboarding.tsx +34 -0
  25. package/src/commands/pr_comments.ts +59 -0
  26. package/src/commands/refreshCommands.ts +54 -0
  27. package/src/commands/release-notes.ts +34 -0
  28. package/src/commands/resume.tsx +30 -0
  29. package/src/commands/review.ts +49 -0
  30. package/src/commands/terminalSetup.ts +221 -0
  31. package/src/commands.ts +136 -0
  32. package/src/components/ApproveApiKey.tsx +93 -0
  33. package/src/components/AsciiLogo.tsx +13 -0
  34. package/src/components/AutoUpdater.tsx +148 -0
  35. package/src/components/Bug.tsx +367 -0
  36. package/src/components/Config.tsx +289 -0
  37. package/src/components/ConsoleOAuthFlow.tsx +326 -0
  38. package/src/components/Cost.tsx +23 -0
  39. package/src/components/CostThresholdDialog.tsx +46 -0
  40. package/src/components/CustomSelect/option-map.ts +42 -0
  41. package/src/components/CustomSelect/select-option.tsx +52 -0
  42. package/src/components/CustomSelect/select.tsx +143 -0
  43. package/src/components/CustomSelect/use-select-state.ts +414 -0
  44. package/src/components/CustomSelect/use-select.ts +35 -0
  45. package/src/components/FallbackToolUseRejectedMessage.tsx +15 -0
  46. package/src/components/FileEditToolUpdatedMessage.tsx +66 -0
  47. package/src/components/Help.tsx +215 -0
  48. package/src/components/HighlightedCode.tsx +33 -0
  49. package/src/components/InvalidConfigDialog.tsx +113 -0
  50. package/src/components/Link.tsx +32 -0
  51. package/src/components/LogSelector.tsx +86 -0
  52. package/src/components/Logo.tsx +145 -0
  53. package/src/components/MCPServerApprovalDialog.tsx +100 -0
  54. package/src/components/MCPServerDialogCopy.tsx +25 -0
  55. package/src/components/MCPServerMultiselectDialog.tsx +109 -0
  56. package/src/components/Message.tsx +219 -0
  57. package/src/components/MessageResponse.tsx +15 -0
  58. package/src/components/MessageSelector.tsx +211 -0
  59. package/src/components/ModeIndicator.tsx +88 -0
  60. package/src/components/ModelConfig.tsx +301 -0
  61. package/src/components/ModelListManager.tsx +223 -0
  62. package/src/components/ModelSelector.tsx +3208 -0
  63. package/src/components/ModelStatusDisplay.tsx +228 -0
  64. package/src/components/Onboarding.tsx +274 -0
  65. package/src/components/PressEnterToContinue.tsx +11 -0
  66. package/src/components/PromptInput.tsx +710 -0
  67. package/src/components/SentryErrorBoundary.ts +33 -0
  68. package/src/components/Spinner.tsx +129 -0
  69. package/src/components/StructuredDiff.tsx +184 -0
  70. package/src/components/TextInput.tsx +246 -0
  71. package/src/components/TokenWarning.tsx +31 -0
  72. package/src/components/ToolUseLoader.tsx +40 -0
  73. package/src/components/TrustDialog.tsx +106 -0
  74. package/src/components/binary-feedback/BinaryFeedback.tsx +63 -0
  75. package/src/components/binary-feedback/BinaryFeedbackOption.tsx +111 -0
  76. package/src/components/binary-feedback/BinaryFeedbackView.tsx +172 -0
  77. package/src/components/binary-feedback/utils.ts +220 -0
  78. package/src/components/messages/AssistantBashOutputMessage.tsx +22 -0
  79. package/src/components/messages/AssistantLocalCommandOutputMessage.tsx +45 -0
  80. package/src/components/messages/AssistantRedactedThinkingMessage.tsx +19 -0
  81. package/src/components/messages/AssistantTextMessage.tsx +144 -0
  82. package/src/components/messages/AssistantThinkingMessage.tsx +40 -0
  83. package/src/components/messages/AssistantToolUseMessage.tsx +123 -0
  84. package/src/components/messages/UserBashInputMessage.tsx +28 -0
  85. package/src/components/messages/UserCommandMessage.tsx +30 -0
  86. package/src/components/messages/UserKodingInputMessage.tsx +28 -0
  87. package/src/components/messages/UserPromptMessage.tsx +35 -0
  88. package/src/components/messages/UserTextMessage.tsx +39 -0
  89. package/src/components/messages/UserToolResultMessage/UserToolCanceledMessage.tsx +12 -0
  90. package/src/components/messages/UserToolResultMessage/UserToolErrorMessage.tsx +36 -0
  91. package/src/components/messages/UserToolResultMessage/UserToolRejectMessage.tsx +31 -0
  92. package/src/components/messages/UserToolResultMessage/UserToolResultMessage.tsx +57 -0
  93. package/src/components/messages/UserToolResultMessage/UserToolSuccessMessage.tsx +35 -0
  94. package/src/components/messages/UserToolResultMessage/utils.tsx +56 -0
  95. package/src/components/permissions/BashPermissionRequest/BashPermissionRequest.tsx +121 -0
  96. package/src/components/permissions/FallbackPermissionRequest.tsx +155 -0
  97. package/src/components/permissions/FileEditPermissionRequest/FileEditPermissionRequest.tsx +182 -0
  98. package/src/components/permissions/FileEditPermissionRequest/FileEditToolDiff.tsx +75 -0
  99. package/src/components/permissions/FileWritePermissionRequest/FileWritePermissionRequest.tsx +164 -0
  100. package/src/components/permissions/FileWritePermissionRequest/FileWriteToolDiff.tsx +81 -0
  101. package/src/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.tsx +242 -0
  102. package/src/components/permissions/PermissionRequest.tsx +103 -0
  103. package/src/components/permissions/PermissionRequestTitle.tsx +69 -0
  104. package/src/components/permissions/hooks.ts +44 -0
  105. package/src/components/permissions/toolUseOptions.ts +59 -0
  106. package/src/components/permissions/utils.ts +23 -0
  107. package/src/constants/betas.ts +5 -0
  108. package/src/constants/claude-asterisk-ascii-art.tsx +238 -0
  109. package/src/constants/figures.ts +4 -0
  110. package/src/constants/keys.ts +3 -0
  111. package/src/constants/macros.ts +6 -0
  112. package/src/constants/models.ts +935 -0
  113. package/src/constants/oauth.ts +18 -0
  114. package/src/constants/product.ts +17 -0
  115. package/src/constants/prompts.ts +177 -0
  116. package/src/constants/releaseNotes.ts +7 -0
  117. package/src/context/PermissionContext.tsx +149 -0
  118. package/src/context.ts +278 -0
  119. package/src/cost-tracker.ts +84 -0
  120. package/src/entrypoints/cli.tsx +1498 -0
  121. package/src/entrypoints/mcp.ts +176 -0
  122. package/src/history.ts +25 -0
  123. package/src/hooks/useApiKeyVerification.ts +59 -0
  124. package/src/hooks/useArrowKeyHistory.ts +55 -0
  125. package/src/hooks/useCanUseTool.ts +138 -0
  126. package/src/hooks/useCancelRequest.ts +39 -0
  127. package/src/hooks/useDoublePress.ts +42 -0
  128. package/src/hooks/useExitOnCtrlCD.ts +31 -0
  129. package/src/hooks/useInterval.ts +25 -0
  130. package/src/hooks/useLogMessages.ts +16 -0
  131. package/src/hooks/useLogStartupTime.ts +12 -0
  132. package/src/hooks/useNotifyAfterTimeout.ts +65 -0
  133. package/src/hooks/usePermissionRequestLogging.ts +44 -0
  134. package/src/hooks/useSlashCommandTypeahead.ts +137 -0
  135. package/src/hooks/useTerminalSize.ts +49 -0
  136. package/src/hooks/useTextInput.ts +315 -0
  137. package/src/messages.ts +37 -0
  138. package/src/permissions.ts +268 -0
  139. package/src/query.ts +704 -0
  140. package/src/screens/ConfigureNpmPrefix.tsx +197 -0
  141. package/src/screens/Doctor.tsx +219 -0
  142. package/src/screens/LogList.tsx +68 -0
  143. package/src/screens/REPL.tsx +792 -0
  144. package/src/screens/ResumeConversation.tsx +68 -0
  145. package/src/services/browserMocks.ts +66 -0
  146. package/src/services/claude.ts +1947 -0
  147. package/src/services/customCommands.ts +683 -0
  148. package/src/services/fileFreshness.ts +377 -0
  149. package/src/services/mcpClient.ts +564 -0
  150. package/src/services/mcpServerApproval.tsx +50 -0
  151. package/src/services/notifier.ts +40 -0
  152. package/src/services/oauth.ts +357 -0
  153. package/src/services/openai.ts +796 -0
  154. package/src/services/sentry.ts +3 -0
  155. package/src/services/statsig.ts +171 -0
  156. package/src/services/statsigStorage.ts +86 -0
  157. package/src/services/systemReminder.ts +406 -0
  158. package/src/services/vcr.ts +161 -0
  159. package/src/tools/ArchitectTool/ArchitectTool.tsx +122 -0
  160. package/src/tools/ArchitectTool/prompt.ts +15 -0
  161. package/src/tools/AskExpertModelTool/AskExpertModelTool.tsx +505 -0
  162. package/src/tools/BashTool/BashTool.tsx +270 -0
  163. package/src/tools/BashTool/BashToolResultMessage.tsx +38 -0
  164. package/src/tools/BashTool/OutputLine.tsx +48 -0
  165. package/src/tools/BashTool/prompt.ts +174 -0
  166. package/src/tools/BashTool/utils.ts +56 -0
  167. package/src/tools/FileEditTool/FileEditTool.tsx +316 -0
  168. package/src/tools/FileEditTool/prompt.ts +51 -0
  169. package/src/tools/FileEditTool/utils.ts +58 -0
  170. package/src/tools/FileReadTool/FileReadTool.tsx +371 -0
  171. package/src/tools/FileReadTool/prompt.ts +7 -0
  172. package/src/tools/FileWriteTool/FileWriteTool.tsx +297 -0
  173. package/src/tools/FileWriteTool/prompt.ts +10 -0
  174. package/src/tools/GlobTool/GlobTool.tsx +119 -0
  175. package/src/tools/GlobTool/prompt.ts +8 -0
  176. package/src/tools/GrepTool/GrepTool.tsx +147 -0
  177. package/src/tools/GrepTool/prompt.ts +11 -0
  178. package/src/tools/MCPTool/MCPTool.tsx +106 -0
  179. package/src/tools/MCPTool/prompt.ts +3 -0
  180. package/src/tools/MemoryReadTool/MemoryReadTool.tsx +127 -0
  181. package/src/tools/MemoryReadTool/prompt.ts +3 -0
  182. package/src/tools/MemoryWriteTool/MemoryWriteTool.tsx +89 -0
  183. package/src/tools/MemoryWriteTool/prompt.ts +3 -0
  184. package/src/tools/MultiEditTool/MultiEditTool.tsx +366 -0
  185. package/src/tools/MultiEditTool/prompt.ts +45 -0
  186. package/src/tools/NotebookEditTool/NotebookEditTool.tsx +298 -0
  187. package/src/tools/NotebookEditTool/prompt.ts +3 -0
  188. package/src/tools/NotebookReadTool/NotebookReadTool.tsx +266 -0
  189. package/src/tools/NotebookReadTool/prompt.ts +3 -0
  190. package/src/tools/StickerRequestTool/StickerRequestTool.tsx +93 -0
  191. package/src/tools/StickerRequestTool/prompt.ts +19 -0
  192. package/src/tools/TaskTool/TaskTool.tsx +382 -0
  193. package/src/tools/TaskTool/constants.ts +1 -0
  194. package/src/tools/TaskTool/prompt.ts +56 -0
  195. package/src/tools/ThinkTool/ThinkTool.tsx +56 -0
  196. package/src/tools/ThinkTool/prompt.ts +12 -0
  197. package/src/tools/TodoWriteTool/TodoWriteTool.tsx +289 -0
  198. package/src/tools/TodoWriteTool/prompt.ts +63 -0
  199. package/src/tools/lsTool/lsTool.tsx +269 -0
  200. package/src/tools/lsTool/prompt.ts +2 -0
  201. package/src/tools.ts +63 -0
  202. package/src/types/PermissionMode.ts +120 -0
  203. package/src/types/RequestContext.ts +72 -0
  204. package/src/utils/Cursor.ts +436 -0
  205. package/src/utils/PersistentShell.ts +373 -0
  206. package/src/utils/agentStorage.ts +97 -0
  207. package/src/utils/array.ts +3 -0
  208. package/src/utils/ask.tsx +98 -0
  209. package/src/utils/auth.ts +13 -0
  210. package/src/utils/autoCompactCore.ts +223 -0
  211. package/src/utils/autoUpdater.ts +318 -0
  212. package/src/utils/betas.ts +20 -0
  213. package/src/utils/browser.ts +14 -0
  214. package/src/utils/cleanup.ts +72 -0
  215. package/src/utils/commands.ts +261 -0
  216. package/src/utils/config.ts +771 -0
  217. package/src/utils/conversationRecovery.ts +54 -0
  218. package/src/utils/debugLogger.ts +1123 -0
  219. package/src/utils/diff.ts +42 -0
  220. package/src/utils/env.ts +57 -0
  221. package/src/utils/errors.ts +21 -0
  222. package/src/utils/exampleCommands.ts +108 -0
  223. package/src/utils/execFileNoThrow.ts +51 -0
  224. package/src/utils/expertChatStorage.ts +136 -0
  225. package/src/utils/file.ts +402 -0
  226. package/src/utils/fileRecoveryCore.ts +71 -0
  227. package/src/utils/format.tsx +44 -0
  228. package/src/utils/generators.ts +62 -0
  229. package/src/utils/git.ts +92 -0
  230. package/src/utils/globalLogger.ts +77 -0
  231. package/src/utils/http.ts +10 -0
  232. package/src/utils/imagePaste.ts +38 -0
  233. package/src/utils/json.ts +13 -0
  234. package/src/utils/log.ts +382 -0
  235. package/src/utils/markdown.ts +213 -0
  236. package/src/utils/messageContextManager.ts +289 -0
  237. package/src/utils/messages.tsx +938 -0
  238. package/src/utils/model.ts +836 -0
  239. package/src/utils/permissions/filesystem.ts +118 -0
  240. package/src/utils/ripgrep.ts +167 -0
  241. package/src/utils/sessionState.ts +49 -0
  242. package/src/utils/state.ts +25 -0
  243. package/src/utils/style.ts +29 -0
  244. package/src/utils/terminal.ts +49 -0
  245. package/src/utils/theme.ts +122 -0
  246. package/src/utils/thinking.ts +144 -0
  247. package/src/utils/todoStorage.ts +431 -0
  248. package/src/utils/tokens.ts +43 -0
  249. package/src/utils/toolExecutionController.ts +163 -0
  250. package/src/utils/unaryLogging.ts +26 -0
  251. package/src/utils/user.ts +37 -0
  252. package/src/utils/validate.ts +165 -0
  253. package/cli.mjs +0 -1803
@@ -0,0 +1,564 @@
1
+ import { zipObject } from 'lodash-es'
2
+ import {
3
+ getCurrentProjectConfig,
4
+ McpServerConfig,
5
+ saveCurrentProjectConfig,
6
+ getGlobalConfig,
7
+ saveGlobalConfig,
8
+ getMcprcConfig,
9
+ addMcprcServerForTesting,
10
+ removeMcprcServerForTesting,
11
+ } from '../utils/config.js'
12
+ import { existsSync, readFileSync, writeFileSync } from 'fs'
13
+ import { join } from 'path'
14
+ import { getCwd } from '../utils/state'
15
+ import { safeParseJSON } from '../utils/json'
16
+ import {
17
+ ImageBlockParam,
18
+ MessageParam,
19
+ ToolResultBlockParam,
20
+ } from '@anthropic-ai/sdk/resources/index.mjs'
21
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
22
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
23
+ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'
24
+ import {
25
+ CallToolResultSchema,
26
+ ClientRequest,
27
+ ListPromptsResult,
28
+ ListPromptsResultSchema,
29
+ ListToolsResult,
30
+ ListToolsResultSchema,
31
+ Result,
32
+ ResultSchema,
33
+ } from '@modelcontextprotocol/sdk/types.js'
34
+ import { memoize, pickBy } from 'lodash-es'
35
+ import type { Tool } from '../Tool'
36
+ import { MCPTool } from '../tools/MCPTool/MCPTool'
37
+ import { logMCPError } from '../utils/log'
38
+ import { Command } from '../commands'
39
+ import { logEvent } from '../services/statsig'
40
+ import { PRODUCT_COMMAND } from '../constants/product.js'
41
+
42
+ type McpName = string
43
+
44
+ export function parseEnvVars(
45
+ rawEnvArgs: string[] | undefined,
46
+ ): Record<string, string> {
47
+ const parsedEnv: Record<string, string> = {}
48
+
49
+ // Parse individual env vars
50
+ if (rawEnvArgs) {
51
+ for (const envStr of rawEnvArgs) {
52
+ const [key, ...valueParts] = envStr.split('=')
53
+ if (!key || valueParts.length === 0) {
54
+ throw new Error(
55
+ `Invalid environment variable format: ${envStr}, environment variables should be added as: -e KEY1=value1 -e KEY2=value2`,
56
+ )
57
+ }
58
+ parsedEnv[key] = valueParts.join('=')
59
+ }
60
+ }
61
+ return parsedEnv
62
+ }
63
+
64
+ const VALID_SCOPES = ['project', 'global', 'mcprc'] as const
65
+ type ConfigScope = (typeof VALID_SCOPES)[number]
66
+ const EXTERNAL_SCOPES = ['project', 'global'] as ConfigScope[]
67
+
68
+ export function ensureConfigScope(scope?: string): ConfigScope {
69
+ if (!scope) return 'project'
70
+
71
+ const scopesToCheck =
72
+ process.env.USER_TYPE === 'external' ? EXTERNAL_SCOPES : VALID_SCOPES
73
+
74
+ if (!scopesToCheck.includes(scope as ConfigScope)) {
75
+ throw new Error(
76
+ `Invalid scope: ${scope}. Must be one of: ${scopesToCheck.join(', ')}`,
77
+ )
78
+ }
79
+
80
+ return scope as ConfigScope
81
+ }
82
+
83
+ export function addMcpServer(
84
+ name: McpName,
85
+ server: McpServerConfig,
86
+ scope: ConfigScope = 'project',
87
+ ): void {
88
+ if (scope === 'mcprc') {
89
+ if (process.env.NODE_ENV === 'test') {
90
+ addMcprcServerForTesting(name, server)
91
+ } else {
92
+ const mcprcPath = join(getCwd(), '.mcprc')
93
+ let mcprcConfig: Record<string, McpServerConfig> = {}
94
+
95
+ // Read existing config if present
96
+ if (existsSync(mcprcPath)) {
97
+ try {
98
+ const mcprcContent = readFileSync(mcprcPath, 'utf-8')
99
+ const existingConfig = safeParseJSON(mcprcContent)
100
+ if (existingConfig && typeof existingConfig === 'object') {
101
+ mcprcConfig = existingConfig as Record<string, McpServerConfig>
102
+ }
103
+ } catch {
104
+ // If we can't read/parse, start with empty config
105
+ }
106
+ }
107
+
108
+ // Add the server
109
+ mcprcConfig[name] = server
110
+
111
+ // Write back to .mcprc
112
+ try {
113
+ writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')
114
+ } catch (error) {
115
+ throw new Error(`Failed to write to .mcprc: ${error}`)
116
+ }
117
+ }
118
+ } else if (scope === 'global') {
119
+ const config = getGlobalConfig()
120
+ if (!config.mcpServers) {
121
+ config.mcpServers = {}
122
+ }
123
+ config.mcpServers[name] = server
124
+ saveGlobalConfig(config)
125
+ } else {
126
+ const config = getCurrentProjectConfig()
127
+ if (!config.mcpServers) {
128
+ config.mcpServers = {}
129
+ }
130
+ config.mcpServers[name] = server
131
+ saveCurrentProjectConfig(config)
132
+ }
133
+ }
134
+
135
+ export function removeMcpServer(
136
+ name: McpName,
137
+ scope: ConfigScope = 'project',
138
+ ): void {
139
+ if (scope === 'mcprc') {
140
+ if (process.env.NODE_ENV === 'test') {
141
+ removeMcprcServerForTesting(name)
142
+ } else {
143
+ const mcprcPath = join(getCwd(), '.mcprc')
144
+ if (!existsSync(mcprcPath)) {
145
+ throw new Error('No .mcprc file found in this directory')
146
+ }
147
+
148
+ try {
149
+ const mcprcContent = readFileSync(mcprcPath, 'utf-8')
150
+ const mcprcConfig = safeParseJSON(mcprcContent) as Record<
151
+ string,
152
+ McpServerConfig
153
+ > | null
154
+
155
+ if (
156
+ !mcprcConfig ||
157
+ typeof mcprcConfig !== 'object' ||
158
+ !mcprcConfig[name]
159
+ ) {
160
+ throw new Error(`No MCP server found with name: ${name} in .mcprc`)
161
+ }
162
+
163
+ delete mcprcConfig[name]
164
+ writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')
165
+ } catch (error) {
166
+ if (error instanceof Error) {
167
+ throw error
168
+ }
169
+ throw new Error(`Failed to remove from .mcprc: ${error}`)
170
+ }
171
+ }
172
+ } else if (scope === 'global') {
173
+ const config = getGlobalConfig()
174
+ if (!config.mcpServers?.[name]) {
175
+ throw new Error(`No global MCP server found with name: ${name}`)
176
+ }
177
+ delete config.mcpServers[name]
178
+ saveGlobalConfig(config)
179
+ } else {
180
+ const config = getCurrentProjectConfig()
181
+ if (!config.mcpServers?.[name]) {
182
+ throw new Error(`No local MCP server found with name: ${name}`)
183
+ }
184
+ delete config.mcpServers[name]
185
+ saveCurrentProjectConfig(config)
186
+ }
187
+ }
188
+
189
+ export function listMCPServers(): Record<string, McpServerConfig> {
190
+ const globalConfig = getGlobalConfig()
191
+ const mcprcConfig = getMcprcConfig()
192
+ const projectConfig = getCurrentProjectConfig()
193
+ return {
194
+ ...(globalConfig.mcpServers ?? {}),
195
+ ...(mcprcConfig ?? {}), // mcprc configs override global ones
196
+ ...(projectConfig.mcpServers ?? {}), // Project configs override mcprc ones
197
+ }
198
+ }
199
+
200
+ export type ScopedMcpServerConfig = McpServerConfig & {
201
+ scope: ConfigScope
202
+ }
203
+
204
+ export function getMcpServer(name: McpName): ScopedMcpServerConfig | undefined {
205
+ const projectConfig = getCurrentProjectConfig()
206
+ const mcprcConfig = getMcprcConfig()
207
+ const globalConfig = getGlobalConfig()
208
+
209
+ // Check each scope in order of precedence
210
+ if (projectConfig.mcpServers?.[name]) {
211
+ return { ...projectConfig.mcpServers[name], scope: 'project' }
212
+ }
213
+
214
+ if (mcprcConfig?.[name]) {
215
+ return { ...mcprcConfig[name], scope: 'mcprc' }
216
+ }
217
+
218
+ if (globalConfig.mcpServers?.[name]) {
219
+ return { ...globalConfig.mcpServers[name], scope: 'global' }
220
+ }
221
+
222
+ return undefined
223
+ }
224
+
225
+ async function connectToServer(
226
+ name: string,
227
+ serverRef: McpServerConfig,
228
+ ): Promise<Client> {
229
+ const transport =
230
+ serverRef.type === 'sse'
231
+ ? new SSEClientTransport(new URL(serverRef.url))
232
+ : new StdioClientTransport({
233
+ command: serverRef.command,
234
+ args: serverRef.args,
235
+ env: {
236
+ ...process.env,
237
+ ...serverRef.env,
238
+ } as Record<string, string>,
239
+ stderr: 'pipe', // prevents error output from the MCP server from printing to the UI
240
+ })
241
+
242
+ const client = new Client(
243
+ {
244
+ name: PRODUCT_COMMAND,
245
+ version: '0.1.0',
246
+ },
247
+ {
248
+ capabilities: {},
249
+ },
250
+ )
251
+
252
+ // Add a timeout to connection attempts to prevent tests from hanging indefinitely
253
+ const CONNECTION_TIMEOUT_MS = 5000
254
+ const connectPromise = client.connect(transport)
255
+ const timeoutPromise = new Promise<never>((_, reject) => {
256
+ const timeoutId = setTimeout(() => {
257
+ reject(
258
+ new Error(
259
+ `Connection to MCP server "${name}" timed out after ${CONNECTION_TIMEOUT_MS}ms`,
260
+ ),
261
+ )
262
+ }, CONNECTION_TIMEOUT_MS)
263
+
264
+ // Clean up timeout if connect resolves or rejects
265
+ connectPromise.then(
266
+ () => clearTimeout(timeoutId),
267
+ () => clearTimeout(timeoutId),
268
+ )
269
+ })
270
+
271
+ await Promise.race([connectPromise, timeoutPromise])
272
+
273
+ if (serverRef.type === 'stdio') {
274
+ ;(transport as StdioClientTransport).stderr?.on('data', (data: Buffer) => {
275
+ const errorText = data.toString().trim()
276
+ if (errorText) {
277
+ logMCPError(name, `Server stderr: ${errorText}`)
278
+ }
279
+ })
280
+ }
281
+ return client
282
+ }
283
+
284
+ type ConnectedClient = {
285
+ client: Client
286
+ name: string
287
+ type: 'connected'
288
+ }
289
+ type FailedClient = {
290
+ name: string
291
+ type: 'failed'
292
+ }
293
+ export type WrappedClient = ConnectedClient | FailedClient
294
+
295
+ export function getMcprcServerStatus(
296
+ serverName: string,
297
+ ): 'approved' | 'rejected' | 'pending' {
298
+ const config = getCurrentProjectConfig()
299
+ if (config.approvedMcprcServers?.includes(serverName)) {
300
+ return 'approved'
301
+ }
302
+ if (config.rejectedMcprcServers?.includes(serverName)) {
303
+ return 'rejected'
304
+ }
305
+ return 'pending'
306
+ }
307
+
308
+ export const getClients = memoize(async (): Promise<WrappedClient[]> => {
309
+ // TODO: This is a temporary fix for a hang during npm run verify in CI.
310
+ // We need to investigate why MCP client connections hang in CI verify but not in CI tests.
311
+ if (process.env.CI && process.env.NODE_ENV !== 'test') {
312
+ return []
313
+ }
314
+
315
+ const globalServers = getGlobalConfig().mcpServers ?? {}
316
+ const mcprcServers = getMcprcConfig()
317
+ const projectServers = getCurrentProjectConfig().mcpServers ?? {}
318
+
319
+ // Filter mcprc servers to only include approved ones
320
+ const approvedMcprcServers = pickBy(
321
+ mcprcServers,
322
+ (_, name) => getMcprcServerStatus(name) === 'approved',
323
+ )
324
+
325
+ const allServers = {
326
+ ...globalServers,
327
+ ...approvedMcprcServers, // Approved .mcprc servers override global ones
328
+ ...projectServers, // Project servers take highest precedence
329
+ }
330
+
331
+ return await Promise.all(
332
+ Object.entries(allServers).map(async ([name, serverRef]) => {
333
+ try {
334
+ const client = await connectToServer(name, serverRef)
335
+ logEvent('tengu_mcp_server_connection_succeeded', {})
336
+ return { name, client, type: 'connected' as const }
337
+ } catch (error) {
338
+ logEvent('tengu_mcp_server_connection_failed', {})
339
+ logMCPError(
340
+ name,
341
+ `Connection failed: ${error instanceof Error ? error.message : String(error)}`,
342
+ )
343
+ return { name, type: 'failed' as const }
344
+ }
345
+ }),
346
+ )
347
+ })
348
+
349
+ async function requestAll<
350
+ ResultT extends Result,
351
+ ResultSchemaT extends typeof ResultSchema,
352
+ >(
353
+ req: ClientRequest,
354
+ resultSchema: ResultSchemaT,
355
+ requiredCapability: string,
356
+ ): Promise<{ client: ConnectedClient; result: ResultT }[]> {
357
+ const clients = await getClients()
358
+ const results = await Promise.allSettled(
359
+ clients.map(async client => {
360
+ if (client.type === 'failed') return null
361
+
362
+ try {
363
+ const capabilities = await client.client.getServerCapabilities()
364
+ if (!capabilities?.[requiredCapability]) {
365
+ return null
366
+ }
367
+ return {
368
+ client,
369
+ result: (await client.client.request(req, resultSchema)) as ResultT,
370
+ }
371
+ } catch (error) {
372
+ if (client.type === 'connected') {
373
+ logMCPError(
374
+ client.name,
375
+ `Failed to request '${req.method}': ${error instanceof Error ? error.message : String(error)}`,
376
+ )
377
+ }
378
+ return null
379
+ }
380
+ }),
381
+ )
382
+ return results
383
+ .filter(
384
+ (
385
+ result,
386
+ ): result is PromiseFulfilledResult<{
387
+ client: ConnectedClient
388
+ result: ResultT
389
+ } | null> => result.status === 'fulfilled',
390
+ )
391
+ .map(result => result.value)
392
+ .filter(
393
+ (result): result is { client: ConnectedClient; result: ResultT } =>
394
+ result !== null,
395
+ )
396
+ }
397
+
398
+ export const getMCPTools = memoize(async (): Promise<Tool[]> => {
399
+ const toolsList = await requestAll<
400
+ ListToolsResult,
401
+ typeof ListToolsResultSchema
402
+ >(
403
+ {
404
+ method: 'tools/list',
405
+ },
406
+ ListToolsResultSchema,
407
+ 'tools',
408
+ )
409
+
410
+ // TODO: Add zod schema validation
411
+ return toolsList.flatMap(({ client, result: { tools } }) =>
412
+ tools.map(
413
+ (tool): Tool => ({
414
+ ...MCPTool,
415
+ name: 'mcp__' + client.name + '__' + tool.name,
416
+ async description() {
417
+ return tool.description ?? ''
418
+ },
419
+ async prompt() {
420
+ return tool.description ?? ''
421
+ },
422
+ inputJSONSchema: tool.inputSchema as Tool['inputJSONSchema'],
423
+ async validateInput(input, context) {
424
+ // MCP tools handle their own validation through their schemas
425
+ return { result: true }
426
+ },
427
+ async *call(args: Record<string, unknown>, context) {
428
+ const data = await callMCPTool({ client, tool: tool.name, args })
429
+ yield {
430
+ type: 'result' as const,
431
+ data,
432
+ resultForAssistant: data,
433
+ }
434
+ },
435
+ userFacingName() {
436
+ return `${client.name}:${tool.name} (MCP)`
437
+ },
438
+ }),
439
+ ),
440
+ )
441
+ })
442
+
443
+ async function callMCPTool({
444
+ client: { client, name },
445
+ tool,
446
+ args,
447
+ }: {
448
+ client: ConnectedClient
449
+ tool: string
450
+ args: Record<string, unknown>
451
+ }): Promise<ToolResultBlockParam['content']> {
452
+ const result = await client.callTool(
453
+ {
454
+ name: tool,
455
+ arguments: args,
456
+ },
457
+ CallToolResultSchema,
458
+ )
459
+
460
+ if ('isError' in result && result.isError) {
461
+ const errorMessage = `Error calling tool ${tool}: ${result.error}`
462
+ logMCPError(name, errorMessage)
463
+ throw Error(errorMessage)
464
+ }
465
+
466
+ // Handle toolResult-type response
467
+ if ('toolResult' in result) {
468
+ return String(result.toolResult)
469
+ }
470
+
471
+ // Handle content array response
472
+ if ('content' in result && Array.isArray(result.content)) {
473
+ return result.content.map(item => {
474
+ if (item.type === 'image') {
475
+ return {
476
+ type: 'image',
477
+ source: {
478
+ type: 'base64',
479
+ data: String(item.data),
480
+ media_type: item.mimeType as ImageBlockParam.Source['media_type'],
481
+ },
482
+ }
483
+ }
484
+ return item
485
+ })
486
+ }
487
+
488
+ throw Error(`Unexpected response format from tool ${tool}`)
489
+ }
490
+
491
+ export const getMCPCommands = memoize(async (): Promise<Command[]> => {
492
+ const results = await requestAll<
493
+ ListPromptsResult,
494
+ typeof ListPromptsResultSchema
495
+ >(
496
+ {
497
+ method: 'prompts/list',
498
+ },
499
+ ListPromptsResultSchema,
500
+ 'prompts',
501
+ )
502
+
503
+ return results.flatMap(({ client, result }) =>
504
+ result.prompts?.map(_ => {
505
+ const argNames = Object.values(_.arguments ?? {}).map(k => k.name)
506
+ return {
507
+ type: 'prompt',
508
+ name: 'mcp__' + client.name + '__' + _.name,
509
+ description: _.description ?? '',
510
+ isEnabled: true,
511
+ isHidden: false,
512
+ progressMessage: 'running',
513
+ userFacingName() {
514
+ return `${client.name}:${_.name} (MCP)`
515
+ },
516
+ argNames,
517
+ async getPromptForCommand(args: string) {
518
+ const argsArray = args.split(' ')
519
+ return await runCommand(
520
+ { name: _.name, client },
521
+ zipObject(argNames, argsArray),
522
+ )
523
+ },
524
+ }
525
+ }),
526
+ )
527
+ })
528
+
529
+ export async function runCommand(
530
+ { name, client }: { name: string; client: ConnectedClient },
531
+ args: Record<string, string>,
532
+ ): Promise<MessageParam[]> {
533
+ try {
534
+ const result = await client.client.getPrompt({ name, arguments: args })
535
+ // TODO: Support type == resource
536
+ return result.messages.map(
537
+ (message): MessageParam => ({
538
+ role: message.role,
539
+ content: [
540
+ message.content.type === 'text'
541
+ ? {
542
+ type: 'text',
543
+ text: message.content.text,
544
+ }
545
+ : {
546
+ type: 'image',
547
+ source: {
548
+ data: String(message.content.data),
549
+ media_type: message.content
550
+ .mimeType as ImageBlockParam.Source['media_type'],
551
+ type: 'base64',
552
+ },
553
+ },
554
+ ],
555
+ }),
556
+ )
557
+ } catch (error) {
558
+ logMCPError(
559
+ client.name,
560
+ `Error running command '${name}': ${error instanceof Error ? error.message : String(error)}`,
561
+ )
562
+ throw error
563
+ }
564
+ }
@@ -0,0 +1,50 @@
1
+ import React from 'react'
2
+ import { render } from 'ink'
3
+ import { MCPServerMultiselectDialog } from '../components/MCPServerMultiselectDialog'
4
+ import { MCPServerApprovalDialog } from '../components/MCPServerApprovalDialog'
5
+ import { getMcprcServerStatus } from './mcpClient'
6
+ import { getMcprcConfig } from '../utils/config'
7
+
8
+ export async function handleMcprcServerApprovals(): Promise<void> {
9
+ const mcprcServers = getMcprcConfig()
10
+ const pendingServers = Object.keys(mcprcServers).filter(
11
+ serverName => getMcprcServerStatus(serverName) === 'pending',
12
+ )
13
+
14
+ if (pendingServers.length === 0) {
15
+ return
16
+ }
17
+
18
+ await new Promise<void>(resolve => {
19
+ const clearScreenAndResolve = () => {
20
+ // Clear screen after dialog
21
+ process.stdout.write('\x1b[2J\x1b[3J\x1b[H', () => {
22
+ resolve()
23
+ })
24
+ }
25
+
26
+ if (pendingServers.length === 1 && pendingServers[0] !== undefined) {
27
+ const result = render(
28
+ <MCPServerApprovalDialog
29
+ serverName={pendingServers[0]}
30
+ onDone={() => {
31
+ result.unmount?.()
32
+ clearScreenAndResolve()
33
+ }}
34
+ />,
35
+ { exitOnCtrlC: false },
36
+ )
37
+ } else {
38
+ const result = render(
39
+ <MCPServerMultiselectDialog
40
+ serverNames={pendingServers}
41
+ onDone={() => {
42
+ result.unmount?.()
43
+ clearScreenAndResolve()
44
+ }}
45
+ />,
46
+ { exitOnCtrlC: false },
47
+ )
48
+ }
49
+ })
50
+ }
@@ -0,0 +1,40 @@
1
+ import { getGlobalConfig } from '../utils/config'
2
+
3
+ export type NotificationOptions = {
4
+ message: string
5
+ title?: string
6
+ }
7
+
8
+ function sendITerm2Notification({ message, title }: NotificationOptions): void {
9
+ const displayString = title ? `${title}:\n${message}` : message
10
+ try {
11
+ process.stdout.write(`\x1b]9;\n\n${displayString}\x07`)
12
+ } catch {
13
+ // Ignore errors
14
+ }
15
+ }
16
+
17
+ function sendTerminalBell(): void {
18
+ process.stdout.write('\x07')
19
+ }
20
+
21
+ export async function sendNotification(
22
+ notif: NotificationOptions,
23
+ ): Promise<void> {
24
+ const channel = getGlobalConfig().preferredNotifChannel
25
+ switch (channel) {
26
+ case 'iterm2':
27
+ sendITerm2Notification(notif)
28
+ break
29
+ case 'terminal_bell':
30
+ sendTerminalBell()
31
+ break
32
+ case 'iterm2_with_bell':
33
+ sendITerm2Notification(notif)
34
+ sendTerminalBell()
35
+ break
36
+ case 'notifications_disabled':
37
+ // Do nothing
38
+ break
39
+ }
40
+ }