Elffuss BraidHub

kikocis/continue public

5aed8ce6ba7e · 6.7 KiBRawPermalink
1import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
2import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
3import { canParseUrl } from "../util/url";
4import { BuiltInToolNames } from "./builtIn";
5
6import { codebaseToolImpl } from "./implementations/codebaseTool";
7import { createNewFileImpl } from "./implementations/createNewFile";
8import { createRuleBlockImpl } from "./implementations/createRuleBlock";
9import { fetchUrlContentImpl } from "./implementations/fetchUrlContent";
10import { fileGlobSearchImpl } from "./implementations/globSearch";
11import { grepSearchImpl } from "./implementations/grepSearch";
12import { lsToolImpl } from "./implementations/lsTool";
13import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
14import { readFileImpl } from "./implementations/readFile";
15import { requestRuleImpl } from "./implementations/requestRule";
16import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
17import { searchWebImpl } from "./implementations/searchWeb";
18import { viewDiffImpl } from "./implementations/viewDiff";
19import { safeParseToolCallArgs } from "./parseArgs";
20
21async 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
45export function encodeMCPToolUri(mcpId: string, toolName: string): string {
46 return `mcp://${encodeURIComponent(mcpId)}/${encodeURIComponent(toolName)}`;
47}
48
49export 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
60async 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
138async 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 case BuiltInToolNames.CodebaseTool:
169 return await codebaseToolImpl(args, extras);
170 default:
171 throw new Error(`Tool "${functionName}" not found`);
172 }
173}
174
175// Handles calls for core/non-client tools
176// Returns an error context item if the tool call fails
177// Note: Edit tool is handled on client
178export async function callTool(
179 tool: Tool,
180 toolCall: ToolCall,
181 extras: ToolExtras,
182): Promise<{
183 contextItems: ContextItem[];
184 errorMessage: string | undefined;
185}> {
186 try {
187 const args = safeParseToolCallArgs(toolCall);
188 const contextItems = tool.uri
189 ? await callToolFromUri(tool.uri, args, extras)
190 : await callBuiltInTool(tool.function.name, args, extras);
191 if (tool.faviconUrl) {
192 contextItems.forEach((item) => {
193 item.icon = tool.faviconUrl;
194 });
195 }
196 return {
197 contextItems,
198 errorMessage: undefined,
199 };
200 } catch (e) {
201 let errorMessage = `${e}`;
202 if (e instanceof Error) {
203 errorMessage = e.message;
204 }
205 return {
206 contextItems: [],
207 errorMessage,
208 };
209 }
210}