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