Skip to content

MCP merge_pull_request and PR state checks: fail with the specific precondition and the pull request's actual state #2600

Closed

Description

@propr-dev

Context

merge_pull_request (in packages/api/mcp/toolsPullRequests.ts) collapses several different situations into two messages:

  • PRECONDITION_FAILED: PR must be open and ready for review. — thrown when the PR is closed, already merged, or a draft. The caller cannot tell which, and in the reported incident the PR had in fact already been merged.
  • CHECKS_NOT_PASSED: PR head, required reviews or branch protection requirements are not satisfied. — thrown for a stale head, mergeStateStatus of BEHIND/BLOCKED/DIRTY/UNSTABLE/UNKNOWN, CHANGES_REQUESTED, REVIEW_REQUIRED, or a failing/pending check rollup.

The other PR tools repeat Pull request is not open. with no state. This issue makes every PR precondition failure specific and ties into the error envelope (stage: 'precondition', retryable, details).

Requirements

  1. New helper pullRequestSnapshot(pr, graph?) returning the actual state:
    { "state": "open" | "closed" | "merged", "draft": false, "merged": true, "mergedAt": "...", "mergeCommitSha": "...",
      "closedAt": "...", "head": "<sha>", "base": "main", "mergeStateStatus": "BLOCKED", "reviewDecision": "REVIEW_REQUIRED",
      "checks": { "state": "PENDING", "failing": ["build"], "pending": ["e2e"] }, "url": "..." }
  2. New helper assertPullRequestOpen(pr, action) used by all PR mutation tools, throwing one of:
    • PULL_REQUEST_ALREADY_MERGED (409, not retryable, details include mergedAt, mergeCommitSha) — for merge_pull_request this is reported as such so the agent can tell the user "it was already merged".
    • PULL_REQUEST_CLOSED (409, not retryable, closedAt).
    • PULL_REQUEST_DRAFT (409, not retryable) — only for merge (other commands can run on drafts as today? keep current behaviour: other commands only require open).
  3. merge_pull_request evaluates preconditions in order and reports the first failing one, always attaching details.currentState (the snapshot) and details.failedPrecondition:
    Precondition Code Retryable
    head equals expectedHead STALE_HEAD false
    not draft PULL_REQUEST_DRAFT false
    reviewDecision !== 'CHANGES_REQUESTED' CHANGES_REQUESTED false
    reviewDecision !== 'REVIEW_REQUIRED' REVIEW_REQUIRED false
    check rollup not FAILURE/ERROR CHECKS_FAILING (details.failing = names) false
    check rollup not PENDING/EXPECTED CHECKS_PENDING (details.pending = names) true
    mergeStateStatus === 'BEHIND' BRANCH_BEHIND_BASE (message suggests update_pull_request_branch) false
    mergeStateStatus === 'DIRTY' MERGE_CONFLICT false
    mergeStateStatus === 'BLOCKED' BRANCH_PROTECTION_BLOCKED false
    mergeStateStatus === 'UNKNOWN' MERGE_STATE_UNKNOWN (GitHub still computing) true
    mergeStateStatus === 'UNSTABLE'/HAS_HOOKS → allowed only if rollup SUCCESS CHECKS_FAILING false
    GitHub merge API returns merged: false or 405/409 MERGE_REJECTED with GitHub's message false
  4. The GraphQL query fetches check names: statusCheckRollup { state contexts(first: 50) { nodes { ... on CheckRun { name conclusion status } ... on StatusContext { context state } } } }, plus isDraft, merged, mergedAt, closedAt, state.
  5. Messages are human sentences naming the precondition, e.g. "Cannot merge AI Fix for Issue #40: Feat: Monitor PR comments for follow-up tasks #42: 2 required checks are still running (e2e, lint). Try again when they finish."
  6. Replace every 'Pull request is not open.' / 'Pull request must be open.' throw in toolsPullRequests.ts with assertPullRequestOpen.

Implementation Specification

  • New packages/api/mcp/pullRequestPreconditions.ts (snapshot + assertions + merge evaluation, pure functions, no GitHub calls).
  • Edit packages/api/mcp/toolsPullRequests.ts (merge_pull_request and the open checks).
  • Tests packages/api/test/mcpMergePreconditions.test.ts covering every row of the table (pure-function tests) and one integration case through executeTool.

