Skip to content

MCP task submissions: expose submission progress through to task state and pull request, add list_task_submissions and a submission resource #2597

Closed

Description

@propr-dev

Context

create_task (in packages/api/mcp/toolsTaskSubmissions.ts) returns a receipt with submissionId, submissionState and, once associated, taskId. get_task_submission reads the task_submissions row, but its projection (projectSubmission) only includes { id, state, issueNumber, issueUrl, taskId, error }. It does not tell the caller:

  • whether the associated task is queued, running, completed or failed (the caller has to call get_task separately and needs to know the task id first),
  • whether a pull request has appeared (needs list_tasks/list_pull_requests and manual correlation),
  • the failure reason when the task failed.

The request is: "Add a way to read a submission's current state by id, so the caller can follow a queued task through to its task id and its PR without blind polling of list_tasks."

Requirements

  1. Extend get_task_submission output with a progress block, computed server-side in one read:
    {
      "progress": {
        "stage": "submitted" | "issue_created" | "queued" | "running" | "completed" | "failed" | "cancelled",
        "issue": { "number": 123, "url": "https://github.com/a/b/issues/123" } | null,
        "task": { "id": "...", "state": "claude_execution", "updatedAt": "...", "startedAt": "...", "failureReason": null } | null,
        "pullRequest": { "number": 45, "url": "https://github.com/a/b/pull/45", "state": "open" | "merged" | "closed" | null } | null,
        "next": "Poll again in ~30s; the agent is implementing." // one human sentence
      }
    }
    • stage derivation: submission prepared/creating → submitted; issue_created → issue_created; queued without task → queued; task latest history state in (pending,queued) → queued; (processing,claude_execution,post_processing) → running; completed/failed/cancelled → same; submission failed → failed (with error).
    • Task and PR use the latest task for the submission (latest_task_id column, falling back to task_id), matching retries.
    • pullRequest.number from tasks.pr_number, falling back to final_result.postProcessing.pr.number (same fallback taskHelpers.ts uses); state via notification_pull_request_state.merged_at (merged) else null (unknown without a GitHub call). Do not call GitHub from this read.
    • failureReason is the latest history reason when state is failed, redacted via redactSecrets.
  2. Include the same progress in create_task / retry_task_submission receipts when polled through get_operation (via trackTaskSubmission), so receipts and the direct read agree. Also record artifacts (submissionId, taskId, pullRequest) on the operation lifecycle.
  3. New tool list_task_submissions (scope read): your submissions (owner-scoped by user_id), optional repository, stage filter (active = submitted/issue_created/queued/running, or an exact stage), sinceMinutes (default 1440, max 10080), paginated (limit ≤ 50), newest first, each item with the progress block.
  4. New MCP resource propr://instances/{instance_id}/submissions/{submission_id} that reads through get_task_submission guards (register next to the existing task/goal resources in server.ts).
  5. create_task description updated: "Follow progress with get_task_submission (task state and pull request) instead of polling list_tasks."

Implementation Specification

  • New helper packages/api/mcp/submissionProgress.ts exporting submissionProgress(db, row) and progressStage(...).
  • Edit packages/api/mcp/toolsTaskSubmissions.ts: use the helper in get_task_submission, trackTaskSubmission, add list_task_submissions.
  • Edit packages/api/mcp/server.ts: register the submission resource.
  • Tests: extend packages/api/test/mcpTaskSubmissions.test.ts.

