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