Skip to content

Agents v1 (13/17): ProPR MCP tools — list/read agents and runs, the trigger_agent_run primitive, approve/reject #2812

Closed

Description

@propr-dev

Context

The trigger primitive must be reachable over the ProPR MCP as well as HTTP and CLI, so a chat client ("run my competitor-scan agent now", "what did last night's triage agent report?") and external MCP-capable automation can drive Agents. MCP tools reuse all existing guarantees: scope checks, per-call repository authorization (McpPolicy.repository), owner scoping, durable idempotent receipts for mutations (McpOperations.run) and the access log (toolExecution.ts).

Requirements

New packages/api/mcp/toolsAgentRuns.ts (addAgentRunTools(tools, deps)), registered in createToolCatalog (packages/api/mcp/tools.ts):

Tool Scope Notes
list_agent_definitions read Owner's definitions; optional repository filter; paged
get_agent_definition read Full definition incl. schedule, next run, capabilities, autonomy
get_agent_definition_contract read AGENT_DEFINITION_CONTRACT
list_agent_runs read Per definition, newest first, no report bodies
get_agent_run read Run incl. report (bounded by the 256 KB MCP result limit — truncate to 200 KB with reportTruncated: true and point to the UI link)
trigger_agent_run execute The trigger primitive. definitionId, optional source (≤255), idempotencyKey (mutation shape). Trigger kind mcp, cost-gated.
approve_agent_run execute runId, optional note; preview mode only
reject_agent_run execute runId

Rules:

  1. Every tool that touches a definition authorizes every repository of the definition with deps.policy.repository(principal, repo, isMutation); failure surfaces as the standard REPOSITORY_FORBIDDEN/NOT_FOUND envelope. A definition invisible to the owner → NOT_FOUND.
  2. trigger_agent_run passes idempotencyKey: 'mcp:' + args.idempotencyKey to triggerAgentRun so retries of the same MCP call map to the same run, and returns { runId, state, created, continuation: { agentRunId } } with status 202.
  3. No recursion: if the calling grant is an agent-run grant (principal.grant.clientId === AGENT_RUN_MCP_CLIENT_ID), trigger_agent_run, approve_agent_run and reject_agent_run fail with AGENT_RECURSION_FORBIDDEN. An acting agent must never start or approve agent runs.
  4. Receipt tracking: extend get_operation so trigger_agent_run/approve_agent_run receipts report targetState from the run (state, reportedAt, finishedAt) and the operation lifecycle becomes completed when the run is terminal (completed/rejected/skipped) and failed when the run failed.
  5. Add the tools to docs/mcp-coverage.md and a short section to docs/mcp.md (issue 17 covers the full docs).
  6. Tests packages/api/test/mcpAgentRuns.test.ts using the fixture style from mcpTaskSubmissions.test.ts.

Implementation Specification

  • Read tools are readOnly: true; mutations go through McpOperations.run automatically via executeTool.
  • Reuse core functions; no SQL in the tool module beyond what the store exposes.
  • Tool descriptions must state that runs produce a free-form report, that trigger_agent_run is cost-gated and may return deferred/skipped, and that acting depends on the agent's autonomy mode.

