actions.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use server";
  2. import { createClient, executeRequest } from "./client";
  3. import { MCPClientLogger } from "./logger";
  4. import conf from "./mcp_config.json";
  5. import { McpRequestMessage } from "./types";
  6. const logger = new MCPClientLogger("MCP Actions");
  7. // Use Map to store all clients
  8. const clientsMap = new Map<string, any>();
  9. // Whether initialized
  10. let initialized = false;
  11. // Store failed clients
  12. let errorClients: string[] = [];
  13. // Initialize all configured clients
  14. export async function initializeMcpClients() {
  15. // If already initialized, return
  16. if (initialized) {
  17. return;
  18. }
  19. logger.info("Starting to initialize MCP clients...");
  20. // Initialize all clients, key is clientId, value is client config
  21. for (const [clientId, config] of Object.entries(conf.mcpServers)) {
  22. try {
  23. logger.info(`Initializing MCP client: ${clientId}`);
  24. const client = await createClient(config, clientId);
  25. clientsMap.set(clientId, client);
  26. logger.success(`Client ${clientId} initialized`);
  27. } catch (error) {
  28. errorClients.push(clientId);
  29. logger.error(`Failed to initialize client ${clientId}: ${error}`);
  30. }
  31. }
  32. initialized = true;
  33. if (errorClients.length > 0) {
  34. logger.warn(`Failed to initialize clients: ${errorClients.join(", ")}`);
  35. } else {
  36. logger.success("All MCP clients initialized");
  37. }
  38. const availableClients = await getAvailableClients();
  39. logger.info(`Available clients: ${availableClients.join(",")}`);
  40. }
  41. // Execute MCP request
  42. export async function executeMcpAction(
  43. clientId: string,
  44. request: McpRequestMessage,
  45. ) {
  46. try {
  47. // Find the corresponding client
  48. const client = clientsMap.get(clientId);
  49. if (!client) {
  50. logger.error(`Client ${clientId} not found`);
  51. return;
  52. }
  53. logger.info(`Executing MCP request for ${clientId}`);
  54. // Execute request and return result
  55. return await executeRequest(client, request);
  56. } catch (error) {
  57. logger.error(`MCP execution error: ${error}`);
  58. throw error;
  59. }
  60. }
  61. // Get all available client IDs
  62. export async function getAvailableClients() {
  63. return Array.from(clientsMap.keys()).filter(
  64. (clientId) => !errorClients.includes(clientId),
  65. );
  66. }