Elffuss BraidHub

kikocis/continue public

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