Skip to main content
Glama

bazel_build_target

Build specified Bazel targets with optional command-line arguments to compile code and generate outputs in Bazel projects.

Instructions

Build specified Bazel targets

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
targetsYesList of Bazel targets to build (e.g. ['//path/to:target'])
additionalArgsNoAdditional Bazel command line arguments (e.g. ['--verbose_failures', '--sandbox_debug'])

Implementation Reference

  • Core handler function that executes the Bazel build command for the specified targets, including argument validation and command execution.
    async buildTargets(targets: string[], additionalArgs?: string[], onOutput?: (chunk: string) => void): Promise<string> {
      const validatedArgs = this.validateAdditionalArgs(additionalArgs);
      const allArgs = [...targets, ...validatedArgs];
      const { stdout, stderr } = await this.runBazelCommand("build", allArgs, onOutput);
      return `${stdout}\n${stderr}`;
    }
  • Defines the Tool object including name, description, and input schema for the bazel_build_target tool.
    const buildTargetTool: Tool = {
      name: "bazel_build_target",
      description: "Build specified Bazel targets",
      inputSchema: {
        type: "object",
        properties: {
          targets: {
            type: "array",
            items: {
              type: "string",
            },
            description: "List of Bazel targets to build (e.g. ['//path/to:target'])",
          },
          additionalArgs: {
            type: "array",
            items: {
              type: "string",
            },
            description: "Additional Bazel command line arguments (e.g. ['--verbose_failures', '--sandbox_debug'])",
          },
        },
        required: ["targets"],
      },
    };
  • index.ts:608-615 (registration)
    Registers the bazel_build_target tool (as buildTargetTool) in the ListTools response.
    tools: [
      buildTargetTool,
      queryTargetTool,
      testTargetTool,
      listTargetsTool,
      fetchDependenciesTool,
      setWorkspacePathTool,
    ],
  • MCP request handler case that processes the tool call and invokes the buildTargets method.
    case "bazel_build_target": {
      const args = request.params.arguments as unknown as BuildTargetArgs;
      log(`Processing bazel_build_target with args: ${JSON.stringify(args)}`, 'info', false);
      if (!args.targets || args.targets.length === 0) {
        throw new Error("Missing required argument: targets");
      }
      response = await bazelClient.buildTargets(args.targets, args.additionalArgs);
      break;
    }
  • Helper method that spawns the actual Bazel process, captures output, and handles errors.
    private runBazelCommand(
      command: string,
      args: string[] = [],
      onOutput?: (chunk: string) => void
    ): Promise<{ stdout: string; stderr: string }> {
      return new Promise((resolve, reject) => {
        const fullArgs = [command, ...args];
        
        if (this.workspaceConfig) {
          fullArgs.unshift(`--bazelrc=${this.workspaceConfig}`);
        }
    
        const cmdString = `${this.bazelPath} ${fullArgs.join(" ")}`;
        log(`Running command: ${cmdString} in directory: ${this.workspacePath}`);
        
        const process = spawn(this.bazelPath, fullArgs, {
          cwd: this.workspacePath,
          stdio: ["ignore", "pipe", "pipe"],
        });
    
        let stdout = "";
        let stderr = "";
    
        process.stdout.on("data", (data) => {
          const chunk = data.toString();
          stdout += chunk;
          log(`STDOUT: ${chunk}`, 'info', false);
          if (onOutput) {
            onOutput(chunk);
          }
        });
    
        process.stderr.on("data", (data) => {
          const chunk = data.toString();
          stderr += chunk;
          log(`STDERR: ${chunk}`, 'info', false);
          if (onOutput) {
            onOutput(chunk);
          }
        });
    
        process.on("close", (code) => {
          log(`Command completed with exit code: ${code}`);
          if (code === 0) {
            resolve({ stdout, stderr });
          } else {
            const errorMsg = `Bazel command failed with code ${code}: ${stderr}`;
            log(errorMsg, 'error');
            reject(new Error(errorMsg));
          }
        });
    
        process.on("error", (err) => {
          log(`Command execution error: ${err.message}`, 'error');
          reject(err);
        });
      });
    }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/nacgarg/bazel-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server