This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathUseMcpToolTool.ts
More file actions
348 lines (297 loc) · 10.3 KB
/
Copy pathUseMcpToolTool.ts
File metadata and controls
348 lines (297 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import type { ClineAskUseMcpServer, McpExecutionStatus } from "@roo-code/types"
import { Task } from "../task/Task"
import { formatResponse } from "../prompts/responses"
import { t } from "../../i18n"
import type { ToolUse } from "../../shared/tools"
import { BaseTool, ToolCallbacks } from "./BaseTool"
interface UseMcpToolParams {
server_name: string
tool_name: string
arguments?: Record<string, unknown>
}
type ValidationResult =
| { isValid: false }
| {
isValid: true
serverName: string
toolName: string
parsedArguments?: Record<string, unknown>
}
export class UseMcpToolTool extends BaseTool<"use_mcp_tool"> {
readonly name = "use_mcp_tool" as const
async execute(params: UseMcpToolParams, task: Task, callbacks: ToolCallbacks): Promise<void> {
const { askApproval, handleError, pushToolResult } = callbacks
try {
// Validate parameters
const validation = await this.validateParams(task, params, pushToolResult)
if (!validation.isValid) {
return
}
const { serverName, toolName, parsedArguments } = validation
// Validate that the tool exists on the server
const toolValidation = await this.validateToolExists(task, serverName, toolName, pushToolResult)
if (!toolValidation.isValid) {
return
}
// Reset mistake count on successful validation
task.consecutiveMistakeCount = 0
// Get user approval
const completeMessage = JSON.stringify({
type: "use_mcp_tool",
serverName,
toolName,
arguments: params.arguments ? JSON.stringify(params.arguments) : undefined,
} satisfies ClineAskUseMcpServer)
const executionId = task.lastMessageTs?.toString() ?? Date.now().toString()
const didApprove = await askApproval("use_mcp_server", completeMessage)
if (!didApprove) {
return
}
// Execute the tool and process results
await this.executeToolAndProcessResult(
task,
serverName,
toolName,
parsedArguments,
executionId,
pushToolResult,
)
} catch (error) {
await handleError("executing MCP tool", error as Error)
}
}
override async handlePartial(task: Task, block: ToolUse<"use_mcp_tool">): Promise<void> {
const params = block.params
const partialMessage = JSON.stringify({
type: "use_mcp_tool",
serverName: params.server_name ?? "",
toolName: params.tool_name ?? "",
arguments: params.arguments,
} satisfies ClineAskUseMcpServer)
await task.ask("use_mcp_server", partialMessage, true).catch(() => {})
}
private async validateParams(
task: Task,
params: UseMcpToolParams,
pushToolResult: (content: string) => void,
): Promise<ValidationResult> {
if (!params.server_name) {
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
pushToolResult(await task.sayAndCreateMissingParamError("use_mcp_tool", "server_name"))
return { isValid: false }
}
if (!params.tool_name) {
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
pushToolResult(await task.sayAndCreateMissingParamError("use_mcp_tool", "tool_name"))
return { isValid: false }
}
// Native-only: arguments are already a structured object.
let parsedArguments: Record<string, unknown> | undefined
if (params.arguments !== undefined) {
if (typeof params.arguments !== "object" || params.arguments === null || Array.isArray(params.arguments)) {
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
await task.say("error", t("mcp:errors.invalidJsonArgument", { toolName: params.tool_name }))
task.didToolFailInCurrentTurn = true
pushToolResult(
formatResponse.toolError(
formatResponse.invalidMcpToolArgumentError(params.server_name, params.tool_name),
),
)
return { isValid: false }
}
parsedArguments = params.arguments
}
return {
isValid: true,
serverName: params.server_name,
toolName: params.tool_name,
parsedArguments,
}
}
private async validateToolExists(
task: Task,
serverName: string,
toolName: string,
pushToolResult: (content: string) => void,
): Promise<{ isValid: boolean; availableTools?: string[] }> {
try {
// Get the MCP hub to access server information
const provider = task.providerRef.deref()
const mcpHub = provider?.getMcpHub()
if (!mcpHub) {
// If we can't get the MCP hub, we can't validate, so proceed with caution
return { isValid: true }
}
// Get all servers to find the specific one
const servers = mcpHub.getAllServers()
const server = servers.find((s) => s.name === serverName)
if (!server) {
// Fail fast when server is unknown
const availableServersArray = servers.map((s) => s.name)
const availableServers =
availableServersArray.length > 0 ? availableServersArray.join(", ") : "No servers available"
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
await task.say("error", t("mcp:errors.serverNotFound", { serverName, availableServers }))
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.unknownMcpServerError(serverName, availableServersArray))
return { isValid: false, availableTools: [] }
}
// Check if the server has tools defined
if (!server.tools || server.tools.length === 0) {
// No tools available on this server
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
await task.say(
"error",
t("mcp:errors.toolNotFound", {
toolName,
serverName,
availableTools: "No tools available",
}),
)
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.unknownMcpToolError(serverName, toolName, []))
return { isValid: false, availableTools: [] }
}
// Check if the requested tool exists
const tool = server.tools.find((tool) => tool.name === toolName)
if (!tool) {
// Tool not found - provide list of available tools
const availableToolNames = server.tools.map((tool) => tool.name)
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
await task.say(
"error",
t("mcp:errors.toolNotFound", {
toolName,
serverName,
availableTools: availableToolNames.join(", "),
}),
)
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.unknownMcpToolError(serverName, toolName, availableToolNames))
return { isValid: false, availableTools: availableToolNames }
}
// Check if the tool is disabled (enabledForPrompt is false)
if (tool.enabledForPrompt === false) {
// Tool is disabled - only show enabled tools
const enabledTools = server.tools.filter((t) => t.enabledForPrompt !== false)
const enabledToolNames = enabledTools.map((t) => t.name)
task.consecutiveMistakeCount++
task.recordToolError("use_mcp_tool")
await task.say(
"error",
t("mcp:errors.toolDisabled", {
toolName,
serverName,
availableTools:
enabledToolNames.length > 0 ? enabledToolNames.join(", ") : "No enabled tools available",
}),
)
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.unknownMcpToolError(serverName, toolName, enabledToolNames))
return { isValid: false, availableTools: enabledToolNames }
}
// Tool exists and is enabled
return { isValid: true, availableTools: server.tools.map((tool) => tool.name) }
} catch (error) {
// If there's an error during validation, log it but don't block the tool execution
// The actual tool call might still fail with a proper error
console.error("Error validating MCP tool existence:", error)
return { isValid: true }
}
}
private async sendExecutionStatus(task: Task, status: McpExecutionStatus): Promise<void> {
const clineProvider = await task.providerRef.deref()
clineProvider?.postMessageToWebview({
type: "mcpExecutionStatus",
text: JSON.stringify(status),
})
}
private processToolContent(toolResult: any): { text: string; images: string[] } {
if (!toolResult?.content || toolResult.content.length === 0) {
return { text: "", images: [] }
}
const images: string[] = []
const textContent = toolResult.content
.map((item: any) => {
if (item.type === "text") {
return item.text
}
if (item.type === "resource") {
const { blob: _, ...rest } = item.resource
return JSON.stringify(rest, null, 2)
}
if (item.type === "image") {
// Handle image content (MCP image content has mimeType and data properties)
if (item.mimeType && item.data) {
if (item.data.startsWith("data:")) {
images.push(item.data)
} else {
images.push(`data:${item.mimeType};base64,${item.data}`)
}
}
return ""
}
return ""
})
.filter(Boolean)
.join("\n\n")
return { text: textContent, images }
}
private async executeToolAndProcessResult(
task: Task,
serverName: string,
toolName: string,
parsedArguments: Record<string, unknown> | undefined,
executionId: string,
pushToolResult: (content: string | Array<any>) => void,
): Promise<void> {
await task.say("mcp_server_request_started")
// Send started status
await this.sendExecutionStatus(task, {
executionId,
status: "started",
serverName,
toolName,
})
const toolResult = await task.providerRef.deref()?.getMcpHub()?.callTool(serverName, toolName, parsedArguments)
let toolResultPretty = "(No response)"
let images: string[] = []
if (toolResult) {
const { text: outputText, images: extractedImages } = this.processToolContent(toolResult)
images = extractedImages
if (outputText || images.length > 0) {
await this.sendExecutionStatus(task, {
executionId,
status: "output",
response: outputText || (images.length > 0 ? `[${images.length} image(s)]` : ""),
})
toolResultPretty =
(toolResult.isError ? "Error:\n" : "") +
(outputText || (images.length > 0 ? `[${images.length} image(s) received]` : ""))
}
// Send completion status
await this.sendExecutionStatus(task, {
executionId,
status: toolResult.isError ? "error" : "completed",
response: toolResultPretty,
error: toolResult.isError ? "Error executing MCP tool" : undefined,
})
} else {
// Send error status if no result
await this.sendExecutionStatus(task, {
executionId,
status: "error",
error: "No response from MCP server",
})
}
await task.say("mcp_server_response", toolResultPretty, images)
pushToolResult(formatResponse.toolResult(toolResultPretty, images))
}
}
export const useMcpToolTool = new UseMcpToolTool()