Acceptance Criteria

  • After create_task, get_task_submission shows progress.stage === 'queued' and the issue link.
  • Inserting a task with history processing and associating it moves stage to running with progress.task.id set.
  • Setting tasks.pr_number = 45 and history completed yields stage === 'completed' and progress.pullRequest.number === 45; with a notification_pull_request_state merged row, state === 'merged'.
  • A failed task yields stage === 'failed' and a redacted failureReason.
  • list_task_submissions({ stage: 'active' }) returns only the caller's active submissions; another user sees none.
  • No GitHub request is made by get_task_submission or list_task_submissions (assert fake Octokit call count unchanged).

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 28, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We compute submission progress purely from ProPR's database (task_submissions, tasks, task_history, notification_pull_request_state). Calling GitHub for PR state on every poll was rejected: pollers call frequently, quota is shared with workers, and ProPR already persists the PR number and merge state. The PR state is therefore merged when known and null otherwise, and the caller can use get_pull_request (or the new work overview) for review/check state.

    A single helper shared by the direct read, the receipt tracker and the list tool guarantees the three surfaces never disagree.

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

    Why this file: One derivation for "where is my submission now", consumed by three tools.

    import type { Knex } from 'knex';
    import type { TaskSubmission } from '@propr/core';
    import { redactSecrets } from './errorEnvelope.js';
    
    export type SubmissionStage = 'submitted' | 'issue_created' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
    export const ACTIVE_SUBMISSION_STAGES: SubmissionStage[] = ['submitted', 'issue_created', 'queued', 'running'];
    const RUNNING = ['processing', 'claude_execution', 'post_processing'];
    
    export interface SubmissionProgress {
      stage: SubmissionStage;
      issue: { number: number; url: string | null } | null;
      task: { id: string; state: string | null; updatedAt: string | null; startedAt: string | null; failureReason: string | null } | null;
      pullRequest: { number: number; url: string; state: 'merged' | null } | null;
      next: string;
    }
    
    function prFromFinalResult(value: unknown): number | null {
      try {
        const parsed = typeof value === 'string' ? JSON.parse(value) : value;
        const number = Number(parsed?.postProcessing?.pr?.number);
        return Number.isSafeInteger(number) && number > 0 ? number : null;
      } catch { return null; }
    }
    
    export function progressStage(submission: Pick<TaskSubmission, 'state' | 'error'>, taskState: string | null): SubmissionStage {
      if (taskState) {
        if (RUNNING.includes(taskState)) return 'running';
        if (taskState === 'completed' || taskState === 'failed' || taskState === 'cancelled') return taskState;
        return 'queued';
      }
      if (submission.state === 'failed') return 'failed';
      if (submission.state === 'queued') return 'queued';
      if (submission.state === 'issue_created') return 'issue_created';
      return 'submitted';
    }
    
    const NEXT: Record<SubmissionStage, string> = {
      submitted: 'The GitHub issue is being created. Poll again in a few seconds.',
      issue_created: 'The issue exists; implementation is being dispatched. Poll again in a few seconds.',
      queued: 'The task is queued for a worker. Poll again in ~30 seconds.',
      running: 'The agent is implementing. Poll again in ~30-60 seconds, or read get_agent_activity for narration.',
      completed: 'The task finished. Review the pull request if one was opened.',
      failed: 'The task failed. Read failureReason, then retry_task_submission or send_task_followup.',
      cancelled: 'The task was cancelled.',
    };
    
    export async function submissionProgress(db: Knex, row: TaskSubmission & { latest_task_id?: string | null }): Promise<SubmissionProgress> {
      // Retries re-associate a new task; the latest one is what the caller cares about.
      const taskId = row.latest_task_id || row.task_id || null;
      let task: SubmissionProgress['task'] = null;
      let pullRequest: SubmissionProgress['pullRequest'] = null;
      if (taskId) {
        const [taskRow, latest, started] = await Promise.all([
          db('tasks').where({ task_id: taskId }).first('pr_number', 'final_result'),
          db('task_history').where({ task_id: taskId }).orderBy('history_id', 'desc').first('state', 'reason', 'timestamp'),
          db('task_history').where({ task_id: taskId }).whereIn('state', RUNNING).min('timestamp as startedAt').first(),
        ]);
        task = {
          id: taskId, state: latest?.state ?? null, updatedAt: latest?.timestamp ?? null, startedAt: started?.startedAt ?? null,
          failureReason: latest?.state === 'failed' && latest.reason ? redactSecrets(String(latest.reason)).slice(0, 500) : null,
        };
        const number = Number(taskRow?.pr_number) || prFromFinalResult(taskRow?.final_result);
        if (number) {
          const merged = await db('notification_pull_request_state').where({ repository: row.repository, pr_number: number }).whereNotNull('merged_at').first('pr_number');
          pullRequest = { number, url: `https://github.com/${row.repository}/pull/${number}`, state: merged ? 'merged' : null };
        }
      }
      const stage = progressStage(row, task?.state ?? null);
      return {
        stage,
        issue: row.issue_number ? { number: row.issue_number, url: row.issue_url } : null,
        task, pullRequest,
        next: stage === 'failed' && !task && row.error ? `Submission failed: ${redactSecrets(row.error)}. Use retry_task_submission.` : NEXT[stage],
      };
    }

    File: packages/api/mcp/toolsTaskSubmissions.ts

    Why this file: Owns the submission tools and trackTaskSubmission; all three consumers of the helper live here.

    --- a/packages/api/mcp/toolsTaskSubmissions.ts
    +++ b/packages/api/mcp/toolsTaskSubmissions.ts
    @@
    -import { type McpTool, type ToolDeps, mutationShape, repositorySchema, idSchema, ok } from './tools.js';
    +import { type McpTool, type ToolDeps, mutationShape, repositorySchema, idSchema, ok } from './tools.js';
    +import { ACTIVE_SUBMISSION_STAGES, submissionProgress, type SubmissionStage } from './submissionProgress.js';
    +import { McpOperations } from './operations.js';
    @@
    -  tools.push({ name: 'create_task', description: 'Create a GitHub issue and immediately START ... inspect the submission or operation before retrying.', scope: 'execute',
    +  tools.push({ name: 'create_task', description: 'Create a GitHub issue and immediately START ... inspect the submission or operation before retrying. Follow progress with get_task_submission (task state and pull request) instead of polling list_tasks.', scope: 'execute',
    @@
    -  tools.push({ name: 'get_task_submission', description: 'Read your direct task submission, GitHub issue link and exact taskId once execution is associated. Does not retry or start work.', scope: 'read', readOnly: true,
    +  tools.push({ name: 'get_task_submission', description: 'Read your direct task submission with its progress: GitHub issue, associated task and its lifecycle state, failure reason, and the pull request once opened. Does not retry or start work and makes no GitHub calls.', scope: 'read', readOnly: true,
         schema: z.object(shape).strict(), target, run: async ({ principal, args }) => {
           const row = await ownedSubmission(deps, principal, args.repository, args.submissionId);
    -      return ok(projectSubmission(row));
    +      return ok({ ...projectSubmission(row), progress: await submissionProgress(deps.db, row) });
         } });
    +  tools.push({ name: 'list_task_submissions', description: 'List your recent direct task submissions, newest first, each with its progress (task state and pull request). stage=active covers work that has not finished.', scope: 'read', readOnly: true,
    +    schema: z.object({ repository: shape.repository.optional(),
    +      stage: z.enum(['active', 'submitted', 'issue_created', 'queued', 'running', 'completed', 'failed', 'cancelled']).optional(),
    +      sinceMinutes: z.number().int().min(1).max(10080).default(1440), limit: z.number().int().min(1).max(50).default(20) }).strict(),
    +    run: async ({ principal, args }) => {
    +      if (args.repository) await deps.policy.repository(principal, args.repository);
    +      const since = new Date(Date.now() - args.sinceMinutes * 60_000).toISOString();
    +      const query = deps.db<TaskSubmission>('task_submissions').where({ user_id: principal.user.id }).where('created_at', '>=', since);
    +      if (args.repository) query.where({ repository: args.repository });
    +      // Stage is derived from joined task history, so over-fetch a bounded window and filter in memory.
    +      const rows = await query.orderBy('created_at', 'desc').limit(Math.min(args.limit * 4, 200));
    +      const items = [];
    +      for (const row of rows) {
    +        const progress = await submissionProgress(deps.db, row);
    +        const wanted: SubmissionStage[] | null = args.stage === 'active' ? ACTIVE_SUBMISSION_STAGES : args.stage ? [args.stage] : null;
    +        if (wanted && !wanted.includes(progress.stage)) continue;
    +        items.push({ ...projectSubmission(row), repository: row.repository, createdAt: row.created_at, progress });
    +        if (items.length === args.limit) break;
    +      }
    +      return ok({ submissions: items, truncated: rows.length === Math.min(args.limit * 4, 200) });
    +    } });
    @@ export async function trackTaskSubmission(...)
       const current = projectSubmission(submission);
       const taskId = result.continuation?.taskId || submission.task_id;
       if (taskId) { current.taskId = taskId; current.continuation.taskId = taskId; }
    +  const progress = await submissionProgress(deps.db, submission);
       receipt.state = current.state;
    -  receipt.result = current;
    +  receipt.result = { ...current, progress };
       receipt.targetState = { submissionId: submission.id, state: submission.state, taskId };
    +  // Persist artefacts on the receipt lifecycle so list_operations shows them.
    +  await new McpOperations(deps.db).recordArtifacts(row.id, { submissionId: submission.id, ...(taskId ? { taskId } : {}),
    +    ...(progress.pullRequest ? { pullRequest: { repository: submission.repository, number: progress.pullRequest.number, url: progress.pullRequest.url } } : {}) });

    Keep the existing row.result = JSON.stringify(current) write in trackTaskSubmission storing without progress (progress is derived on read; persisting it would go stale).

    File: packages/api/mcp/server.ts

    Why this file: Resources are registered here (tasks/{id}, goals/{id} …). The submission resource must reuse the tool guards, exactly like existing resources invoke get_task/get_goal.

    // Next to the tasks/{task_id} resource registration:
    // URI: propr://instances/{instance_id}/submissions/{submission_id}?repository=owner/repo
    // Handler: executeTool(catalog 'get_task_submission', { repository, submissionId }, principal, deps)
    // and return the JSON as a text resource, identical to how tasks/{task_id} is served.

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

    Why this file: Existing fixtures already build submissions, tasks and history in SQLite; extend them.

    test('get_task_submission follows the submission to its task and pull request', async () => {
      const f = await fixture();
      try {
        await f.db.schema.alterTable('tasks', table => { table.integer('pr_number'); table.text('final_result'); });
        await f.db.schema.createTable('notification_pull_request_state', t => { t.string('repository'); t.integer('pr_number'); t.string('merged_at'); });
        await f.call('create_task', { repository: 'owner/repo', instruction: 'Fix dates', idempotencyKey: 'progress-key-1' });
        const stored = await f.db('task_submissions').first();
        const read = async () => (await f.call('get_task_submission', { repository: 'owner/repo', submissionId: stored.id })).data as { progress: Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
        assert.equal((await read()).progress.stage, 'queued');
        await f.db('tasks').insert({ task_id: 't-1', repository: 'owner/repo', task_type: 'issue' });
        await f.db('task_submissions').update({ task_id: 't-1', latest_task_id: 't-1' });
        await f.db('task_history').insert({ task_id: 't-1', state: 'processing' });
        assert.equal((await read()).progress.stage, 'running');
        await f.db('tasks').where({ task_id: 't-1' }).update({ pr_number: 45 });
        await f.db('task_history').insert({ task_id: 't-1', state: 'completed' });
        await f.db('notification_pull_request_state').insert({ repository: 'owner/repo', pr_number: 45, merged_at: new Date().toISOString() });
        const done = await read();
        assert.equal(done.progress.stage, 'completed');
        assert.deepEqual(done.progress.pullRequest, { number: 45, url: 'https://github.com/owner/repo/pull/45', state: 'merged' });
      } finally { await f.db.destroy(); }
    });
  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: 2597/gpt-5.6-sol-mcp-task-submissions-expo-20260929-1402-mu9
    • Base Branch: 2593-epic-mcp-observability-cf6
    • Worktree: issue-2597-20260929-1402-gpt-5.6-sol-mu9

    🔍 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