Elffuss BraidHub

kikocis/continue public

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