All files / src/mcp mcp.service.ts

62.85% Statements 110/175
46.93% Branches 23/49
70.37% Functions 19/27
62.73% Lines 101/161

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 42122x               22x 22x 22x 22x 22x                       22x 27x 27x       27x   27x       7x 7x     7x 6x     6x     1x 1x         6x 6x               3x 3x       3x 3x 3x 3x         3x   3x 3x       3x     3x   3x   3x             2x 2x                           3x   3x   3x     3x     3x                                                                                   1x 1x         1x 1x           1x 1x           1x     1x           1x               1x 1x 1x             2x     2x           2x 2x   2x 1x   1x       2x       1x     1x           1x 1x 1x             1x     1x       1x       2x     2x       2x 2x                         2x                                                                             2x 2x   2x 2x                                                       6x     6x   5x     5x   5x 4x 8x 7x                 9x     9x   8x     8x     8x   7x 7x 11x     10x 10x 2x     10x 1x     10x                       7x     7x      
import {
  BadRequestException,
  Injectable,
  Logger,
  NotFoundException,
  OnModuleDestroy,
  OnModuleInit,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { McpConfig, McpTool } from '../core-entities';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { LlmFunctionTool } from '../llm-provider/llm-provider.interface';
 
// Local interface to match the shape of a tool from the MCP SDK
// Properties are optional to match the inferred type from the SDK.
interface McpSdkTool {
  name?: string;
  description?: string;
  inputSchema?: Record<string, any>;
}
 
@Injectable()
export class McpService implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(McpService.name);
  private readonly activeClients = new Map<string, Client>();
 
  constructor(
    @InjectRepository(McpConfig)
    private readonly mcpConfigRepository: Repository<McpConfig>,
    @InjectRepository(McpTool)
    private readonly mcpToolRepository: Repository<McpTool>,
  ) {}
 
  async onModuleInit() {
    this.logger.log('Initializing MCP connections...');
    const configs = await this.mcpConfigRepository.find({
      where: { is_active: true },
    });
    if (configs.length === 0) {
      this.logger.warn(
        'No active MCP configurations found. MCP tools will be unavailable.',
      );
      return;
    }
 
    for (const config of configs) {
      await this.connectToServer(config);
    }
  }
 
  async onModuleDestroy() {
    this.logger.log('Closing all active MCP connections...');
    await Promise.all(
      Array.from(this.activeClients.keys()).map((serverName) =>
        this.disconnectFromServer(serverName),
      ),
    );
  }
 
  public async connectToServer(config: McpConfig) {
    const { server_name, command, args, env } = config;
    Iif (this.activeClients.has(server_name)) {
      this.logger.log(`Already connected to ${server_name}. Skipping.`);
      return;
    }
    this.logger.log(`Attempting to connect to MCP server: ${server_name}`);
    try {
      const transport = new StdioClientTransport({ command, args, env });
      const client = new Client({
        name: `repoburg-backend-${server_name}`,
        version: '1.0.0',
      });
 
      client.connect(transport);
 
      const toolsResult = await client.listTools();
      Iif (!toolsResult || !toolsResult.tools) {
        throw new Error('Invalid or empty tool list received from server.');
      }
 
      this.logger.log(
        `Connected to ${server_name}. Discovered ${toolsResult.tools.length} tools.`,
      );
      this.activeClients.set(server_name, client);
 
      await this.syncToolsToDb(server_name, toolsResult.tools as McpSdkTool[]);
    } catch (e) {
      this.logger.error(
        `Failed to connect to MCP server "${server_name}": ${e.message}`,
      );
    }
  }
 
  public async disconnectFromServer(serverName: string) {
    const client = this.activeClients.get(serverName);
    Iif (client) {
      try {
        await client.close();
        this.activeClients.delete(serverName);
        this.logger.log(`Disconnected from ${serverName}`);
      } catch (e) {
        this.logger.error(
          `Error disconnecting from ${serverName}: ${e.message}`,
        );
      }
    }
  }
 
  private async syncToolsToDb(serverName: string, tools: McpSdkTool[]) {
    this.logger.log(`Syncing tools for server: ${serverName}`);
 
    const validTools = tools.filter(
      (tool): tool is Required<Pick<McpSdkTool, 'name'>> & McpSdkTool =>
        !!tool.name,
    );
 
    const existingTools = await this.mcpToolRepository.find({
      where: { server_name: serverName },
    });
    const existingToolsMap = new Map(
      existingTools.map((t) => [t.tool_name, t]),
    );
 
    const toolsToSave: McpTool[] = [];
    for (const sdkTool of validTools) {
      const existingTool = existingToolsMap.get(sdkTool.name);
      if (existingTool) {
        // Update existing tool but preserve its active state
        existingTool.description = sdkTool.description || '';
        existingTool.input_schema = sdkTool.inputSchema || {};
        toolsToSave.push(existingTool);
      } else {
        // Create new tool, will default to is_active: true
        toolsToSave.push(
          this.mcpToolRepository.create({
            server_name: serverName,
            tool_name: sdkTool.name,
            description: sdkTool.description || '',
            input_schema: sdkTool.inputSchema || {},
          }),
        );
      }
    }
 
    await this.mcpToolRepository.save(toolsToSave);
 
    const newToolNames = validTools.map((t) => t.name);
    const toolsToDelete = existingTools.filter(
      (t) => !newToolNames.includes(t.tool_name),
    );
    Iif (toolsToDelete.length > 0) {
      await this.mcpToolRepository.remove(toolsToDelete);
    }
 
    this.logger.log(
      `Successfully synced tools for ${serverName}. Saved: ${toolsToSave.length}, Deleted: ${toolsToDelete.length}`,
    );
  }
 
  public async createMcpConfig(configJson: string): Promise<McpConfig> {
    let parsedConfig: any;
    try {
      parsedConfig = JSON.parse(configJson);
    } catch (e) {
      throw new BadRequestException('Invalid JSON format.');
    }
 
    const serverName = Object.keys(parsedConfig)[0];
    Iif (!serverName) {
      throw new BadRequestException(
        'JSON must have a root key as the server name.',
      );
    }
 
    const configData = parsedConfig[serverName];
    Iif (!configData || !configData.command || !configData.args) {
      throw new BadRequestException(
        'Configuration must include "command" and "args" properties.',
      );
    }
 
    const existingConfig = await this.mcpConfigRepository.findOneBy({
      server_name: serverName,
    });
    Iif (existingConfig) {
      throw new BadRequestException(
        `A configuration for "${serverName}" already exists.`,
      );
    }
 
    const newConfig = this.mcpConfigRepository.create({
      server_name: serverName,
      command: configData.command,
      args: configData.args,
      env: configData.env || {},
      is_active: true,
    });
 
    const savedConfig = await this.mcpConfigRepository.save(newConfig);
    await this.connectToServer(savedConfig);
    return savedConfig;
  }
 
  public async updateMcpConfigStatus(
    serverName: string,
    isActive: boolean,
  ): Promise<McpConfig> {
    const config = await this.mcpConfigRepository.findOneBy({
      server_name: serverName,
    });
    Iif (!config) {
      throw new NotFoundException(
        `MCP configuration for "${serverName}" not found.`,
      );
    }
 
    config.is_active = isActive;
    await this.mcpConfigRepository.save(config);
 
    if (isActive) {
      await this.connectToServer(config);
    } else {
      await this.disconnectFromServer(serverName);
      // Do not remove tools from DB, just mark them as inactive conceptually
    }
 
    return config;
  }
 
  public async deleteMcpConfig(serverName: string): Promise<void> {
    const config = await this.mcpConfigRepository.findOneBy({
      server_name: serverName,
    });
    Iif (!config) {
      throw new NotFoundException(
        `MCP configuration for "${serverName}" not found.`,
      );
    }
 
    await this.disconnectFromServer(serverName);
    await this.mcpToolRepository.delete({ server_name: serverName });
    await this.mcpConfigRepository.remove(config);
  }
 
  public async batchUpdateToolStatus(
    toolIds: string[],
    isActive: boolean,
  ): Promise<{ affected: number }> {
    Iif (toolIds.length === 0) {
      return { affected: 0 };
    }
    const result = await this.mcpToolRepository.update(
      { id: In(toolIds) },
      { is_active: isActive },
    );
    return { affected: result.affected || 0 };
  }
 
  public async getMcpServers(): Promise<any[]> {
    const configs = await this.mcpConfigRepository.find({
      order: { server_name: 'ASC' },
    });
    const tools = await this.mcpToolRepository.find({
      order: { tool_name: 'ASC' },
    });
 
    const toolsByServer = new Map<string, any[]>();
    for (const tool of tools) {
      Iif (!toolsByServer.has(tool.server_name)) {
        toolsByServer.set(tool.server_name, []);
      }
      toolsByServer.get(tool.server_name).push({
        id: tool.id,
        tool_name: tool.tool_name,
        description: tool.description,
        input_schema: tool.input_schema,
        is_active: tool.is_active,
      });
    }
 
    return configs.map((config) => ({
      server_name: config.server_name,
      description: `Tools available from the ${config.server_name} server.`,
      is_active: config.is_active,
      tools: toolsByServer.get(config.server_name) || [],
    }));
  }
 
  public async executeMcpTool(
    serverName: string,
    toolName: string,
    args: any,
  ): Promise<{ stdout: string; stderr: string }> {
    this.logger.log(
      `Executing MCP tool: ${serverName}.${toolName} with args: ${JSON.stringify(
        args,
      )}`,
    );
 
    const client = this.activeClients.get(serverName);
    Iif (!client) {
      const errorMsg = `No active MCP connection found for server: ${serverName}`;
      this.logger.error(errorMsg);
      return { stdout: '', stderr: errorMsg };
    }
 
    try {
      const result = await client.callTool({ name: toolName, arguments: args });
      const stdout = JSON.stringify(result, null, 2);
      return { stdout, stderr: '' };
    } catch (e) {
      this.logger.error(
        `Error calling tool ${toolName} on ${serverName}: ${e.message}`,
      );
      return { stdout: '', stderr: e.message };
    }
  }
 
  public async getMcpToolsDefinition(): Promise<string> {
    const servers = await this.getMcpServers();
    const activeServers = servers.filter((s) => s.is_active);
 
    if (activeServers.length === 0) {
      return 'No active MCP servers are currently connected.';
    }
 
    let definition = '';
    for (const server of activeServers) {
      const activeTools = server.tools.filter((t) => t.is_active);
      Iif (activeTools.length === 0) continue;
 
      definition += `### Server: ${server.server_name}\n`;
      definition += `Description: ${server.description}\n`;
      definition += 'Tools:\n';
      for (const tool of activeTools) {
        definition += `- **${tool.tool_name}**\n`;
        definition += `  - Description: ${tool.description}\n`;
        definition += `  - Input Schema: \`${JSON.stringify(
          tool.input_schema,
        )}\`\n`;
      }
      definition += '\n';
    }
    return definition;
  }
 
  /**
   * Get all active MCP tool names in serverName__toolName format.
   * Used by SystemPromptsService to populate the MCP tool selection UI.
   */
  public async getActiveMcpToolNames(): Promise<string[]> {
    const activeConfigs = await this.mcpConfigRepository.find({
      where: { is_active: true },
    });
    if (activeConfigs.length === 0) return [];
 
    const activeTools = await this.mcpToolRepository.find({
      where: { is_active: true },
    });
    if (activeTools.length === 0) return [];
 
    const activeServerNames = new Set(activeConfigs.map((c) => c.server_name));
    return activeTools
      .filter((t) => activeServerNames.has(t.server_name))
      .map((t) => `${t.server_name}__${t.tool_name}`);
  }
 
  /**
   * Generate LlmFunctionTool definitions for all active MCP tools.
   * Each tool is named `{server_name}__{tool_name}` (double underscore).
   * These definitions are merged with built-in tool definitions for native tool calling.
   */
  public async getActiveMcpToolDefinitions(): Promise<LlmFunctionTool[]> {
    const activeConfigs = await this.mcpConfigRepository.find({
      where: { is_active: true },
    });
    if (activeConfigs.length === 0) return [];
 
    const activeTools = await this.mcpToolRepository.find({
      where: { is_active: true },
    });
    if (activeTools.length === 0) return [];
 
    // Only include tools from active servers
    const activeServerNames = new Set(activeConfigs.map((c) => c.server_name));
 
    const definitions: LlmFunctionTool[] = [];
    for (const tool of activeTools) {
      if (!activeServerNames.has(tool.server_name)) continue;
 
      // Use input_schema directly if it's a valid object, otherwise fallback
      let parameters = tool.input_schema;
      if (!parameters || typeof parameters !== 'object') {
        parameters = { type: 'object', properties: {} };
      }
      // Ensure parameters has the required JSON Schema fields
      if (!parameters.type) {
        parameters = { type: 'object', ...parameters };
      }
 
      definitions.push({
        type: 'function',
        function: {
          name: `${tool.server_name}__${tool.tool_name}`,
          description:
            tool.description ||
            `MCP tool: ${tool.server_name}.${tool.tool_name}`,
          parameters,
        },
      });
    }
 
    this.logger.log(
      `Generated ${definitions.length} MCP tool definitions from ${activeServerNames.size} active servers.`,
    );
    return definitions;
  }
}