actions.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. "use server";
  2. import {
  3. createClient,
  4. executeRequest,
  5. listTools,
  6. removeClient,
  7. } from "./client";
  8. import { MCPClientLogger } from "./logger";
  9. import {
  10. DEFAULT_MCP_CONFIG,
  11. McpClientData,
  12. McpConfigData,
  13. McpRequestMessage,
  14. ServerConfig,
  15. ServerStatusResponse,
  16. } from "./types";
  17. import fs from "fs/promises";
  18. import path from "path";
  19. const logger = new MCPClientLogger("MCP Actions");
  20. const CONFIG_PATH = path.join(process.cwd(), "app/mcp/mcp_config.json");
  21. const clientsMap = new Map<string, McpClientData>();
  22. // 获取客户端状态
  23. export async function getClientStatus(
  24. clientId: string,
  25. ): Promise<ServerStatusResponse> {
  26. const status = clientsMap.get(clientId);
  27. const config = await getMcpConfigFromFile();
  28. const serverConfig = config.mcpServers[clientId];
  29. // 如果配置中不存在该服务器
  30. if (!serverConfig) {
  31. return { status: "undefined", errorMsg: null };
  32. }
  33. // 如果服务器配置为暂停状态
  34. if (serverConfig.status === "paused") {
  35. return { status: "paused", errorMsg: null };
  36. }
  37. // 如果 clientsMap 中没有记录
  38. if (!status) {
  39. return { status: "undefined", errorMsg: null };
  40. }
  41. // 如果有错误
  42. if (status.errorMsg) {
  43. return { status: "error", errorMsg: status.errorMsg };
  44. }
  45. // 如果客户端正常运行
  46. if (status.client) {
  47. return { status: "active", errorMsg: null };
  48. }
  49. // 如果客户端不存在
  50. return { status: "error", errorMsg: "Client not found" };
  51. }
  52. // 获取客户端工具
  53. export async function getClientTools(clientId: string) {
  54. return clientsMap.get(clientId)?.tools ?? null;
  55. }
  56. // 获取可用客户端数量
  57. export async function getAvailableClientsCount() {
  58. let count = 0;
  59. clientsMap.forEach((map) => !map.errorMsg && count++);
  60. return count;
  61. }
  62. // 获取所有客户端工具
  63. export async function getAllTools() {
  64. const result = [];
  65. for (const [clientId, status] of clientsMap.entries()) {
  66. result.push({
  67. clientId,
  68. tools: status.tools,
  69. });
  70. }
  71. return result;
  72. }
  73. // 初始化单个客户端
  74. async function initializeSingleClient(
  75. clientId: string,
  76. serverConfig: ServerConfig,
  77. ) {
  78. // 如果服务器状态是暂停,则不初始化
  79. if (serverConfig.status === "paused") {
  80. logger.info(`Skipping initialization for paused client [${clientId}]`);
  81. return;
  82. }
  83. logger.info(`Initializing client [${clientId}]...`);
  84. try {
  85. const client = await createClient(clientId, serverConfig);
  86. const tools = await listTools(client);
  87. clientsMap.set(clientId, { client, tools, errorMsg: null });
  88. logger.success(`Client [${clientId}] initialized successfully`);
  89. } catch (error) {
  90. clientsMap.set(clientId, {
  91. client: null,
  92. tools: null,
  93. errorMsg: error instanceof Error ? error.message : String(error),
  94. });
  95. logger.error(`Failed to initialize client [${clientId}]: ${error}`);
  96. }
  97. }
  98. // 初始化系统
  99. export async function initializeMcpSystem() {
  100. logger.info("MCP Actions starting...");
  101. try {
  102. const config = await getMcpConfigFromFile();
  103. // 初始化所有客户端
  104. for (const [clientId, serverConfig] of Object.entries(config.mcpServers)) {
  105. await initializeSingleClient(clientId, serverConfig);
  106. }
  107. return config;
  108. } catch (error) {
  109. logger.error(`Failed to initialize MCP system: ${error}`);
  110. throw error;
  111. }
  112. }
  113. // 添加服务器
  114. export async function addMcpServer(clientId: string, config: ServerConfig) {
  115. try {
  116. const currentConfig = await getMcpConfigFromFile();
  117. const newConfig = {
  118. ...currentConfig,
  119. mcpServers: {
  120. ...currentConfig.mcpServers,
  121. [clientId]: config,
  122. },
  123. };
  124. await updateMcpConfig(newConfig);
  125. // 只初始化新添加的服务器
  126. await initializeSingleClient(clientId, config);
  127. return newConfig;
  128. } catch (error) {
  129. logger.error(`Failed to add server [${clientId}]: ${error}`);
  130. throw error;
  131. }
  132. }
  133. // 暂停服务器
  134. export async function pauseMcpServer(clientId: string) {
  135. try {
  136. const currentConfig = await getMcpConfigFromFile();
  137. const serverConfig = currentConfig.mcpServers[clientId];
  138. if (!serverConfig) {
  139. throw new Error(`Server ${clientId} not found`);
  140. }
  141. // 先更新配置
  142. const newConfig: McpConfigData = {
  143. ...currentConfig,
  144. mcpServers: {
  145. ...currentConfig.mcpServers,
  146. [clientId]: {
  147. ...serverConfig,
  148. status: "paused" as const,
  149. },
  150. },
  151. };
  152. await updateMcpConfig(newConfig);
  153. // 然后关闭客户端
  154. const client = clientsMap.get(clientId);
  155. if (client?.client) {
  156. await removeClient(client.client);
  157. }
  158. clientsMap.delete(clientId);
  159. return newConfig;
  160. } catch (error) {
  161. logger.error(`Failed to pause server [${clientId}]: ${error}`);
  162. throw error;
  163. }
  164. }
  165. // 恢复服务器
  166. export async function resumeMcpServer(clientId: string): Promise<boolean> {
  167. try {
  168. const currentConfig = await getMcpConfigFromFile();
  169. const serverConfig = currentConfig.mcpServers[clientId];
  170. if (!serverConfig) {
  171. throw new Error(`Server ${clientId} not found`);
  172. }
  173. // 先尝试初始化客户端
  174. logger.info(`Trying to initialize client [${clientId}]...`);
  175. try {
  176. const client = await createClient(clientId, serverConfig);
  177. const tools = await listTools(client);
  178. clientsMap.set(clientId, { client, tools, errorMsg: null });
  179. logger.success(`Client [${clientId}] initialized successfully`);
  180. // 初始化成功后更新配置
  181. const newConfig: McpConfigData = {
  182. ...currentConfig,
  183. mcpServers: {
  184. ...currentConfig.mcpServers,
  185. [clientId]: {
  186. ...serverConfig,
  187. status: "active" as const,
  188. },
  189. },
  190. };
  191. await updateMcpConfig(newConfig);
  192. // 再次确认状态
  193. const status = await getClientStatus(clientId);
  194. return status.status === "active";
  195. } catch (error) {
  196. const currentConfig = await getMcpConfigFromFile();
  197. const serverConfig = currentConfig.mcpServers[clientId];
  198. // 如果配置中存在该服务器,则更新其状态为 error
  199. if (serverConfig) {
  200. serverConfig.status = "error";
  201. await updateMcpConfig(currentConfig);
  202. }
  203. // 初始化失败
  204. clientsMap.set(clientId, {
  205. client: null,
  206. tools: null,
  207. errorMsg: error instanceof Error ? error.message : String(error),
  208. });
  209. logger.error(`Failed to initialize client [${clientId}]: ${error}`);
  210. return false;
  211. }
  212. } catch (error) {
  213. logger.error(`Failed to resume server [${clientId}]: ${error}`);
  214. throw error;
  215. }
  216. }
  217. // 移除服务器
  218. export async function removeMcpServer(clientId: string) {
  219. try {
  220. const currentConfig = await getMcpConfigFromFile();
  221. const { [clientId]: _, ...rest } = currentConfig.mcpServers;
  222. const newConfig = {
  223. ...currentConfig,
  224. mcpServers: rest,
  225. };
  226. await updateMcpConfig(newConfig);
  227. // 关闭并移除客户端
  228. const client = clientsMap.get(clientId);
  229. if (client?.client) {
  230. await removeClient(client.client);
  231. }
  232. clientsMap.delete(clientId);
  233. return newConfig;
  234. } catch (error) {
  235. logger.error(`Failed to remove server [${clientId}]: ${error}`);
  236. throw error;
  237. }
  238. }
  239. // 重启所有客户端
  240. export async function restartAllClients() {
  241. logger.info("Restarting all clients...");
  242. try {
  243. // 关闭所有客户端
  244. for (const client of clientsMap.values()) {
  245. if (client.client) {
  246. await removeClient(client.client);
  247. }
  248. }
  249. // 清空状态
  250. clientsMap.clear();
  251. // 重新初始化
  252. const config = await getMcpConfigFromFile();
  253. for (const [clientId, serverConfig] of Object.entries(config.mcpServers)) {
  254. await initializeSingleClient(clientId, serverConfig);
  255. }
  256. return config;
  257. } catch (error) {
  258. logger.error(`Failed to restart clients: ${error}`);
  259. throw error;
  260. }
  261. }
  262. // 执行 MCP 请求
  263. export async function executeMcpAction(
  264. clientId: string,
  265. request: McpRequestMessage,
  266. ) {
  267. try {
  268. const client = clientsMap.get(clientId);
  269. if (!client?.client) {
  270. throw new Error(`Client ${clientId} not found`);
  271. }
  272. logger.info(`Executing request for [${clientId}]`);
  273. return await executeRequest(client.client, request);
  274. } catch (error) {
  275. logger.error(`Failed to execute request for [${clientId}]: ${error}`);
  276. throw error;
  277. }
  278. }
  279. // 获取 MCP 配置文件
  280. export async function getMcpConfigFromFile(): Promise<McpConfigData> {
  281. try {
  282. const configStr = await fs.readFile(CONFIG_PATH, "utf-8");
  283. return JSON.parse(configStr);
  284. } catch (error) {
  285. logger.error(`Failed to load MCP config, using default config: ${error}`);
  286. return DEFAULT_MCP_CONFIG;
  287. }
  288. }
  289. // 更新 MCP 配置文件
  290. async function updateMcpConfig(config: McpConfigData): Promise<void> {
  291. try {
  292. await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2));
  293. } catch (error) {
  294. throw error;
  295. }
  296. }
  297. // 重新初始化单个客户端
  298. export async function reinitializeClient(clientId: string) {
  299. const config = await getMcpConfigFromFile();
  300. const serverConfig = config.mcpServers[clientId];
  301. if (!serverConfig) {
  302. throw new Error(`Server config not found for client ${clientId}`);
  303. }
  304. await initializeSingleClient(clientId, serverConfig);
  305. }