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;
    }

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