actions.ts 2.1 KB

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