Elffuss BraidHub

kikocis/continue public

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