| 1 | import { ContextItem, Tool, ToolCall, ToolExtras } from ".."; |
| 2 | import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton"; |
| 3 | import { DataLogger } from "../data/log"; |
| 4 | import { canParseUrl } from "../util/url"; |
| 5 | import { BuiltInToolNames } from "./builtIn"; |
| 6 | |
| 7 | import { createNewFileImpl } from "./implementations/createNewFile"; |
| 8 | import { createRuleBlockImpl } from "./implementations/createRuleBlock"; |
| 9 | import { fetchUrlContentImpl } from "./implementations/fetchUrlContent"; |
| 10 | import { fileGlobSearchImpl } from "./implementations/globSearch"; |
| 11 | import { grepSearchImpl } from "./implementations/grepSearch"; |
| 12 | import { lsToolImpl } from "./implementations/lsTool"; |
| 13 | import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; |
| 14 | import { readFileImpl } from "./implementations/readFile"; |
| 15 | import { requestRuleImpl } from "./implementations/requestRule"; |
| 16 | import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; |
| 17 | import { searchWebImpl } from "./implementations/searchWeb"; |
| 18 | import { viewDiffImpl } from "./implementations/viewDiff"; |
| 19 | import { safeParseToolCallArgs } from "./parseArgs"; |
| 20 | |
| 21 | async function callHttpTool( |
| 22 | url: string, |
| 23 | args: any, |
| 24 | extras: ToolExtras, |
| 25 | ): Promise<ContextItem[]> { |
| 26 | const response = await extras.fetch(url, { |
| 27 | method: "POST", |
| 28 | headers: { |
| 29 | "Content-Type": "application/json", |
| 30 | }, |
| 31 | body: JSON.stringify({ |
| 32 | arguments: args, |
| 33 | }), |
| 34 | }); |
| 35 | |
| 36 | const data = await response.json(); |
| 37 | |
| 38 | if (!response.ok) { |
| 39 | throw new Error(`Failed to call tool at ${url}:\n${JSON.stringify(data)}`); |
| 40 | } |
| 41 | |
| 42 | return data.output; |
| 43 | } |
| 44 | |
| 45 | export function encodeMCPToolUri(mcpId: string, toolName: string): string { |
| 46 | return `mcp://${encodeURIComponent(mcpId)}/${encodeURIComponent(toolName)}`; |
| 47 | } |
| 48 | |
| 49 | export function decodeMCPToolUri(uri: string): [string, string] | null { |
| 50 | const url = new URL(uri); |
| 51 | if (url.protocol !== "mcp:") { |
| 52 | return null; |
| 53 | } |
| 54 | return [ |
| 55 | decodeURIComponent(url.hostname), |
| 56 | decodeURIComponent(url.pathname).slice(1), // to remove leading '/' |
| 57 | ]; |
| 58 | } |
| 59 | |
| 60 | async function callToolFromUri( |
| 61 | uri: string, |
| 62 | args: any, |
| 63 | extras: ToolExtras, |
| 64 | ): Promise<ContextItem[]> { |
| 65 | const parseable = canParseUrl(uri); |
| 66 | if (!parseable) { |
| 67 | throw new Error(`Invalid URI: ${uri}`); |
| 68 | } |
| 69 | const parsedUri = new URL(uri); |
| 70 | |
| 71 | switch (parsedUri?.protocol) { |
| 72 | case "http:": |
| 73 | case "https:": |
| 74 | return callHttpTool(uri, args, extras); |
| 75 | case "mcp:": |
| 76 | const decoded = decodeMCPToolUri(uri); |
| 77 | if (!decoded) { |
| 78 | throw new Error(`Invalid MCP tool URI: ${uri}`); |
| 79 | } |
| 80 | const [mcpId, toolName] = decoded; |
| 81 | const client = MCPManagerSingleton.getInstance().getConnection(mcpId); |
| 82 | |
| 83 | if (!client) { |
| 84 | throw new Error("MCP connection not found"); |
| 85 | } |
| 86 | const response = await client.client.callTool({ |
| 87 | name: toolName, |
| 88 | arguments: args, |
| 89 | }); |
| 90 | |
| 91 | if (response.isError === true) { |
| 92 | throw new Error(JSON.stringify(response.content)); |
| 93 | } |
| 94 | |
| 95 | const contextItems: ContextItem[] = []; |
| 96 | (response.content as any).forEach((item: any) => { |
| 97 | if (item.type === "text") { |
| 98 | contextItems.push({ |
| 99 | name: extras.tool.displayTitle, |
| 100 | description: "Tool output", |
| 101 | content: item.text, |
| 102 | icon: extras.tool.faviconUrl, |
| 103 | }); |
| 104 | } else if (item.type === "resource") { |
| 105 | // TODO resource change subscribers https://modelcontextprotocol.io/docs/concepts/resources |
| 106 | if (item.resource?.blob) { |
| 107 | contextItems.push({ |
| 108 | name: extras.tool.displayTitle, |
| 109 | description: "MCP Item Error", |
| 110 | content: |
| 111 | "Error: tool call received unsupported blob resource item", |
| 112 | icon: extras.tool.faviconUrl, |
| 113 | }); |
| 114 | } |
| 115 | // TODO account for mimetype? // const mimeType = item.resource.mimeType |
| 116 | // const uri = item.resource.uri; |
| 117 | contextItems.push({ |
| 118 | name: extras.tool.displayTitle, |
| 119 | description: "Tool output", |
| 120 | content: item.resource.text, |
| 121 | icon: extras.tool.faviconUrl, |
| 122 | }); |
| 123 | } else { |
| 124 | contextItems.push({ |
| 125 | name: extras.tool.displayTitle, |
| 126 | description: "MCP Item Error", |
| 127 | content: `Error: tool call received unsupported item of type "${item.type}"`, |
| 128 | icon: extras.tool.faviconUrl, |
| 129 | }); |
| 130 | } |
| 131 | }); |
| 132 | return contextItems; |
| 133 | default: |
| 134 | throw new Error(`Unsupported protocol: ${parsedUri?.protocol}`); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | async function callBuiltInTool( |
| 139 | functionName: string, |
| 140 | args: any, |
| 141 | extras: ToolExtras, |
| 142 | ): Promise<ContextItem[]> { |
| 143 | switch (functionName) { |
| 144 | case BuiltInToolNames.ReadFile: |
| 145 | return await readFileImpl(args, extras); |
| 146 | case BuiltInToolNames.CreateNewFile: |
| 147 | return await createNewFileImpl(args, extras); |
| 148 | case BuiltInToolNames.GrepSearch: |
| 149 | return await grepSearchImpl(args, extras); |
| 150 | case BuiltInToolNames.FileGlobSearch: |
| 151 | return await fileGlobSearchImpl(args, extras); |
| 152 | case BuiltInToolNames.RunTerminalCommand: |
| 153 | return await runTerminalCommandImpl(args, extras); |
| 154 | case BuiltInToolNames.SearchWeb: |
| 155 | return await searchWebImpl(args, extras); |
| 156 | case BuiltInToolNames.FetchUrlContent: |
| 157 | return await fetchUrlContentImpl(args, extras); |
| 158 | case BuiltInToolNames.ViewDiff: |
| 159 | return await viewDiffImpl(args, extras); |
| 160 | case BuiltInToolNames.LSTool: |
| 161 | return await lsToolImpl(args, extras); |
| 162 | case BuiltInToolNames.ReadCurrentlyOpenFile: |
| 163 | return await readCurrentlyOpenFileImpl(args, extras); |
| 164 | case BuiltInToolNames.CreateRuleBlock: |
| 165 | return await createRuleBlockImpl(args, extras); |
| 166 | case BuiltInToolNames.RequestRule: |
| 167 | return await requestRuleImpl(args, extras); |
| 168 | default: |
| 169 | throw new Error(`Tool "${functionName}" not found`); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | function logToolUsage( |
| 174 | toolCall: ToolCall, |
| 175 | args: Record<string, any>, |
| 176 | contextItems: ContextItem[], |
| 177 | success: boolean, |
| 178 | ) { |
| 179 | void DataLogger.getInstance().logDevData({ |
| 180 | name: "toolUsage", |
| 181 | data: { |
| 182 | toolCallId: toolCall.id, |
| 183 | functionName: toolCall.function.name, |
| 184 | functionArgs: toolCall.function.arguments, |
| 185 | toolCallArgs: args, |
| 186 | parsedArgs: args, |
| 187 | output: contextItems, |
| 188 | succeeded: success, |
| 189 | }, |
| 190 | }); |
| 191 | } |
| 192 | |
| 193 | // Handles calls for core/non-client tools |
| 194 | // Returns an error context item if the tool call fails |
| 195 | // Note: Edit tool is handled on client |
| 196 | export async function callTool( |
| 197 | tool: Tool, |
| 198 | toolCall: ToolCall, |
| 199 | extras: ToolExtras, |
| 200 | ): Promise<{ |
| 201 | contextItems: ContextItem[]; |
| 202 | errorMessage: string | undefined; |
| 203 | }> { |
| 204 | try { |
| 205 | const args = safeParseToolCallArgs(toolCall); |
| 206 | const contextItems = tool.uri |
| 207 | ? await callToolFromUri(tool.uri, args, extras) |
| 208 | : await callBuiltInTool(tool.function.name, args, extras); |
| 209 | if (tool.faviconUrl) { |
| 210 | contextItems.forEach((item) => { |
| 211 | item.icon = tool.faviconUrl; |
| 212 | }); |
| 213 | } |
| 214 | logToolUsage(toolCall, args, contextItems, true); |
| 215 | return { |
| 216 | contextItems, |
| 217 | errorMessage: undefined, |
| 218 | }; |
| 219 | } catch (e) { |
| 220 | let errorMessage = `${e}`; |
| 221 | if (e instanceof Error) { |
| 222 | errorMessage = e.message; |
| 223 | } |
| 224 | logToolUsage(toolCall, {}, [], false); |
| 225 | return { |
| 226 | contextItems: [], |
| 227 | errorMessage, |
| 228 | }; |
| 229 | } |
| 230 | } |