Elffuss BraidHub

kikocis/continue public

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