Acceptance Criteria

  • Merging an already-merged PR fails with PULL_REQUEST_ALREADY_MERGED, details.currentState.mergedAt set.
  • Each row of the table has a unit test asserting code, retryable flag and that details.currentState is present.
  • comment_on_pull_request on a closed PR fails with PULL_REQUEST_CLOSED (not PRECONDITION_FAILED).
  • The receipt of a failed merge (get_operation) shows the same envelope.
  • No behaviour change for a clean, approved, passing PR (merge succeeds exactly as before).

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We separate evaluation (pure: snapshot + ordered rule list) from effects (GitHub reads and the merge call). Pure functions make every precondition row unit-testable without a GitHub fake and keep the order explicit, so the "first failing precondition" is deterministic. We report precondition failures via McpError with stage: 'precondition' so the envelope from the first issue carries them unchanged into receipts.

    We deliberately keep GitHub's merge API as the final authority (it re-checks head SHA and protection atomically). Our pre-check exists to explain why before attempting, not to replace GitHub's enforcement.

    File: packages/api/mcp/pullRequestPreconditions.ts (new file)

    Why this file: Holds the snapshot shape and precondition rules shared by merge and all PR mutation tools.

    import { McpError } from './config.js';
    
    export interface RestPullRequest {
      number: number; state: string; draft?: boolean; merged?: boolean; merged_at?: string | null; merge_commit_sha?: string | null;
      closed_at?: string | null; head: { sha: string }; base: { ref: string }; html_url: string;
    }
    export interface GraphPullRequest {
      headRefOid: string; isDraft?: boolean; merged?: boolean; mergedAt?: string | null; closedAt?: string | null; state?: string;
      mergeStateStatus: string; reviewDecision: string | null;
      commits: { nodes: Array<{ commit: { statusCheckRollup: { state: string; contexts?: { nodes: Array<Record<string, string | null>> } } | null } }> };
    }
    
    export interface PullRequestSnapshot {
      number: number; url: string; state: 'open' | 'closed' | 'merged'; draft: boolean; merged: boolean;
      mergedAt: string | null; mergeCommitSha: string | null; closedAt: string | null; head: string; base: string;
      mergeStateStatus: string | null; reviewDecision: string | null;
      checks: { state: string | null; failing: string[]; pending: string[] };
    }
    
    export function pullRequestSnapshot(pr: RestPullRequest, graph?: GraphPullRequest): PullRequestSnapshot {
      const rollup = graph?.commits.nodes[0]?.commit.statusCheckRollup ?? null;
      const failing: string[] = [];
      const pending: string[] = [];
      for (const node of rollup?.contexts?.nodes ?? []) {
        // CheckRun: name/status/conclusion; StatusContext: context/state.
        const name = node.name ?? node.context ?? 'unnamed';
        const outcome = node.conclusion ?? node.state ?? null;
        if (node.status && node.status !== 'COMPLETED') pending.push(name);
        else if (outcome === 'PENDING' || outcome === 'EXPECTED') pending.push(name);
        else if (outcome && ['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE'].includes(outcome)) failing.push(name);
      }
      const merged = Boolean(pr.merged ?? graph?.merged);
      return {
        number: pr.number, url: pr.html_url, merged,
        state: merged ? 'merged' : pr.state === 'open' ? 'open' : 'closed',
        draft: Boolean(pr.draft ?? graph?.isDraft),
        mergedAt: pr.merged_at ?? graph?.mergedAt ?? null, mergeCommitSha: pr.merge_commit_sha ?? null,
        closedAt: pr.closed_at ?? graph?.closedAt ?? null,
        head: graph?.headRefOid ?? pr.head.sha, base: pr.base.ref,
        mergeStateStatus: graph?.mergeStateStatus ?? null, reviewDecision: graph?.reviewDecision ?? null,
        checks: { state: rollup?.state ?? null, failing: failing.slice(0, 20), pending: pending.slice(0, 20) },
      };
    }
    
    function fail(code: string, message: string, snapshot: PullRequestSnapshot, precondition: string, extra: Record<string, unknown> = {}, retryable = false): never {
      // Every precondition failure carries the PR's actual state so the caller can
      // explain it without another read.
      throw new McpError(code, message, 409, { stage: 'precondition', retryable,
        details: { failedPrecondition: precondition, currentState: snapshot, ...extra } });
    }
    
    /** Used by every PR mutation: distinguishes merged from closed instead of "not open". */
    export function assertPullRequestOpen(snapshot: PullRequestSnapshot, action: string): void {
      if (snapshot.state === 'merged') {
        fail('PULL_REQUEST_ALREADY_MERGED', `Cannot ${action} #${snapshot.number}: it was already merged${snapshot.mergedAt ? ` at ${snapshot.mergedAt}` : ''}.`, snapshot, 'open');
      }
      if (snapshot.state === 'closed') {
        fail('PULL_REQUEST_CLOSED', `Cannot ${action} #${snapshot.number}: it is closed without being merged.`, snapshot, 'open');
      }
    }
    
    const list = (names: string[]) => names.length ? ` (${names.slice(0, 5).join(', ')}${names.length > 5 ? ', …' : ''})` : '';
    
    /** Ordered merge preconditions; throws for the first one that fails. */
    export function assertMergeable(snapshot: PullRequestSnapshot, expectedHead: string): void {
      const n = `#${snapshot.number}`;
      assertPullRequestOpen(snapshot, 'merge');
      if (snapshot.head !== expectedHead) {
        fail('STALE_HEAD', `Cannot merge ${n}: its head moved to ${snapshot.head.slice(0, 7)} since you read it. Review the new commits first.`, snapshot, 'expected_head', { expectedHead });
      }
      if (snapshot.draft) fail('PULL_REQUEST_DRAFT', `Cannot merge ${n}: it is a draft. Mark it ready for review first.`, snapshot, 'ready_for_review');
      if (snapshot.reviewDecision === 'CHANGES_REQUESTED') fail('CHANGES_REQUESTED', `Cannot merge ${n}: a reviewer requested changes.`, snapshot, 'review');
      if (snapshot.reviewDecision === 'REVIEW_REQUIRED') fail('REVIEW_REQUIRED', `Cannot merge ${n}: a required approving review is missing.`, snapshot, 'review');
      const rollup = snapshot.checks.state;
      if (rollup === 'FAILURE' || rollup === 'ERROR') {
        fail('CHECKS_FAILING', `Cannot merge ${n}: ${snapshot.checks.failing.length || 'some'} required check(s) failed${list(snapshot.checks.failing)}.`, snapshot, 'checks', { failing: snapshot.checks.failing });
      }
      if (rollup === 'PENDING' || rollup === 'EXPECTED') {
        fail('CHECKS_PENDING', `Cannot merge ${n}: ${snapshot.checks.pending.length || 'some'} check(s) are still running${list(snapshot.checks.pending)}. Try again when they finish.`, snapshot, 'checks', { pending: snapshot.checks.pending }, true);
      }
      switch (snapshot.mergeStateStatus) {
        case 'CLEAN': case 'HAS_HOOKS': return;
        case 'UNSTABLE':
          if (rollup === 'SUCCESS' || rollup === null) return;
          return fail('CHECKS_FAILING', `Cannot merge ${n}: non-passing checks make it unstable${list(snapshot.checks.failing)}.`, snapshot, 'checks');
        case 'BEHIND': return fail('BRANCH_BEHIND_BASE', `Cannot merge ${n}: it is behind ${snapshot.base}. Run update_pull_request_branch, then merge the new head.`, snapshot, 'up_to_date');
        case 'DIRTY': return fail('MERGE_CONFLICT', `Cannot merge ${n}: it has merge conflicts with ${snapshot.base}.`, snapshot, 'conflicts');
        case 'BLOCKED': return fail('BRANCH_PROTECTION_BLOCKED', `Cannot merge ${n}: branch protection rules are not satisfied.`, snapshot, 'branch_protection');
        case 'UNKNOWN': return fail('MERGE_STATE_UNKNOWN', `Cannot merge ${n} yet: GitHub is still computing mergeability. Try again in a few seconds.`, snapshot, 'mergeability', {}, true);
        default: return fail('MERGE_STATE_UNSUPPORTED', `Cannot merge ${n}: unexpected merge state ${snapshot.mergeStateStatus}.`, snapshot, 'mergeability');
      }
    }

    File: packages/api/mcp/toolsPullRequests.ts

    Why this file: merge_pull_request and the open checks of the other PR tools live here.

    --- a/packages/api/mcp/toolsPullRequests.ts
    +++ b/packages/api/mcp/toolsPullRequests.ts
    @@
    +import { assertMergeable, assertPullRequestOpen, pullRequestSnapshot, type GraphPullRequest } from './pullRequestPreconditions.js';
    @@ (review/fix/ultrafix, comment_on_pull_request, update_pull_request_branch, revert_pull_request_commit, set_pull_request_model)
    -        if (pr.state !== 'open' || pr.merged) throw new McpError('PRECONDITION_FAILED', 'Pull request is not open.', 409);
    +        assertPullRequestOpen(pullRequestSnapshot(pr), `run /${command} on`);
    @@ tools.push({ name: 'merge_pull_request', ...
         schema: z.object({ ...mutation, method: z.enum(['merge', 'squash', 'rebase']).default('squash') }).strict(), run: async ({ principal, args }) => {
    -      const { owner, repo, pr } = await pull(principal, args);
    -      if (pr.state !== 'open' || pr.draft || pr.merged) throw new McpError('PRECONDITION_FAILED', 'PR must be open and ready for review.', 409);
    -      const result = await principal.github.graphql<{ repository: { pullRequest: { headRefOid: string; mergeStateStatus: string; reviewDecision: string | null; commits: ... } } }>(
    -        `query(...){repository(...){pullRequest(number:$number){headRefOid mergeStateStatus reviewDecision commits(last:1){nodes{commit{statusCheckRollup{state}}}}}}}`, { owner, repo, number: args.pullRequest });
    -      const state = result.repository.pullRequest;
    -      if (state.headRefOid !== args.expectedHead || ...) throw new McpError('CHECKS_NOT_PASSED', '...', 409);
    -      const rollup = state.commits.nodes[0]?.commit.statusCheckRollup;
    -      if (rollup && rollup.state !== 'SUCCESS') throw new McpError('CHECKS_NOT_PASSED', 'Head checks are not all passing.', 409);
    +      // Read without the expectedHead check in pull(): a merged PR must report
    +      // PULL_REQUEST_ALREADY_MERGED, not STALE_HEAD, even if its head moved.
    +      const { owner, repo, pr } = await pull(principal, { repository: args.repository, pullRequest: args.pullRequest });
    +      const result = await principal.github.graphql<{ repository: { pullRequest: GraphPullRequest } }>(
    +        `query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,name:$repo){pullRequest(number:$number){
    +          headRefOid isDraft merged mergedAt closedAt state mergeStateStatus reviewDecision
    +          commits(last:1){nodes{commit{statusCheckRollup{state contexts(first:50){nodes{
    +            ... on CheckRun { name status conclusion } ... on StatusContext { context state } }}}}}}}}}`,
    +        { owner, repo, number: args.pullRequest });
    +      const snapshot = pullRequestSnapshot(pr, result.repository.pullRequest);
    +      assertMergeable(snapshot, args.expectedHead);
           // GitHub atomically checks expected head and repository rules at merge.
    -      const response = await principal.github.request('PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge', { ... });
    -      if (!response.data.merged) throw new McpError('MERGE_REJECTED', response.data.message, 409);
    +      let response;
    +      try {
    +        response = await principal.github.request('PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge', { owner, repo, pull_number: args.pullRequest, sha: args.expectedHead, merge_method: args.method });
    +      } catch (error) {
    +        // 405 (not mergeable) and 409 (head changed) are deliberate rejections:
    +        // report them with GitHub's reason and the state we observed.
    +        const status = (error as { status?: number }).status;
    +        if (status === 405 || status === 409) {
    +          throw new McpError('MERGE_REJECTED', `GitHub rejected the merge of #${args.pullRequest}: ${(error as { response?: { data?: { message?: string } } }).response?.data?.message ?? 'not mergeable'}.`, 409,
    +            { stage: 'github', details: { failedPrecondition: 'github_merge', currentState: snapshot } });
    +        }
    +        throw error;
    +      }
    +      if (!response.data.merged) throw new McpError('MERGE_REJECTED', response.data.message, 409, { stage: 'github', details: { currentState: snapshot } });
           return ok({ merged: true, sha: response.data.sha, url: pr.html_url });
         } });

    File: packages/api/test/mcpMergePreconditions.test.ts (new file)

    Why this file: Table-driven proof for every precondition code, retryability and attached state.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { McpError } from '../mcp/config.js';
    import { assertMergeable, pullRequestSnapshot } from '../mcp/pullRequestPreconditions.js';
    
    const head = 'a'.repeat(40);
    const rest = (over = {}) => ({ number: 42, state: 'open', draft: false, merged: false, head: { sha: head }, base: { ref: 'main' }, html_url: 'u', ...over });
    const graph = (over: Record<string, unknown> = {}, rollup: string | null = 'SUCCESS', contexts: Array<Record<string, string>> = []) => ({
      headRefOid: head, mergeStateStatus: 'CLEAN', reviewDecision: 'APPROVED',
      commits: { nodes: [{ commit: { statusCheckRollup: rollup ? { state: rollup, contexts: { nodes: contexts } } : null } }] }, ...over });
    
    const cases: Array<[string, ReturnType<typeof rest>, ReturnType<typeof graph>, string, boolean]> = [
      ['merged', rest({ state: 'closed', merged: true, merged_at: '2026-09-01T00:00:00Z' }), graph(), 'PULL_REQUEST_ALREADY_MERGED', false],
      ['closed', rest({ state: 'closed' }), graph(), 'PULL_REQUEST_CLOSED', false],
      ['stale', rest(), graph({ headRefOid: 'b'.repeat(40) }), 'STALE_HEAD', false],
      ['draft', rest({ draft: true }), graph(), 'PULL_REQUEST_DRAFT', false],
      ['changes', rest(), graph({ reviewDecision: 'CHANGES_REQUESTED' }), 'CHANGES_REQUESTED', false],
      ['review', rest(), graph({ reviewDecision: 'REVIEW_REQUIRED' }), 'REVIEW_REQUIRED', false],
      ['failing', rest(), graph({}, 'FAILURE', [{ name: 'build', status: 'COMPLETED', conclusion: 'FAILURE' }]), 'CHECKS_FAILING', false],
      ['pending', rest(), graph({}, 'PENDING', [{ name: 'e2e', status: 'IN_PROGRESS' }]), 'CHECKS_PENDING', true],
      ['behind', rest(), graph({ mergeStateStatus: 'BEHIND' }), 'BRANCH_BEHIND_BASE', false],
      ['dirty', rest(), graph({ mergeStateStatus: 'DIRTY' }), 'MERGE_CONFLICT', false],
      ['blocked', rest(), graph({ mergeStateStatus: 'BLOCKED' }), 'BRANCH_PROTECTION_BLOCKED', false],
      ['unknown', rest(), graph({ mergeStateStatus: 'UNKNOWN' }), 'MERGE_STATE_UNKNOWN', true],
    ];
    
    for (const [name, pr, state, code, retryable] of cases) {
      test(`merge precondition: ${name}`, () => {
        assert.throws(() => assertMergeable(pullRequestSnapshot(pr, state), head), (error: unknown) => {
          assert.ok(error instanceof McpError);
          assert.equal(error.code, code);
          assert.equal(error.retryable, retryable);
          assert.equal(error.stage, 'precondition');
          assert.ok((error.details as { currentState?: unknown }).currentState);
          return true;
        });
      });
    }
    
    test('clean approved PR passes', () => {
      assert.doesNotThrow(() => assertMergeable(pullRequestSnapshot(rest(), graph()), head));
    });
  2. propr-dev commented on Sep 29, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 2600/gpt-5.6-sol-mcp-merge_pull_request-an-20260929-1746-4ds
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2600-20260929-1746-gpt-5.6-sol-4ds

    🔍 Track Task Execution

  3. added a commit that references this issue on Sep 29, 2026
  4. added a commit that references this issue on Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions