Skip to content

MCP PR commands: make expectedHead optional on append-only commands and report the resolved head in the receipt #2599

Closed

Description

@propr-dev

Context

review_pull_request, fix_review_findings, run_ultrafix and comment_on_pull_request (all in packages/api/mcp/toolsPullRequests.ts) share a mutation schema that requires expectedHead: /^[0-9a-f]{40}$/. Every call therefore needs a preceding get_pull_request just to fetch the SHA, doubling round trips for the most common operations.

For these commands the pin gives little real safety: they are append-only — they post a comment that queues work, and the worker acts on whatever the head is when it starts, which can already be newer than the pinned SHA. The guarantee is largely illusory.

The pin does protect against acting on unseen code for merge_pull_request, update_pull_request_branch and stop_ultrafix (a moved head may be a human fix the loop should still see), and for revert_pull_request_commit and set_pull_request_model (not in scope to change). Those keep it required.

Requirements

  1. Split the schema: appendOnlyMutation (expectedHead optional) for review_pull_request, fix_review_findings, run_ultrafix, comment_on_pull_request; the existing mutation (required) stays for everything else.
  2. When expectedHead is supplied: behaviour is unchanged — mismatch still fails with STALE_HEAD (now with details: { expectedHead, currentHead } and stage: 'precondition').
  3. When omitted: the head is read from the pull request fetched by the tool itself (the tool already fetches it), no extra request.
  4. Every receipt of these four tools includes resolvedHead (the SHA acted on) and headSource: 'caller' | 'server'. The hidden marker comment keeps using the resolved head (head:<sha>), so review/fix tracking and stale-finding detection work identically.
  5. For fix_review_findings, the stale-review check (review.matchesCurrentHead === false → STALE_FINDINGS) keeps comparing against the current head, whether supplied or resolved.
  6. Idempotency: expectedHead omitted vs supplied are different argument payloads; the existing IDEMPOTENCY_CONFLICT semantics are unchanged. Document that retries must repeat the same arguments.
  7. Tool descriptions state: "expectedHead is optional; when omitted the current head at call time is used and returned as resolvedHead. Supply it to require that no new commits arrived since you read the PR."
  8. merge_pull_request, update_pull_request_branch, stop_ultrafix descriptions explicitly say expectedHead is required and why.
  9. Update docs/mcp.md ("Act on it, at an exact head") and docs/mcp-coverage.md rows accordingly.

Implementation Specification

  • Edit packages/api/mcp/toolsPullRequests.ts only (plus the two docs files).
  • Extend packages/api/test/fixtures/mcpPullRequestWrites.js/ts tests (verifyPullRequestWrites) or add cases in packages/api/test/mcpPullRequests.test.ts.