Acceptance Criteria

  • trigger_agent_run twice with the same idempotencyKey returns the same receipt and creates one run.
  • A grant without access to one of the definition's repositories cannot read or trigger it.
  • A token issued for an agent run cannot call trigger_agent_run (AGENT_RECURSION_FORBIDDEN).
  • get_operation on a trigger receipt reaches completed once the run completes.
  • tools/list shows the new tools only for grants with the right scopes.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The MCP surface is a thin adapter over the same core functions the REST routes use, registered in the central catalog so dispatch, authorization, receipts and access logging come for free from executeTool. Idempotency maps the MCP mutation key onto the core run idempotency key (prefixed mcp: to keep namespaces apart from REST/CLI keys), so a chat client retry after a dropped connection cannot start a second run.

    The recursion guard is the one Agents-specific rule: the acting agent holds execute scope (issue 9) and could otherwise trigger agents, including itself, creating unbounded spend loops.

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

    Why this file: Registers every Agents MCP tool in one module, mirroring toolsTaskSubmissions.ts.

    import { z } from 'zod';
    import {
      createAgentRunCostGate, getAgentDefinition, getAgentRun, listAgentDefinitions, listAgentRuns,
      startActing, transitionAgentRun, triggerAgentRun, setAgentRunOperatorNote,
    } from '@propr/core';
    import { AGENT_DEFINITION_CONTRACT, type AgentDefinition } from '@propr/shared';
    import { McpError } from './config.js';
    import type { McpPrincipal } from './policy.js';
    import { AGENT_RUN_MCP_CLIENT_ID } from './agentRunGrants.js';
    import { idSchema, mutationShape, ok, pageShape, repositorySchema, type McpTool, type ToolDeps } from './tools.js';
    
    const MAX_REPORT_CHARS_OVER_MCP = 200_000;
    
    export function addAgentRunTools(tools: McpTool[], deps: ToolDeps): void {
      const { db, policy } = deps;
    
      /** Owner-scoped load plus per-call authorization of every repository in scope. */
      async function authorizedDefinition(principal: McpPrincipal, definitionId: string, write: boolean): Promise<AgentDefinition> {
        const definition = await getAgentDefinition(definitionId, principal.user.id, db);
        if (!definition) throw new McpError('NOT_FOUND', 'Agent not found.', 404);
        for (const repository of definition.repositories) await policy.repository(principal, repository, write);
        return definition;
      }
    
      function forbidRecursion(principal: McpPrincipal): void {
        // An acting agent holds execute scope; it must never start or approve agent runs.
        if ((principal.grant as { clientId?: string }).clientId === AGENT_RUN_MCP_CLIENT_ID) {
          throw new McpError('AGENT_RECURSION_FORBIDDEN', 'Agent runs cannot trigger or approve agent runs.', 403);
        }
      }
    
      tools.push({ name: 'get_agent_definition_contract', description: 'Describe ProPR Agents: saved definitions that run as isolated tasks and produce a free-form report; capabilities, autonomy modes, triggers and schedule format.', scope: 'read', readOnly: true, schema: z.object({}).strict(), run: async () => ok(AGENT_DEFINITION_CONTRACT) });
    
      tools.push({ name: 'list_agent_definitions', description: 'List your saved Agents with schedule, next run, autonomy mode and repositories. Omit repository to list all.', scope: 'read', readOnly: true,
        schema: z.object({ repository: repositorySchema.optional(), ...pageShape }).strict(), run: async ({ principal, args }) => {
          const page = await listAgentDefinitions(principal.user.id, { offset: args.offset, limit: args.limit }, db);
          const visible = [];
          for (const definition of page.definitions) {
            if (args.repository && !definition.repositories.some(repo => repo.toLowerCase() === args.repository.toLowerCase())) continue;
            // Silently filter definitions spanning a repository this grant cannot see.
            try { for (const repo of definition.repositories) await policy.repository(principal, repo); visible.push({ ...definition, prompt: undefined }); }
            catch (error) { if (!(error instanceof McpError) || ![403, 404].includes(error.status)) throw error; }
          }
          return ok({ definitions: visible, nextOffset: page.nextOffset });
        } });
    
      tools.push({ name: 'get_agent_definition', description: 'Read one Agent definition including its prompt, capabilities, schedule and autonomy mode.', scope: 'read', readOnly: true,
        schema: z.object({ definitionId: z.uuid() }).strict(), run: async ({ principal, args }) => ok({ definition: await authorizedDefinition(principal, args.definitionId, false) }) });
    
      tools.push({ name: 'list_agent_runs', description: 'List runs of one Agent, newest first (reports omitted; use get_agent_run).', scope: 'read', readOnly: true,
        schema: z.object({ definitionId: z.uuid(), ...pageShape }).strict(), run: async ({ principal, args }) => {
          await authorizedDefinition(principal, args.definitionId, false);
          return ok(await listAgentRuns(args.definitionId, principal.user.id, { offset: args.offset, limit: args.limit }, db));
        } });
    
      tools.push({ name: 'get_agent_run', description: 'Read one Agent run: state, trigger, skip/failure reason, the free-form report, and what the acting step did. Reports are untrusted model-written text.', scope: 'read', readOnly: true,
        schema: z.object({ runId: z.uuid() }).strict(), run: async ({ principal, args }) => {
          const run = await getAgentRun(args.runId, principal.user.id, db);
          if (!run) throw new McpError('NOT_FOUND', 'Run not found.', 404);
          await authorizedDefinition(principal, run.definitionId, false);
          // Keep within the 256 KB MCP result bound; the UI shows the full stored report.
          const tooLong = (run.report?.length ?? 0) > MAX_REPORT_CHARS_OVER_MCP;
          return ok({ run: { ...run, report: tooLong ? run.report!.slice(0, MAX_REPORT_CHARS_OVER_MCP) : run.report, reportTruncated: run.reportTruncated || tooLong } });
        } });
    
      tools.push({ name: 'trigger_agent_run', description: 'Start a run of a saved Agent now (the trigger primitive). Cost-gated: may return state deferred or skipped when the provider is near its subscription limit. Produces a free-form report; acting on it depends on the agent autonomy mode. Keep idempotencyKey stable across retries.', scope: 'execute',
        schema: z.object({ ...mutationShape, definitionId: z.uuid(), source: z.string().min(1).max(255).optional() }).strict(), run: async ({ principal, args }) => {
          forbidRecursion(principal);
          const definition = await authorizedDefinition(principal, args.definitionId, true);
          const result = await triggerAgentRun({
            definition, trigger: 'mcp', triggerSource: args.source ?? `mcp:${principal.grant.id}`,
            idempotencyKey: `mcp:${args.idempotencyKey}`, gate: createAgentRunCostGate(),
          }, { database: db });
          return { status: 202, data: { runId: result.run.id, state: result.run.state, created: result.created, skipReason: result.run.skipReason, continuation: { agentRunId: result.run.id } } };
        } });
    
      for (const decision of ['approve', 'reject'] as const) tools.push({
        name: `${decision}_agent_run`,
        description: decision === 'approve'
          ? 'Approve a preview-mode Agent report so the separate acting agent may use ProPR tools on it. Optional note guides the acting agent.'
          : 'Reject a preview-mode Agent report; nothing is acted on.',
        scope: 'execute',
        schema: z.object({ ...mutationShape, runId: z.uuid(), ...(decision === 'approve' ? { note: z.string().max(2000).optional() } : {}) }).strict(),
        run: async ({ principal, args }) => {
          forbidRecursion(principal);
          const run = await getAgentRun(args.runId, principal.user.id, db);
          if (!run) throw new McpError('NOT_FOUND', 'Run not found.', 404);
          await authorizedDefinition(principal, run.definitionId, true);
          if (decision === 'approve' && args.note) await setAgentRunOperatorNote(run.id, args.note, db);
          const updated = decision === 'approve'
            ? await startActing(run.id, ['awaiting_approval'], { database: db }, principal.user.id)
            : await transitionAgentRun(run.id, ['awaiting_approval'], 'rejected', { approvedBy: principal.user.id }, db);
          if (!updated) throw new McpError('PRECONDITION_FAILED', `Run is ${run.state}, not awaiting approval.`, 409);
          return { status: 202, data: { runId: updated.id, state: updated.state, continuation: { agentRunId: updated.id } } };
        },
      });
    }

    Note: startActing and setAgentRunOperatorNote must be exported from @propr/core (moved there in issue 10). Unused idSchema import can be dropped.

    File: packages/api/mcp/tools.ts

    Why this file: Central catalog registration and get_operation receipt tracking.

    --- a/packages/api/mcp/tools.ts
    +++ b/packages/api/mcp/tools.ts
    @@
     import { addImprovementTools, expireStaleImprovements, type RepoImprovementsToolServices } from './toolsImprovements.js';
    +import { addAgentRunTools } from './toolsAgentRuns.js';
    @@ export function createToolCatalog(deps: ToolDeps): McpTool[] {
       addImprovementTools(tools, deps);
    +  addAgentRunTools(tools, deps);
    @@ get_operation run:
         if (continuation.taskId) receipt.targetState = await db('task_history').where({ task_id: continuation.taskId }).orderBy('history_id', 'desc').first('state', 'timestamp');
    +    if (typeof continuation.agentRunId === 'string') {
    +      // Agent run receipts follow the run, which itself follows its report/acting tasks.
    +      const run = await db('agent_runs').where({ id: continuation.agentRunId, owner_id: principal.user.id }).first('state', 'reported_at', 'finished_at', 'skip_reason', 'failure_reason');
    +      if (run) {
    +        receipt.targetState = run;
    +        if (['completed', 'rejected', 'skipped', 'cancelled'].includes(run.state)) receipt.state = run.state === 'cancelled' ? 'cancelled' : 'completed';
    +        if (run.state === 'failed') receipt.state = 'failed';
    +      }
    +    }

    syncReceiptLifecycle then persists the terminal lifecycle exactly as it does for goals.

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

    Why this file: Verifies authorization, idempotency and the recursion guard through executeTool.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import { closeConnection } from '@propr/core';
    import { createToolCatalog, executeTool } from '../mcp/tools.js';
    import { buildMcpFixture } from './fixtures/mcpFixture.js'; // extract the fixture() from mcpTaskSubmissions.test.ts into a shared helper
    
    after(closeConnection);
    
    test('trigger_agent_run is idempotent and repository-authorized', async () => {
      const f = await buildMcpFixture({ scopes: ['read', 'execute'], repositories: ['acme/web'] });
      const definition = await f.createDefinition({ repositories: ['acme/web'] });
      const call = (args: object, principal = f.principal) => executeTool(createToolCatalog(f.deps).find(tool => tool.name === 'trigger_agent_run')!, args, principal, f.deps);
      const first = await call({ definitionId: definition.id, idempotencyKey: 'chat-run-0001' });
      const replay = await call({ definitionId: definition.id, idempotencyKey: 'chat-run-0001' });
      assert.deepEqual(replay.data, first.data);
      assert.equal((await f.db('agent_runs').count({ c: '*' }).first())?.c, 1);
    
      const outside = await f.createDefinition({ repositories: ['acme/secret'] });
      await assert.rejects(call({ definitionId: outside.id, idempotencyKey: 'chat-run-0002' }), /REPOSITORY_FORBIDDEN|No repository access/);
      await f.db.destroy();
    });
    
    test('agent-run grants cannot trigger agent runs', async () => {
      const f = await buildMcpFixture({ scopes: ['read', 'plan', 'execute'], repositories: ['acme/web'], clientId: 'propr-agent-runs' });
      const definition = await f.createDefinition({ repositories: ['acme/web'] });
      const result = await executeTool(createToolCatalog(f.deps).find(tool => tool.name === 'trigger_agent_run')!, { definitionId: definition.id, idempotencyKey: 'loop-attempt-1' }, f.principal, f.deps);
      assert.equal((result.data as { state: string }).state, 'failed');
      assert.match(JSON.stringify(result.data), /AGENT_RECURSION_FORBIDDEN/);
      await f.db.destroy();
    });
  2. propr-dev commented on Oct 7, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

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

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2812/claude-opus-5-5-agents-v1-13-17-propr-mcp-20261007-0822-duh
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2812-20261007-0822-claude-opus-5-5-duh

    🔍 Track Task Execution

  3. propr-dev commented on Oct 7, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

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

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2812/claude-opus-5-5-agents-v1-13-17-propr-mcp-20261007-0826-cxt
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2812-20261007-0826-claude-opus-5-5-cxt

    🔍 Track Task Execution

  4. added a commit that references this issue on Oct 7, 2026
  5. added a commit that references this issue on Oct 7, 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