File size: 2,425 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { logger } from '@librechat/data-schemas';
import { Constants } from 'librechat-data-provider';
import type { PluginAuthMethods } from '@librechat/data-schemas';
import type { GenericTool } from '@librechat/agents';
import { getPluginAuthMap } from '~/agents/auth';

export async function getUserMCPAuthMap({
  userId,
  tools,
  servers,
  toolInstances,
  findPluginAuthsByKeys,
}: {
  userId: string;
  tools?: (string | undefined)[];
  servers?: (string | undefined)[];
  toolInstances?: (GenericTool | null)[];
  findPluginAuthsByKeys: PluginAuthMethods['findPluginAuthsByKeys'];
}) {
  let allMcpCustomUserVars: Record<string, Record<string, string>> = {};
  let mcpPluginKeysToFetch: string[] = [];
  try {
    const uniqueMcpServers = new Set<string>();

    if (servers != null && servers.length) {
      for (const serverName of servers) {
        if (!serverName) {
          continue;
        }
        uniqueMcpServers.add(`${Constants.mcp_prefix}${serverName}`);
      }
    } else if (tools != null && tools.length) {
      for (const toolName of tools) {
        if (!toolName) {
          continue;
        }
        const delimiterIndex = toolName.indexOf(Constants.mcp_delimiter);
        if (delimiterIndex === -1) continue;
        const mcpServer = toolName.slice(delimiterIndex + Constants.mcp_delimiter.length);
        if (!mcpServer) continue;
        uniqueMcpServers.add(`${Constants.mcp_prefix}${mcpServer}`);
      }
    } else if (toolInstances != null && toolInstances.length) {
      for (const tool of toolInstances) {
        if (!tool) {
          continue;
        }
        const mcpTool = tool as GenericTool & { mcpRawServerName?: string };
        if (mcpTool.mcpRawServerName) {
          uniqueMcpServers.add(`${Constants.mcp_prefix}${mcpTool.mcpRawServerName}`);
        }
      }
    }

    if (uniqueMcpServers.size === 0) {
      return {};
    }

    mcpPluginKeysToFetch = Array.from(uniqueMcpServers);
    allMcpCustomUserVars = await getPluginAuthMap({
      userId,
      pluginKeys: mcpPluginKeysToFetch,
      throwError: false,
      findPluginAuthsByKeys,
    });
  } catch (err) {
    logger.error(
      `[handleTools] Error batch fetching customUserVars for MCP tools (keys: ${mcpPluginKeysToFetch.join(
        ', ',
      )}), user ${userId}: ${err instanceof Error ? err.message : 'Unknown error'}`,
      err,
    );
  }

  return allMcpCustomUserVars;
}