Skip to main content
Glama
garc33

Bitbucket Server MCP

by garc33

get_diff

Retrieve code differences for a Bitbucket pull request to review added, removed, or modified lines. Understand change scope and analyze impact before merging.

Instructions

Retrieve the code differences (diff) for a pull request showing what lines were added, removed, or modified. Use this to understand the scope of changes, review specific code modifications, or analyze the impact of proposed changes before merging.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectNoBitbucket project key. If omitted, uses BITBUCKET_DEFAULT_PROJECT environment variable.
repositoryYesRepository slug containing the pull request.
prIdYesPull request ID to get diff for.
contextLinesNoNumber of context lines to show around changes (default: 10). Higher values provide more surrounding code context.
maxLinesPerFileNoMaximum number of lines to show per file (default: uses BITBUCKET_DIFF_MAX_LINES_PER_FILE env var). Set to 0 for no limit. Prevents large files from overwhelming the diff output.

Implementation Reference

  • The main execution logic for the 'get_diff' tool. Fetches the diff from Bitbucket API endpoint `/pull-requests/{prId}/diff`, applies truncation if specified, and returns the diff as text content.
    private async getDiff(params: PullRequestParams, contextLines: number = 10, maxLinesPerFile?: number) {
      const { project, repository, prId } = params;
      
      if (!project || !repository || !prId) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Project, repository, and prId are required'
        );
      }
      
      const response = await this.api.get(
        `/projects/${project}/repos/${repository}/pull-requests/${prId}/diff`,
        {
          params: { contextLines },
          headers: { Accept: 'text/plain' }
        }
      );
    
      // Determine max lines per file: parameter > env var > no limit
      const effectiveMaxLines = maxLinesPerFile !== undefined 
        ? maxLinesPerFile 
        : this.config.maxLinesPerFile;
    
      const diffContent = effectiveMaxLines 
        ? this.truncateDiff(response.data, effectiveMaxLines)
        : response.data;
    
      return {
        content: [{ type: 'text', text: diffContent }]
      };
    }
  • Input schema definition for the 'get_diff' tool, specifying parameters like project, repository, prId, contextLines, and maxLinesPerFile.
    {
      name: 'get_diff',
      description: 'Retrieve the code differences (diff) for a pull request showing what lines were added, removed, or modified. Use this to understand the scope of changes, review specific code modifications, or analyze the impact of proposed changes before merging.',
      inputSchema: {
        type: 'object',
        properties: {
          project: { type: 'string', description: 'Bitbucket project key. If omitted, uses BITBUCKET_DEFAULT_PROJECT environment variable.' },
          repository: { type: 'string', description: 'Repository slug containing the pull request.' },
          prId: { type: 'number', description: 'Pull request ID to get diff for.' },
          contextLines: { type: 'number', description: 'Number of context lines to show around changes (default: 10). Higher values provide more surrounding code context.' },
          maxLinesPerFile: { type: 'number', description: 'Maximum number of lines to show per file (default: uses BITBUCKET_DIFF_MAX_LINES_PER_FILE env var). Set to 0 for no limit. Prevents large files from overwhelming the diff output.' }
        },
        required: ['repository', 'prId']
      }
  • src/index.ts:507-518 (registration)
    Registration in the CallToolRequestSchema handler switch statement, which extracts arguments and invokes the getDiff method.
    case 'get_diff': {
      const diffPrParams: PullRequestParams = {
        project: getProject(args.project as string),
        repository: args.repository as string,
        prId: args.prId as number
      };
      return await this.getDiff(
        diffPrParams, 
        args.contextLines as number, 
        args.maxLinesPerFile as number
      );
    }
  • Helper function to truncate large diff files intelligently, showing beginning and end sections while indicating truncation.
    private truncateDiff(diffContent: string, maxLinesPerFile: number): string {
      if (!maxLinesPerFile || maxLinesPerFile <= 0) {
        return diffContent;
      }
    
      const lines = diffContent.split('\n');
      const result: string[] = [];
      let currentFileLines: string[] = [];
      let currentFileName = '';
      let inFileContent = false;
    
      for (const line of lines) {
        // Detect file headers (diff --git, index, +++, ---)
        if (line.startsWith('diff --git ')) {
          // Process previous file if any
          if (currentFileLines.length > 0) {
            result.push(...this.truncateFileSection(currentFileLines, currentFileName, maxLinesPerFile));
            currentFileLines = [];
          }
          
          // Extract filename for context
          const match = line.match(/diff --git a\/(.+) b\/(.+)/);
          currentFileName = match ? match[2] : 'unknown';
          inFileContent = false;
          
          // Always include file headers
          result.push(line);
        } else if (line.startsWith('index ') || line.startsWith('+++') || line.startsWith('---')) {
          // Always include file metadata
          result.push(line);
        } else if (line.startsWith('@@')) {
          // Hunk header - marks start of actual file content
          inFileContent = true;
          currentFileLines.push(line);
        } else if (inFileContent) {
          // Collect file content lines for potential truncation
          currentFileLines.push(line);
        } else {
          // Other lines (empty lines between files, etc.)
          result.push(line);
        }
      }
    
      // Process the last file
      if (currentFileLines.length > 0) {
        result.push(...this.truncateFileSection(currentFileLines, currentFileName, maxLinesPerFile));
      }
    
      return result.join('\n');
    }
  • Supporting helper for truncateDiff that handles truncation within individual file sections of the diff.
    private truncateFileSection(fileLines: string[], fileName: string, maxLines: number): string[] {
      if (fileLines.length <= maxLines) {
        return fileLines;
      }
    
      // Count actual content lines (excluding hunk headers)
      const contentLines = fileLines.filter(line => !line.startsWith('@@'));
      const hunkHeaders = fileLines.filter(line => line.startsWith('@@'));
    
      if (contentLines.length <= maxLines) {
        return fileLines; // No need to truncate if content is within limit
      }
    
      // Smart truncation: show beginning and end
      const showAtStart = Math.floor(maxLines * 0.6); // 60% at start
      const showAtEnd = Math.floor(maxLines * 0.4);   // 40% at end
      const truncatedCount = contentLines.length - showAtStart - showAtEnd;
    
      const result: string[] = [];
      
      // Add hunk headers first
      result.push(...hunkHeaders);
      
      // Add first portion
      result.push(...contentLines.slice(0, showAtStart));
      
      // Add truncation message
      result.push('');
      result.push(`[*** FILE TRUNCATED: ${truncatedCount} lines hidden from ${fileName} ***]`);
      result.push(`[*** File had ${contentLines.length} total lines, showing first ${showAtStart} and last ${showAtEnd} ***]`);
      result.push(`[*** Use maxLinesPerFile=0 to see complete diff ***]`);
      result.push('');
      
      // Add last portion
      result.push(...contentLines.slice(-showAtEnd));
    
      return result;
    }
Behavior3/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 describes what the tool returns ('code differences showing what lines were added, removed, or modified') and the purpose of those differences. However, it doesn't mention important behavioral aspects like whether this is a read-only operation (implied but not stated), potential rate limits, authentication requirements, or what format the diff is returned in (unified diff, JSON, etc.).

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 efficiently structured with two sentences. The first sentence states the core purpose, and the second provides usage context. Every sentence earns its place by adding value - no redundant or vague language. It's appropriately sized for a tool with 5 parameters and good schema documentation.

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

Completeness3/5

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

For a tool with 5 parameters, 100% schema coverage, but no annotations and no output schema, the description is adequate but has gaps. It explains the purpose and usage context well, but doesn't address the output format or behavioral constraints that would be important for an agent to use this tool effectively. The absence of output schema means the description should ideally mention what format the diff is returned in.

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 all 5 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema. It mentions 'diff' generally but doesn't explain how parameters like contextLines or maxLinesPerFile affect the output format. 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.

Purpose5/5

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

The description clearly states the tool's purpose with specific verbs ('retrieve', 'show') and resource ('code differences for a pull request'). It distinguishes this tool from siblings like get_pull_request (which likely returns metadata) or get_file_content (which retrieves file contents rather than diffs). The description explicitly mentions what the diff shows: 'lines were added, removed, or modified'.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool: 'to understand the scope of changes, review specific code modifications, or analyze the impact of proposed changes before merging.' This gives the agent specific scenarios for invocation. However, it doesn't explicitly state when NOT to use this tool or mention alternatives like get_pull_request for high-level information.

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/garc33/bitbucket-server-mcp-server'

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