Acceptance Criteria

  • comment_on_pull_request without expectedHead posts once, and the receipt has resolvedHead === <current head> and headSource === 'server'; the posted body ends with head:<current head> -->.
  • run_ultrafix with a stale expectedHead still fails with STALE_HEAD, and details.currentHead is present.
  • merge_pull_request, update_pull_request_branch and stop_ultrafix without expectedHead fail schema validation (INVALID_INPUT).
  • The tools/list schema for the four append-only tools lists expectedHead as optional.
  • Only one GET /pulls/{n} is made per call in both modes.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We make the pin optional, not removed: callers that want the stronger precondition keep it, and existing clients that always send it see no behaviour change. The server resolves the head from the PR it already fetches, so omitting it costs nothing extra. Reporting resolvedHead + headSource keeps the receipt honest about exactly which revision was targeted — the caller loses no information versus pinning.

    Keeping the requirement for merge/update-branch/stop_ultrafix follows the request: those act on (or stop acting on) the current code and a moved head may mean a human change the caller has not seen.

    File: packages/api/mcp/toolsPullRequests.ts

    Why this file: All four append-only tools and the shared pull() helper live here.

    --- a/packages/api/mcp/toolsPullRequests.ts
    +++ b/packages/api/mcp/toolsPullRequests.ts
    @@ -115,14 +115,27 @@ export function addPullRequestTools(tools: McpTool[], deps: ToolDeps): void {
       const tasks = createTaskRoutes({ db: deps.db, taskQueue: deps.taskQueue });
       const shape = { repository: repositorySchema, pullRequest: z.number().int().positive() };
    -  const mutation = { ...shape, ...mutationShape, expectedHead: z.string().regex(/^[0-9a-f]{40}$/) };
    +  const headSchema = z.string().regex(/^[0-9a-f]{40}$/);
    +  // Required: these act on the current code, so an unseen push must stop them.
    +  const mutation = { ...shape, ...mutationShape, expectedHead: headSchema };
    +  // Optional: append-only commands queue work that runs on whatever the head is
    +  // when the worker starts, so a pin adds a round trip without real safety.
    +  const appendOnlyMutation = { ...shape, ...mutationShape,
    +    expectedHead: headSchema.optional().describe('Optional. When omitted the current head at call time is used and returned as resolvedHead. Supply it to require that no new commits arrived since you read the PR.') };
       const pull = async (principal: Parameters<McpTool['run']>[0]['principal'], args: Record<string, any>) => { // eslint-disable-line @typescript-eslint/no-explicit-any
         const [owner, repo] = args.repository.split('/');
         const response = await principal.github.request('GET /repos/{owner}/{repo}/pulls/{pull_number}', { owner, repo, pull_number: args.pullRequest });
    -    if (args.expectedHead && response.data.head.sha !== args.expectedHead) throw new McpError('STALE_HEAD', 'Pull request head changed. Read it again.', 409);
    -    return { owner, repo, pr: response.data };
    +    if (args.expectedHead && response.data.head.sha !== args.expectedHead) {
    +      throw new McpError('STALE_HEAD', `Pull request head changed from ${args.expectedHead.slice(0, 7)} to ${response.data.head.sha.slice(0, 7)}. Read it again, or omit expectedHead on append-only commands.`, 409,
    +        { stage: 'precondition', details: { expectedHead: args.expectedHead, currentHead: response.data.head.sha } });
    +    }
    +    // The SHA this call acts on, and whether the caller pinned it.
    +    const resolvedHead: string = args.expectedHead ?? response.data.head.sha;
    +    const headSource: 'caller' | 'server' = args.expectedHead ? 'caller' : 'server';
    +    return { owner, repo, pr: response.data, resolvedHead, headSource };
       };
    @@ for (const [name, command, scope] of [...]) {
    -    tools.push({ name, description: `Request the existing /${command} command at an exact PR head. Returns a durable receipt; normal instance event intake starts work.`
    +    tools.push({ name, description: `Request the existing /${command} command on an open PR. expectedHead is optional; when omitted the current head is used and returned as resolvedHead. Returns a durable receipt (follow it with get_operation); normal instance event intake starts work.`
    @@
    -      schema: z.object({ ...mutation, instructions: textSchema.optional(), ...
    +      schema: z.object({ ...appendOnlyMutation, instructions: textSchema.optional(), ...
           run: async ({ principal, args, operationId }) => {
             if (command === 'ultrafix') deps.policy.requireScope(principal, 'review');
    -        const { owner, repo, pr } = await pull(principal, args);
    +        const { owner, repo, pr, resolvedHead, headSource } = await pull(principal, args);
             if (pr.state !== 'open' || pr.merged) throw new McpError('PRECONDITION_FAILED', 'Pull request is not open.', 409);
    @@
    -        const body = `/${command}...${args.instructions ? `\n\n${args.instructions}` : ''}\n\n<!-- propr-mcp:${operationId}; head:${args.expectedHead} -->`;
    +        // The marker records the head actually targeted so review/fix tracking is unchanged.
    +        const body = `/${command}...${args.instructions ? `\n\n${args.instructions}` : ''}\n\n<!-- propr-mcp:${operationId}; head:${resolvedHead} -->`;
             const { data } = await principal.github.request('POST /repos/{owner}/{repo}/issues/{issue_number}/comments', { owner, repo, issue_number: args.pullRequest, body });
    -        return { status: 202, data: { repository: args.repository, pullRequest: args.pullRequest, commentId: data.id, url: data.html_url, expectedHead: args.expectedHead, state: 'posted', ... } };
    +        return { status: 202, data: { repository: args.repository, pullRequest: args.pullRequest, commentId: data.id, url: data.html_url,
    +          // expectedHead kept for old clients; resolvedHead is always the SHA acted on.
    +          expectedHead: args.expectedHead ?? null, resolvedHead, headSource, state: 'posted',
    +          ...(command === 'ultrafix' ? { goal: args.goal, maxCycles: args.maxCycles } : {}), ... } };
    @@
    -  tools.push({ name: 'comment_on_pull_request', description: 'Post an ordinary natural-language follow-up comment on an open PR at its exact head, ...
    -    schema: z.object({ ...mutation, message: textSchema }).strict(), run: async ({ principal, args, operationId }) => {
    +  tools.push({ name: 'comment_on_pull_request', description: 'Post an ordinary natural-language follow-up comment on an open PR, which is how ProPR queues a scoped refinement. expectedHead is optional; the head acted on is returned as resolvedHead. Slash commands are rejected; use the dedicated command tool instead.', scope: 'execute',
    +    schema: z.object({ ...appendOnlyMutation, message: textSchema }).strict(), run: async ({ principal, args, operationId }) => {
           if (SLASH_COMMAND.test(args.message)) throw ...;
    -      const { owner, repo, pr } = await pull(principal, args);
    +      const { owner, repo, pr, resolvedHead, headSource } = await pull(principal, args);
           ...
    -      const body = `${args.message}\n\n<!-- propr-mcp:${operationId}; head:${args.expectedHead} -->`;
    +      const body = `${args.message}\n\n<!-- propr-mcp:${operationId}; head:${resolvedHead} -->`;
           ...
    -      return { status: 202, data: { ..., expectedHead: args.expectedHead, state: 'posted' } };
    +      return { status: 202, data: { ..., expectedHead: args.expectedHead ?? null, resolvedHead, headSource, state: 'posted' } };
         } });

    resolveFixSelection already takes head from the caller; pass resolvedHead (which equals pr.head.sha when omitted, or the verified pinned SHA when supplied — identical after the STALE_HEAD check):

    -          ? await resolveFixSelection(deps, principal, args, pr.head.sha)
    +          ? await resolveFixSelection(deps, principal, args, resolvedHead)

    Update the three pinned tools' descriptions to explain the requirement, e.g. for stop_ultrafix:

    -  tools.push({ name: 'stop_ultrafix', description: 'Clear the ultrafix circuit breaker by removing the ultrafix label, ...
    +  tools.push({ name: 'stop_ultrafix', description: 'Clear the ultrafix circuit breaker by removing the ultrafix label, so the loop starts no further cycle. expectedHead is required: a moved head may be a human fix the loop should still see. A cycle already running may still finish; this does not claim the loop stopped. Requires review scope.',

    (merge_pull_request: "expectedHead is required: merging must never include commits you have not reviewed." update_pull_request_branch: "expectedHead is required so a concurrent push is not silently merged over.")

    File: docs/mcp.md

    Why this file: The operator walkthrough currently says "Every write takes the expectedHead you just read"; that is no longer true and would push agents into the extra round trip.

    -**4. Act on it, at an exact head.** Every write takes the `expectedHead` you just read
    -and an 8–128 character `idempotencyKey`; a changed head fails with
    -`STALE_HEAD` rather than acting on a revision you did not see.
    +**4. Act on it.** Append-only commands (`comment_on_pull_request`,
    +`review_pull_request`, `fix_review_findings`, `run_ultrafix`) take an optional
    +`expectedHead`: omit it and the server uses the current head and returns it as
    +`resolvedHead` (`headSource: "server"`); supply it to fail with `STALE_HEAD` if
    +new commits arrived. `merge_pull_request`, `update_pull_request_branch` and
    +`stop_ultrafix` always require `expectedHead`. Every write takes an 8–128
    +character `idempotencyKey`.

    File: packages/api/test/mcpPullRequests.test.ts

    Why this file: Existing PR surface tests and the verifyPullRequestWrites fixture already drive these tools against a GitHub fake.

    await t.test('append-only commands resolve the head server-side when expectedHead is omitted', async () => {
      const before = restCalls.filter(call => call.route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}').length;
      const receipt = await mutate('comment_on_pull_request', { repository: 'acme/repo', pullRequest: 42, message: 'Please add a test.' });
      const result = receipt.result as Args;
      assert.equal(result.resolvedHead, 'a'.repeat(40));
      assert.equal(result.headSource, 'server');
      assert.match(comments.at(-1)!.body, new RegExp(`head:${'a'.repeat(40)} -->$`));
      assert.equal(restCalls.filter(call => call.route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}').length - before, 1);
      const stale = await mutate('run_ultrafix', { repository: 'acme/repo', pullRequest: 42, expectedHead: 'b'.repeat(40) });
      assert.equal((stale.result as Args).error.code, 'STALE_HEAD');
      assert.equal((stale.result as Args).error.details.currentHead, 'a'.repeat(40));
      await assert.rejects(call('merge_pull_request', { repository: 'acme/repo', pullRequest: 42, idempotencyKey: 'merge-no-head-1' }));
    });
  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: 2599/gpt-5.6-sol-mcp-pr-commands-make-expe-20260929-1729-lpd
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2599-20260929-1729-gpt-5.6-sol-lpd

    🔍 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