Skip to content

MCP: add get_work_overview — running or recent tasks joined with their pull requests, review decision and checks in one call #2598

Closed

Description

@propr-dev

Context

Answering "what is running and what is the review state of each PR" currently takes list_tasks → list_pull_requests → get_pull_request per item, with correlation by hand. list_pull_requests (packages/api/mcp/pullRequestInventory.ts) is PR-centric and scans GitHub; list_tasks (packages/api/mcp/tools.ts) is task-centric and never calls GitHub. Neither gives the joined view.

Requirements

  1. New read-only tool get_work_overview (scope read), arguments:
    • repository (optional; omit = every repository in the grant, same resolution as list_tasks),
    • state: active (default) | recent | all — recent = terminal within the window,
    • sinceMinutes (default 1440, max 10080) applies to recent/all,
    • limit (default 20, max 50), offset,
    • includeChecks (default true) — include check rollup and review decision.
  2. Output: { items: [{ task: <compact task summary as list_tasks returns>, pullRequest: null | { number, url, state, draft, head, reviewDecision, checks: { state }, mergeable: 'CLEAN'|..., latestReview: { score, reviewedHead, matchesCurrentHead } | null, ultrafixActive } }], nextOffset, githubLookups: { requested, completed, truncated } }.
  3. Task selection reuses the same query and visibility rules as list_tasks (other users' private goal tasks excluded). Refactor the list_tasks query into a shared function so the two tools cannot drift.
  4. PR enrichment uses one GraphQL request per repository, aliasing each PR number (pr_42: pullRequest(number: 42) { ... }), bounded to 25 PRs per repository and 5 repositories per call (githubLookups.truncated when exceeded). A repository that answers 403/404 is skipped for enrichment (items keep pullRequest.enrichment: 'unavailable') — the task list is still returned.
  5. Merge state from notification_pull_request_state wins over GitHub's closed (same rule as markMergedPullRequests).
  6. latestReview uses the newest ProPR AI review comment (<!-- propr:ai-review ... -->) fetched in the same GraphQL query (comments(last: 10)), parsed with the existing review parser used by get_pull_request_discussion: score, reviewed head, and whether it matches the current head. Comment prose is never returned.
  7. Deterministic ordering: active tasks by updated_at desc, recent by completion time desc.

Implementation Specification

  • New packages/api/mcp/taskListing.ts exporting queryTaskSummaries(db, { repositories, state, principalUserId, offset, limit, since? }) — moved out of the list_tasks tool body, and list_tasks switched to call it (no behaviour change).
  • New packages/api/mcp/toolsWorkOverview.ts with addWorkOverviewTools(tools, deps, listScope) registering get_work_overview, plus enrichPullRequests(principal, repository, numbers).
  • Register in createToolCatalog (tools.ts).
  • Tests packages/api/test/mcpWorkOverview.test.ts with a GraphQL fake asserting a single call per repository.

Acceptance Criteria

  • With two running tasks on PRs AI Fix for Issue #40: Feat: Monitor PR comments for follow-up tasks #42 and #7 in two repos, one call returns both items with reviewDecision, checks.state and latestReview.score, issuing exactly one GraphQL request per repository.
  • A task without a PR returns pullRequest: null.
  • A forbidden repository is skipped (not an error) and a merged-in-ProPR PR shows state: 'merged'.
  • list_tasks output is byte-for-byte unchanged by the refactor (existing mcpGoalTaskDepth.test.ts passes).
  • state: 'recent', sinceMinutes: 60 excludes tasks finished earlier.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The overview is task-first: tasks come from ProPR's database (cheap, authoritative for what ProPR is doing), and only the PRs referenced by the returned page are enriched from GitHub. A PR-first approach (start from list_pull_requests and attach tasks) was rejected because it scans all open PRs of every repository, most of which are unrelated to running work, and pays GitHub quota for them.

    Batching with GraphQL aliases makes the enrichment cost O(repositories) requests instead of O(PRs), and the explicit caps (25 PRs × 5 repositories) keep a single call bounded. We extract the list_tasks query into taskListing.ts so both tools share one visibility predicate — duplicating it would risk leaking private goal tasks through the new tool.

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

    Why this file: Single task-listing query used by list_tasks and get_work_overview.

    import type { Knex } from 'knex';
    import { applyTaskVisibility } from './tools.js';
    import { TERMINAL_TASK_STATES } from './goalTaskDetail.js';
    import { summarizeTask } from './listSummaries.js';
    
    export interface TaskListingOptions {
      repository?: string;           // exact repository, or
      repositories?: string[] | null; // granted repositories when no exact one was given
      state?: 'active' | 'completed' | 'failed' | 'recent' | 'all';
      since?: string;                // ISO lower bound on the latest history timestamp (recent/all)
      userId: string;
      offset: number;
      limit: number;
    }
    
    /** Moved verbatim from the list_tasks tool so both tools share visibility and ordering. */
    export async function queryTaskSummaries(db: Knex, options: TaskListingOptions): Promise<Record<string, unknown>[]> {
      const latestHistoryId = db('task_history').select('history_id')
        .where('task_id', db.ref('tasks.task_id')).orderBy('history_id', 'desc').limit(1);
      const latestState = db('task_history').select('state')
        .where('task_id', db.ref('tasks.task_id')).orderBy('history_id', 'desc').limit(1);
      const latestTimestamp = db('task_history').select('timestamp')
        .where('task_id', db.ref('tasks.task_id')).orderBy('history_id', 'desc').limit(1);
      const taskStart = db('task_history').min('timestamp')
        .where('task_id', db.ref('tasks.task_id')).whereIn('state', ['processing', 'claude_execution', 'post_processing']);
      const latestPlanIssueId = db('plan_issues').select('id')
        .where('task_id', db.ref('tasks.task_id')).orderBy('id', 'desc').limit(1);
      const query = db('tasks');
      if (options.repository) query.where('tasks.repository', options.repository);
      else query.whereIn('tasks.repository', options.repositories ?? []);
      applyTaskVisibility(db, query, options.userId);
      const terminal = TERMINAL_TASK_STATES.map(() => '?').join(', ');
      if (options.state === 'active') query.whereRaw(`coalesce((?), 'pending') not in (${terminal})`, [latestState, ...TERMINAL_TASK_STATES]);
      else if (options.state === 'recent') query.whereRaw(`(?) in (${terminal})`, [latestState, ...TERMINAL_TASK_STATES]);
      else if (options.state === 'completed' || options.state === 'failed') query.whereRaw('(?) = ?', [latestState, options.state]);
      if (options.since) query.whereRaw('(?) >= ?', [latestTimestamp, options.since]);
      const taskPage = query.select('task_id', 'repository', 'issue_number', 'task_type', 'created_at', 'model_name', 'pr_number', 'initial_job_data')
        .orderBy('tasks.created_at', 'desc').orderBy('tasks.task_id', 'desc').offset(options.offset).limit(options.limit).as('tasks');
      const rows = await db.from(taskPage)
        .leftJoin('task_history as latest_history', 'latest_history.history_id', db.raw('(?)', [latestHistoryId]))
        .leftJoin('plan_issues as task_plan_issue', 'task_plan_issue.id', db.raw('(?)', [latestPlanIssueId]))
        .select('tasks.*', 'latest_history.state', 'latest_history.timestamp as updated_at', 'latest_history.reason as state_reason',
          'latest_history.metadata as state_metadata', taskStart.as('started_at'),
          'task_plan_issue.pr_number as plan_pr_number', 'task_plan_issue.status as plan_issue_status',
          'task_plan_issue.agent_alias as plan_agent_alias', 'task_plan_issue.model_name as plan_model_name')
        .orderBy('tasks.created_at', 'desc').orderBy('tasks.task_id', 'desc');
      return rows.map(row => summarizeTask(row));
    }

    In tools.ts, replace the body of list_tasks with:

    const tasks = await queryTaskSummaries(db, { repository: args.repository, repositories: await listScope(principal, args),
      state: args.state, userId: principal.user.id, offset: args.offset, limit: args.limit });
    await markMergedListPullRequests(db, tasks);
    return ok({ tasks, nextOffset: tasks.length === args.limit ? args.offset + args.limit : null });

    and pass listScope into addWorkOverviewTools.

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

    Why this file: Hosts the new joined view and its GitHub batching, keeping tools.ts from growing further.

    import { z } from 'zod';
    import type { McpPrincipal } from './policy.js';
    import { McpError } from './config.js';
    import { type Args, type McpTool, type ToolDeps, markMergedListPullRequests, ok, repositorySchema } from './tools.js';
    import { queryTaskSummaries } from './taskListing.js';
    import { parseReviewMarker } from './reviewDiscussion.js'; // existing parser used by get_pull_request_discussion
    
    const MAX_PRS_PER_REPOSITORY = 25;
    const MAX_REPOSITORIES = 5;
    
    interface PullRequestEnrichment {
      number: number; url: string; state: 'open' | 'closed' | 'merged'; draft: boolean; head: string;
      reviewDecision: string | null; checks: { state: string | null }; mergeable: string | null; ultrafixActive: boolean | null;
      latestReview: { score: number | null; reviewedHead: string | null; matchesCurrentHead: boolean | null } | null;
    }
    
    /** One GraphQL round trip per repository; PR numbers become field aliases. */
    async function enrichPullRequests(principal: McpPrincipal, repository: string, numbers: number[], includeChecks: boolean)
      : Promise<Map<number, PullRequestEnrichment>> {
      const [owner, repo] = repository.split('/');
      // Numbers are validated integers, so interpolating them into aliases is safe.
      const fields = numbers.map(number => `pr_${number}: pullRequest(number: ${number}) {
        number url state isDraft merged headRefOid ${includeChecks ? 'reviewDecision mergeStateStatus commits(last:1){nodes{commit{statusCheckRollup{state}}}}' : ''}
        labels(first: 100) { pageInfo { hasNextPage } nodes { name } }
        comments(last: 10) { nodes { body } } }`).join('\n');
      const result = await principal.github.graphql<{ repository: Record<string, any> }>( // eslint-disable-line @typescript-eslint/no-explicit-any
        `query($owner:String!,$repo:String!){repository(owner:$owner,name:$repo){${fields}}}`, { owner, repo });
      const map = new Map<number, PullRequestEnrichment>();
      for (const number of numbers) {
        const pr = result.repository?.[`pr_${number}`];
        if (!pr) continue;
        const labels: string[] = pr.labels?.nodes?.map((label: { name: string }) => label.name) ?? [];
        // Newest ProPR review marker; prose is discarded, only score/head are kept.
        const reviewComment = [...(pr.comments?.nodes ?? [])].reverse().find((comment: { body?: string }) => comment.body?.includes('<!-- propr:ai-review'));
        const review = reviewComment ? parseReviewMarker(reviewComment.body) : null;
        map.set(number, {
          number, url: pr.url, state: pr.merged ? 'merged' : pr.state === 'OPEN' ? 'open' : 'closed', draft: pr.isDraft, head: pr.headRefOid,
          reviewDecision: pr.reviewDecision ?? null, checks: { state: pr.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state ?? null },
          mergeable: pr.mergeStateStatus ?? null,
          ultrafixActive: labels.includes('ultrafix') ? true : pr.labels?.pageInfo?.hasNextPage ? null : false,
          latestReview: review ? { score: review.score ?? null, reviewedHead: review.head ?? null,
            matchesCurrentHead: review.head ? review.head === pr.headRefOid : null } : null,
        });
      }
      return map;
    }
    
    export function addWorkOverviewTools(tools: McpTool[], deps: ToolDeps,
      listScope: (principal: McpPrincipal, args: Args) => Promise<string[] | null>): void {
      tools.push({ name: 'get_work_overview', description: 'One call for "what is running and what is the review state of each PR": your running (or recently finished) tasks, each joined with its pull request, review decision, check state, latest ProPR review score and ultrafix state. Omit repository to cover the grant. GitHub is queried once per repository and bounded; githubLookups.truncated says when some PRs were not enriched.', scope: 'read', readOnly: true,
        schema: z.object({ repository: repositorySchema.optional(), state: z.enum(['active', 'recent', 'all']).default('active'),
          sinceMinutes: z.number().int().min(1).max(10080).default(1440), includeChecks: z.boolean().default(true),
          offset: z.number().int().min(0).max(10000).default(0), limit: z.number().int().min(1).max(50).default(20) }).strict(),
        run: async ({ principal, args }) => {
          const since = args.state === 'active' ? undefined : new Date(Date.now() - args.sinceMinutes * 60_000).toISOString().replace('T', ' ').slice(0, 19);
          const tasks = await queryTaskSummaries(deps.db, { repository: args.repository, repositories: await listScope(principal, args),
            state: args.state, since, userId: principal.user.id, offset: args.offset, limit: args.limit });
          await markMergedListPullRequests(deps.db, tasks);
          // Group referenced PRs by repository, enforcing the per-call bounds.
          const wanted = new Map<string, number[]>();
          for (const task of tasks) {
            const number = Number(task.pr_number);
            if (!Number.isSafeInteger(number) || number <= 0) continue;
            const list = wanted.get(String(task.repository)) ?? [];
            if (!list.includes(number)) list.push(number);
            wanted.set(String(task.repository), list);
          }
          const lookups = { requested: 0, completed: 0, truncated: false };
          const enrichments = new Map<string, Map<number, PullRequestEnrichment> | 'unavailable'>();
          for (const [repository, numbers] of [...wanted.entries()]) {
            lookups.requested += numbers.length;
            if (enrichments.size >= MAX_REPOSITORIES) { lookups.truncated = true; continue; }
            if (numbers.length > MAX_PRS_PER_REPOSITORY) lookups.truncated = true;
            try {
              const map = await enrichPullRequests(principal, repository, numbers.slice(0, MAX_PRS_PER_REPOSITORY), args.includeChecks);
              enrichments.set(repository, map);
              lookups.completed += map.size;
            } catch (error) {
              // A repository the credential can no longer read degrades to task-only rows.
              if (error instanceof McpError) throw error;
              enrichments.set(repository, 'unavailable');
            }
          }
          const items = tasks.map(task => {
            const number = Number(task.pr_number);
            if (!Number.isSafeInteger(number) || number <= 0) return { task, pullRequest: null };
            const repoEnrichment = enrichments.get(String(task.repository));
            const enriched = repoEnrichment && repoEnrichment !== 'unavailable' ? repoEnrichment.get(number) : undefined;
            const base = { number, url: `https://github.com/${task.repository}/pull/${number}` };
            if (!enriched) return { task, pullRequest: { ...base, state: task.pr_state ?? null, enrichment: 'unavailable' as const } };
            // ProPR's merge record is authoritative over GitHub's closed state.
            return { task, pullRequest: { ...enriched, state: task.pr_state === 'merged' ? 'merged' : enriched.state } };
          });
          return ok({ items, nextOffset: tasks.length === args.limit ? args.offset + args.limit : null, githubLookups: lookups });
        } });
    }

    If reviewDiscussion.ts does not already export a marker parser returning { score, head }, extract the parsing used by projectDiscussionComment into an exported parseReviewMarker(body) rather than duplicating the regex.

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

    Why this file: Verifies the join, the bounded single-request-per-repository behaviour, and graceful degradation.

    // Fixture pattern: copy from mcpGoalTaskDepth.test.ts (migrated in-memory SQLite, stubbed loadMonitoredReposRaw,
    // policy.repository throws 403 for acme/forbidden).
    // github.graphql fake records calls and returns { repository: { pr_42: {...}, pr_7: {...} } } keyed by aliases.
    // Assertions:
    // - two repositories -> graphql called exactly twice;
    // - item for task on PR 42 has reviewDecision 'APPROVED', checks.state 'SUCCESS', latestReview.score 8;
    // - task without PR -> pullRequest null;
    // - PR merged in notification_pull_request_state -> state 'merged' although GraphQL says CLOSED;
    // - graphql throwing { status: 403 } for one repository -> its items carry enrichment 'unavailable', call still succeeds.
  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: 2598/gpt-5.6-sol-mcp-add-get_work_overview-20260929-1602-r1y
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2598-20260929-1602-gpt-5.6-sol-r1y

    🔍 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