Elffuss BraidHub

kikocis/continue public

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