Skip to main content
Glama
pdogra1299
by pdogra1299

get_pull_request_diff

Retrieve and filter pull request diffs by specifying context lines, file paths, or inclusion/exclusion patterns to streamline code review and change analysis.

Instructions

Get the diff/changes for a pull request with optional filtering

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
context_linesNoNumber of context lines around changes (optional, default: 3)
exclude_patternsNoArray of glob patterns to exclude (e.g., ["*.lock", "*.svg"]) (optional)
file_pathNoSpecific file path to get diff for (e.g., "src/index.ts") (optional)
include_patternsNoArray of glob patterns to include (e.g., ["*.res", "src/**/*.js"]) (optional)
pull_request_idYesPull request ID
repositoryYesRepository slug (e.g., "my-repo")
workspaceYesBitbucket workspace/project key (e.g., "PROJ")

Implementation Reference

  • Main handler function that fetches the pull request diff from Bitbucket API (Cloud or Server), optionally filters by file patterns or specific file using DiffParser, and returns formatted JSON response with metadata.
    async handleGetPullRequestDiff(args: any) {
      if (!isGetPullRequestDiffArgs(args)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Invalid arguments for get_pull_request_diff'
        );
      }
    
      const { 
        workspace, 
        repository, 
        pull_request_id, 
        context_lines = 3,
        include_patterns,
        exclude_patterns,
        file_path
      } = args;
    
      try {
        let apiPath: string;
        let config: any = {};
    
        if (this.apiClient.getIsServer()) {
          // Bitbucket Server API
          apiPath = `/rest/api/1.0/projects/${workspace}/repos/${repository}/pull-requests/${pull_request_id}/diff`;
          config.params = { contextLines: context_lines };
        } else {
          // Bitbucket Cloud API
          apiPath = `/repositories/${workspace}/${repository}/pullrequests/${pull_request_id}/diff`;
          config.params = { context: context_lines };
        }
    
        // For diff, we want the raw text response
        config.headers = { 'Accept': 'text/plain' };
        
        const rawDiff = await this.apiClient.makeRequest<string>('get', apiPath, undefined, config);
    
        // Check if filtering is needed
        const needsFiltering = file_path || include_patterns || exclude_patterns;
        
        if (!needsFiltering) {
          // Return raw diff without filtering
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  message: 'Pull request diff retrieved successfully',
                  pull_request_id,
                  diff: rawDiff
                }, null, 2),
              },
            ],
          };
        }
    
        // Apply filtering
        const diffParser = new DiffParser();
        const sections = diffParser.parseDiffIntoSections(rawDiff);
        
        const filterOptions = {
          includePatterns: include_patterns,
          excludePatterns: exclude_patterns,
          filePath: file_path
        };
        
        const filteredResult = diffParser.filterSections(sections, filterOptions);
        const filteredDiff = diffParser.reconstructDiff(filteredResult.sections);
    
        // Build response with filtering metadata
        const response: any = {
          message: 'Pull request diff retrieved successfully',
          pull_request_id,
          diff: filteredDiff
        };
    
        // Add filter metadata
        if (filteredResult.metadata.excludedFiles > 0 || file_path || include_patterns || exclude_patterns) {
          response.filter_metadata = {
            total_files: filteredResult.metadata.totalFiles,
            included_files: filteredResult.metadata.includedFiles,
            excluded_files: filteredResult.metadata.excludedFiles
          };
    
          if (filteredResult.metadata.excludedFileList.length > 0) {
            response.filter_metadata.excluded_file_list = filteredResult.metadata.excludedFileList;
          }
    
          response.filter_metadata.filters_applied = {};
          if (file_path) {
            response.filter_metadata.filters_applied.file_path = file_path;
          }
          if (include_patterns) {
            response.filter_metadata.filters_applied.include_patterns = include_patterns;
          }
          if (exclude_patterns) {
            response.filter_metadata.filters_applied.exclude_patterns = exclude_patterns;
          }
        }
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(response, null, 2),
            },
          ],
        };
      } catch (error) {
        return this.apiClient.handleApiError(error, `getting diff for pull request ${pull_request_id} in ${workspace}/${repository}`);
      }
    }
  • Type guard function used in the handler to validate input arguments for get_pull_request_diff tool.
    export const isGetPullRequestDiffArgs = (
      args: any
    ): args is {
      workspace: string;
      repository: string;
      pull_request_id: number;
      context_lines?: number;
      include_patterns?: string[];
      exclude_patterns?: string[];
      file_path?: string;
    } =>
      typeof args === 'object' &&
      args !== null &&
      typeof args.workspace === 'string' &&
      typeof args.repository === 'string' &&
      typeof args.pull_request_id === 'number' &&
      (args.context_lines === undefined || typeof args.context_lines === 'number') &&
      (args.include_patterns === undefined || (Array.isArray(args.include_patterns) && args.include_patterns.every((p: any) => typeof p === 'string'))) &&
      (args.exclude_patterns === undefined || (Array.isArray(args.exclude_patterns) && args.exclude_patterns.every((p: any) => typeof p === 'string'))) &&
      (args.file_path === undefined || typeof args.file_path === 'string');
  • Tool definition including name, description, and input schema used for MCP tool listing and validation.
    {
      name: 'get_pull_request_diff',
      description: 'Get the diff/changes for a pull request with optional filtering',
      inputSchema: {
        type: 'object',
        properties: {
          workspace: {
            type: 'string',
            description: 'Bitbucket workspace/project key (e.g., "PROJ")',
          },
          repository: {
            type: 'string',
            description: 'Repository slug (e.g., "my-repo")',
          },
          pull_request_id: {
            type: 'number',
            description: 'Pull request ID',
          },
          context_lines: {
            type: 'number',
            description: 'Number of context lines around changes (optional, default: 3)',
          },
          include_patterns: {
            type: 'array',
            items: { type: 'string' },
            description: 'Array of glob patterns to include (e.g., ["*.res", "src/**/*.js"]) (optional)',
          },
          exclude_patterns: {
            type: 'array',
            items: { type: 'string' },
            description: 'Array of glob patterns to exclude (e.g., ["*.lock", "*.svg"]) (optional)',
          },
          file_path: {
            type: 'string',
            description: 'Specific file path to get diff for (e.g., "src/index.ts") (optional)',
          },
        },
        required: ['workspace', 'repository', 'pull_request_id'],
      },
    },
  • src/index.ts:122-123 (registration)
    Switch case in main server request handler that routes 'get_pull_request_diff' tool calls to the ReviewHandlers.handleGetPullRequestDiff method.
    case 'get_pull_request_diff':
      return this.reviewHandlers.handleGetPullRequestDiff(request.params.arguments);
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions 'optional filtering', it doesn't describe important behavioral aspects: what format the diff is returned in (unified diff? patch format?), whether it's paginated for large diffs, authentication requirements, rate limits, or error conditions. For a tool that retrieves potentially complex data with 7 parameters, this is insufficient.

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 that front-loads the core purpose ('Get the diff/changes for a pull request') and adds qualifying information ('with optional filtering'). There's no wasted verbiage or redundant information. Every word earns its place in this concise formulation.

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?

For a tool with 7 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (diff format, structure, size limitations) or important behavioral constraints. While the schema covers parameter documentation well, the description fails to provide the contextual information needed to understand how to effectively use this tool and interpret its results.

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 all parameters are well-documented in the schema itself. The description adds minimal value beyond the schema - it mentions 'optional filtering' which aligns with parameters like 'exclude_patterns', 'include_patterns', and 'file_path', but doesn't provide additional semantic context. This meets the baseline expectation when schema coverage is complete.

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 tool's purpose: 'Get the diff/changes for a pull request with optional filtering'. It specifies the verb ('Get'), resource ('diff/changes for a pull request'), and scope ('optional filtering'). However, it doesn't explicitly distinguish this tool from potential siblings like 'get_pull_request' or 'list_pr_commits', which might also provide diff-related information.

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?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'get_pull_request' (which might include diff info) and 'list_pr_commits' (which might show commit-level changes), there's no indication of when this specific diff-focused tool is preferred. The mention of 'optional filtering' hints at use cases but doesn't provide explicit when/when-not guidance.

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

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

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