Elffuss BraidHub

kikocis/continue public

main · 5.9 KiBRawPermalink
1import {
2 claudeCodeLikeConfigFileSchema,
3 claudeDesktopLikeConfigFileSchema,
4 ConfigValidationError,
5 convertJsonMcpConfigToYamlMcpConfig,
6 McpJsonConfig,
7 mcpServersJsonSchema,
8 RequestOptions,
9} from "@continuedev/config-yaml";
10import * as JSONC from "comment-json";
11import ignore from "ignore";
12import { IDE, InternalMcpOptions } from "../../..";
13import { convertYamlMcpConfigToInternalMcpOptions } from "../../../config/yaml/yamlToContinueConfig";
14import {
15 DEFAULT_IGNORE_DIRS,
16 DEFAULT_IGNORE_FILETYPES,
17} from "../../../indexing/ignore";
18import { walkDir } from "../../../indexing/walkDir";
19import { deduplicateArray } from "../../../util";
20import { getGlobalFolderWithName } from "../../../util/paths";
21import { localPathToUri } from "../../../util/pathToUri";
22import { getUriPathBasename, joinPathsToUri } from "../../../util/uri";
23
24/**
25 * Loads MCP configs from JSON files in ~/.continue/mcpServers and workspace .continue/mcpServers
26 */
27export async function loadJsonMcpConfigs(
28 ide: IDE,
29 includeGlobal: boolean,
30 globalRequestOptions: RequestOptions | undefined = undefined,
31): Promise<{
32 mcpServers: InternalMcpOptions[];
33 errors: ConfigValidationError[];
34}> {
35 const errors: ConfigValidationError[] = [];
36
37 // Get dirs
38 const workspaceDirs = await ide.getWorkspaceDirs();
39 const mcpDirs = workspaceDirs.map((dir) =>
40 joinPathsToUri(dir, ".continue", "mcpServers"),
41 );
42 if (includeGlobal) {
43 mcpDirs.push(localPathToUri(getGlobalFolderWithName("mcpServers")));
44 }
45
46 // Get json files and their contents
47 const overrideDefaultIgnores = ignore()
48 .add(
49 DEFAULT_IGNORE_FILETYPES.filter(
50 (val) => !["config.json", "settings.json"].includes(val),
51 ),
52 )
53 .add(DEFAULT_IGNORE_DIRS);
54
55 const jsonFiles: { uri: string; content: string }[] = [];
56
57 await Promise.all(
58 mcpDirs.map(async (dir) => {
59 const exists = await ide.fileExists(dir);
60 if (!exists) {
61 return;
62 }
63 try {
64 const uris = await walkDir(dir, ide, {
65 overrideDefaultIgnores,
66 source: "get mcp json files",
67 });
68 const jsonUris = uris.filter((uri) => uri.endsWith(".json"));
69 await Promise.all(
70 jsonUris.map(async (uri) => {
71 try {
72 const content = await ide.readFile(uri);
73 jsonFiles.push({ uri, content });
74 } catch (e) {
75 errors.push({
76 fatal: false,
77 message: `Failed to read MCP server JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`,
78 });
79 }
80 }),
81 );
82 } catch (e) {
83 errors.push({
84 fatal: false,
85 message: `Failed to check for MCP JSON files in ${dir}: ${e instanceof Error ? e.message : String(e)}`,
86 });
87 }
88 }),
89 );
90
91 const validJsonConfigs: {
92 name: string;
93 mcpJson: McpJsonConfig;
94 uri: string;
95 }[] = [];
96 for (const { content, uri } of jsonFiles) {
97 try {
98 const json = JSONC.parse(content);
99 // Try parsing as a file with mcpServers and multiple servers (claude code/desktop-esque format)
100 const claudeCodeFileParsed =
101 claudeCodeLikeConfigFileSchema.safeParse(json);
102 if (claudeCodeFileParsed.success) {
103 if (claudeCodeFileParsed.data.mcpServers) {
104 validJsonConfigs.push(
105 ...Object.entries(claudeCodeFileParsed.data.mcpServers).map(
106 ([name, mcpJson]) => ({
107 name,
108 mcpJson,
109 uri,
110 }),
111 ),
112 );
113 }
114 const projectServers = Object.values(
115 claudeCodeFileParsed.data.projects,
116 ).map((v) => v.mcpServers);
117 for (const mcpServers of projectServers) {
118 if (mcpServers) {
119 validJsonConfigs.push(
120 ...Object.entries(mcpServers).map(([name, mcpJson]) => ({
121 name,
122 mcpJson,
123 uri,
124 })),
125 );
126 }
127 }
128 } else {
129 const claudeDesktopFileParsed =
130 claudeDesktopLikeConfigFileSchema.safeParse(json);
131 if (claudeDesktopFileParsed.success) {
132 validJsonConfigs.push(
133 ...Object.entries(claudeDesktopFileParsed.data.mcpServers).map(
134 ([name, mcpJson]) => ({
135 name,
136 mcpJson,
137 uri,
138 }),
139 ),
140 );
141 } else {
142 // Try parsing as single JSON file
143 const singleConfigParsed = mcpServersJsonSchema.safeParse(json);
144 if (singleConfigParsed.success) {
145 validJsonConfigs.push({
146 mcpJson: singleConfigParsed.data,
147 name: getUriPathBasename(uri).replace(".json", ""),
148 uri,
149 });
150 } else {
151 errors.push({
152 fatal: false,
153 message: `MCP JSON file at ${uri} doesn't match a supported MCP JSON configuration format`,
154 });
155 }
156 }
157 }
158 } catch (e) {
159 errors.push({
160 fatal: false,
161 message: `Error parsing MCP JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`,
162 });
163 }
164 }
165
166 // De-duplicate
167 const deduplicatedJsonConfigs = deduplicateArray(
168 validJsonConfigs,
169 (a, b) => a.name === b.name,
170 );
171
172 // Two levels of conversion for now.
173 const yamlConfigs = deduplicatedJsonConfigs.map((c) => {
174 const { warnings, yamlConfig } = convertJsonMcpConfigToYamlMcpConfig(
175 c.name,
176 c.mcpJson,
177 );
178 return {
179 warnings,
180 yamlConfig: {
181 ...yamlConfig,
182 sourceFile: c.uri,
183 },
184 };
185 });
186
187 const mcpServers = yamlConfigs.map((c) => {
188 errors.push(
189 ...c.warnings.map((warning) => ({
190 fatal: false,
191 message: warning,
192 })),
193 );
194 return convertYamlMcpConfigToInternalMcpOptions(
195 c.yamlConfig,
196 globalRequestOptions,
197 );
198 });
199 // Parse and convert files
200 return {
201 mcpServers,
202 errors,
203 };
204}