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);
        });
      });
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the action ('Build') but doesn't cover critical traits like whether this is a long-running process, if it requires specific permissions, what happens on failure, or output format. This leaves significant gaps for a build operation tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste—it directly states the tool's purpose without unnecessary words. It's appropriately sized and front-loaded, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a build operation, no annotations, and no output schema, the description is incomplete. It doesn't explain what the build process entails, potential side effects, or what to expect as a result, leaving the agent with insufficient context for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters thoroughly. The description doesn't add any meaning beyond what's in the schema, such as explaining parameter interactions or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Build') and resource ('specified Bazel targets'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'bazel_test_target' or 'bazel_query_target' beyond the basic action, missing specific scope details that would earn a 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives like 'bazel_test_target' for testing or 'bazel_list_targets' for listing. The description lacks context about prerequisites, such as needing a workspace path set via 'bazel_set_workspace_path', or exclusions like not using it for dependency fetching.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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