Elffuss BraidHub

kikocis/continue public

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