Elffuss BraidHub

kikocis/continue public

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