Skip to content

Agents v1 (9/17): Run-scoped, short-lived ProPR MCP grants for agent containers #2808

Closed

Description

@propr-dev

Context

Two places need the ProPR MCP from inside an agent container: the report step when the definition enables the propr_mcp capability (read-only context), and every acting step (issue 10), which acts on the report exclusively through existing MCP tools (create_task, create_todo, comment_on_pull_request, …). The MCP server authenticates OAuth bearer tokens bound to a user, a grant, scopes and repositories, and re-checks instance membership and GitHub repository access on every call (McpPolicy.authenticate). We reuse that entire authorization path by minting a delegated grant for the agent's owner that is:

  • scoped to the definition's repositories only,
  • scope-limited by phase: report → read; action → read, plan, execute (never merge, deploy, manage, review),
  • short-lived (expires after 2 hours) and revoked as soon as the phase ends,
  • labelled so it is visible on the Connected apps page (/mcp/apps) as "ProPR Agent: " and its calls appear in the MCP access log.

The worker cannot import the API package, so issuance is an internal API endpoint authenticated with an HMAC over the run id signed with the existing SYSTEM_TASK_SECRET (same trust root as signed system tasks/reverts).

Requirements

  1. packages/api/mcp/agentRunGrants.ts:
    • AGENT_RUN_MCP_CLIENT_ID = 'propr-agent-runs' registered as an internal public client (no redirect URIs; cannot be used for interactive OAuth).
    • issueAgentRunGrant({ ownerId, definitionName, runId, phase, repositories }) → { grantId, accessToken, expiresAt } built on the existing McpOAuthProvider/McpStore grant + access-token persistence (the same code path used after browser consent), with membershipSource: 'agent_run' and resource = config.resource.
    • revokeAgentRunGrant(grantId) using the existing grant revocation (the same as the Connected apps "Revoke" button).
    • Fails with MCP_DISABLED when MCP is not enabled, and GITHUB_AUTHORIZATION_REQUIRED when the owner has no stored GitHub user grant (githubUserGrantService.resolve) — the MCP principal needs one.
  2. Internal routes (registered in server.ts before the session auth guard, like the desktop pairing exceptions, but protected by HMAC):
    • POST /api/internal/agent-runs/:runId/mcp-grants body { phase, ts, signature } → { grantId, url, token, expiresAt }. Verifies signature (HMAC-SHA256(SYSTEM_TASK_SECRET, runId + ':' + phase + ':' + ts)), |now - ts| < 5 min, and that the run exists and is in running (report) or acting (action). Repositories and owner are read from the run snapshot — never from the request body.
    • POST /api/internal/agent-runs/:runId/mcp-grants/revoke with the same signed body (POST so the HMAC body is carried uniformly).
    • Rate-limited with the existing pairing/discovery limiter.
  3. Worker client src/jobs/agentRuns/mcpGrantClient.ts: requestAgentRunMcpGrant(runId, phase) / revokeAgentRunMcpGrant(runId, grantId) calling PROPR_INTERNAL_API_URL (default http://api:4000). The URL handed to the container is PROPR_AGENT_MCP_URL (default ${PROPR_INTERNAL_API_URL}/api/mcp) because containers reach the API over the Docker network, not the public origin.
  4. Executor integration (issue 7 + 10): request a grant when the policy needs MCP, pass it to toolPolicyForCapabilities, and revoke in finally.
  5. Tests: packages/api/test/agentRunGrants.test.ts (signature, replay window, wrong state, scope/repository restriction of the resulting principal via McpPolicy.authenticate).

Implementation Specification

  • The token is never stored in agent_runs, never logged, and only passed as a container env var (issue 8).
  • Expiry is a backstop; revocation on phase end is the primary control. A daemon sweep (issue 12) also revokes grants of runs that reached a terminal state (crash recovery).
  • Record grant_id per phase in a new nullable column? Not required: store grant ids in mcp_records metadata keyed by run id so the sweep can find them (kind: 'agent_run_grant', id: <runId>:<phase>).

Acceptance Criteria

  • A forged or expired signature returns 401; a valid signature for a completed run returns 409.
  • The issued token authenticates on /api/mcp, lists only the definition's repositories, and create_task on a repository outside the scope is denied.
  • A report-phase token cannot call create_task (requires execute).
  • After revoke, the token is rejected.
  • The grant appears on /mcp/apps labelled with the agent name, and calls appear in the MCP access log.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We reuse ProPR's MCP authorization end to end instead of inventing a second permission system for agents: the acting agent is "the owner, through a narrowly scoped, short-lived connected app". Every MCP call therefore gets the same scope checks, per-call repository re-authorization, instance membership checks, idempotent receipts and access logging as a human's chat client.

    Why an internal HMAC endpoint: grant issuance needs the API's MCP store, encryption key and OAuth provider; the worker runs in a different process/image and must not hold the MCP encryption key. SYSTEM_TASK_SECRET is already the shared trust root between API and worker for signed system tasks, so we reuse it rather than introducing a new secret.

    Alternatives rejected: (a) giving the acting container the owner's GitHub token and letting it call GitHub directly — bypasses ProPR's tools and receipts; (b) a long-lived per-definition token — larger blast radius, harder to revoke.

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

    Why this file: Mints and revokes delegated grants on top of the existing OAuth grant store, so the MCP policy layer treats agent runs exactly like any other connected app.

    import { createHmac, timingSafeEqual } from 'node:crypto';
    import type { Knex } from 'knex';
    import { McpError, type McpScope } from './config.js';
    import type { McpOAuthProvider } from './oauth.js';
    import { githubUserGrantService } from '../githubUserGrantService.js';
    
    export const AGENT_RUN_MCP_CLIENT_ID = 'propr-agent-runs';
    export const AGENT_RUN_GRANT_TTL_MS = 2 * 60 * 60 * 1000;
    const SIGNATURE_WINDOW_MS = 5 * 60 * 1000;
    
    // Least privilege per phase: reading context vs. creating tasks/TODOs/comments.
    // merge, deploy, review and manage are never delegated to an agent in v1.
    export const AGENT_RUN_PHASE_SCOPES: Record<'report' | 'action', McpScope[]> = {
      report: ['read'],
      action: ['read', 'plan', 'execute'],
    };
    
    export function signAgentRunRequest(secret: string, runId: string, phase: string, ts: number): string {
      return createHmac('sha256', secret).update(`${runId}:${phase}:${ts}`).digest('hex');
    }
    
    export function verifyAgentRunRequest(secret: string | undefined, input: { runId: string; phase: string; ts: number; signature: string }, now = Date.now()): boolean {
      if (!secret || !Number.isFinite(input.ts) || Math.abs(now - input.ts) > SIGNATURE_WINDOW_MS) return false;
      const expected = Buffer.from(signAgentRunRequest(secret, input.runId, input.phase, input.ts), 'hex');
      const actual = Buffer.from(input.signature, 'hex');
      return expected.length === actual.length && timingSafeEqual(expected, actual);
    }
    
    /**
     * Adapter over the existing OAuth provider. Implement `issueDelegatedGrant` with
     * the same persistence used after browser consent (grant row + access token),
     * passing client_id AGENT_RUN_MCP_CLIENT_ID and membershipSource 'agent_run'.
     */
    export interface AgentRunGrantIssuer {
      issueDelegatedGrant(input: { userId: string; clientId: string; clientName: string; scopes: McpScope[]; repositories: string[]; expiresAt: number; metadata: Record<string, string> }): Promise<{ grantId: string; accessToken: string }>;
      revokeGrant(grantId: string): Promise<void>;
    }
    
    export function oauthGrantIssuer(provider: McpOAuthProvider): AgentRunGrantIssuer {
      return {
        issueDelegatedGrant: input => (provider as unknown as { issueDelegatedGrant: AgentRunGrantIssuer['issueDelegatedGrant'] }).issueDelegatedGrant(input),
        revokeGrant: grantId => (provider as unknown as { revokeGrant: (id: string) => Promise<void> }).revokeGrant(grantId),
      };
    }
    
    export async function issueAgentRunGrant(deps: { db: Knex; issuer: AgentRunGrantIssuer; mcpEnabled: boolean }, input: {
      ownerId: string; definitionName: string; runId: string; phase: 'report' | 'action'; repositories: string[];
    }): Promise<{ grantId: string; accessToken: string; expiresAt: number }> {
      if (!deps.mcpEnabled) throw new McpError('MCP_DISABLED', 'Enable the MCP server (Settings → Integrations) to use the ProPR MCP in agents.', 409);
      // The MCP principal acts with the owner's own GitHub authority; without a stored
      // grant every tool call would fail, so fail early with an actionable message.
      const github = await githubUserGrantService.resolve(input.ownerId, false);
      if (github.status !== 'active') throw new McpError('GITHUB_AUTHORIZATION_REQUIRED', 'Sign in to ProPR in a browser so agent runs can act with your GitHub access.', 409);
      const expiresAt = Date.now() + AGENT_RUN_GRANT_TTL_MS;
      const { grantId, accessToken } = await deps.issuer.issueDelegatedGrant({
        userId: input.ownerId, clientId: AGENT_RUN_MCP_CLIENT_ID,
        clientName: `ProPR Agent: ${input.definitionName}`, scopes: AGENT_RUN_PHASE_SCOPES[input.phase],
        repositories: input.repositories, expiresAt, metadata: { runId: input.runId, phase: input.phase },
      });
      // Remembered so the daemon sweep can revoke grants of crashed runs.
      await deps.db('mcp_records').insert({ kind: 'agent_run_grant', id: `${input.runId}:${input.phase}`, value: grantId, owner_id: input.ownerId, expires_at: expiresAt })
        .onConflict(['kind', 'id']).merge();
      return { grantId, accessToken, expiresAt };
    }
    
    export async function revokeAgentRunGrant(deps: { db: Knex; issuer: AgentRunGrantIssuer }, runId: string, phase: 'report' | 'action'): Promise<void> {
      const record = await deps.db('mcp_records').where({ kind: 'agent_run_grant', id: `${runId}:${phase}` }).first();
      if (!record) return;
      await deps.issuer.revokeGrant(record.value);
      await deps.db('mcp_records').where({ kind: 'agent_run_grant', id: record.id }).delete();
    }

    Add issueDelegatedGrant and revokeGrant methods to McpOAuthProvider (packages/api/mcp/oauth.ts) by extracting the existing "persist grant + mint access token" and "revoke grant" code into these reusable methods (no behavior change for browser consent). The delegated grant has no refresh token.

    File: packages/api/routes/agentRunInternalRoutes.ts (new file)

    Why this file: The only bridge from the worker to grant issuance, authenticated by HMAC and validated against the run's own snapshot.

    import type { Request, Response } from 'express';
    import type { Knex } from 'knex';
    import { getAgentRunRowById, runDefinitionSnapshot } from '@propr/core';
    import { issueAgentRunGrant, revokeAgentRunGrant, verifyAgentRunRequest, type AgentRunGrantIssuer } from '../mcp/agentRunGrants.js';
    
    const PHASE_STATE = { report: 'running', action: 'acting' } as const;
    
    export function createAgentRunInternalRoutes(deps: { db: Knex; issuer: () => AgentRunGrantIssuer | null; mcpUrl: string; secret?: string }) {
      const secret = deps.secret ?? process.env.SYSTEM_TASK_SECRET;
    
      function authorized(req: Request): { runId: string; phase: 'report' | 'action' } | null {
        const phase = req.body?.phase;
        if (phase !== 'report' && phase !== 'action') return null;
        const runId = String(req.params.runId);
        return verifyAgentRunRequest(secret, { runId, phase, ts: Number(req.body?.ts), signature: String(req.body?.signature ?? '') }) ? { runId, phase } : null;
      }
    
      return {
        issue: async (req: Request, res: Response) => {
          const auth = authorized(req);
          if (!auth) { res.status(401).json({ error: 'Invalid signature' }); return; }
          const row = await getAgentRunRowById(auth.runId, deps.db);
          // Only a live phase may hold a grant; a finished run never gets new access.
          if (!row || row.state !== PHASE_STATE[auth.phase]) { res.status(409).json({ error: 'Run is not in a phase that may use the ProPR MCP' }); return; }
          const issuer = deps.issuer();
          try {
            const definition = runDefinitionSnapshot(row);
            // Owner and repositories come from the frozen snapshot, never from the request.
            const grant = await issueAgentRunGrant({ db: deps.db, issuer: issuer!, mcpEnabled: Boolean(issuer) }, {
              ownerId: row.owner_id, definitionName: definition.name, runId: row.id, phase: auth.phase, repositories: definition.repositories,
            });
            res.status(201).json({ grantId: grant.grantId, url: deps.mcpUrl, token: grant.accessToken, expiresAt: grant.expiresAt });
          } catch (error) {
            const { status = 500, code } = error as { status?: number; code?: string };
            res.status(status).json({ error: (error as Error).message, code });
          }
        },
        revoke: async (req: Request, res: Response) => {
          const auth = authorized(req);
          const issuer = deps.issuer();
          if (!auth || !issuer) { res.status(401).json({ error: 'Invalid signature' }); return; }
          await revokeAgentRunGrant({ db: deps.db, issuer }, auth.runId, auth.phase);
          res.status(204).send();
        },
      };
    }

    File: packages/api/server.ts

    Why this file: Registers the internal routes ahead of the session guard (they use HMAC, not sessions), next to the other documented pre-auth exceptions.

    --- a/packages/api/server.ts
    +++ b/packages/api/server.ts
    @@ function setupRoutes(): void {
       mountMcp(app, { db, taskQueue, redisClient, runtimeBuildQueue });
    +  // INTERNAL: worker-to-API grant issuance for agent runs. HMAC-signed with
    +  // SYSTEM_TASK_SECRET, rate-limited, and validated against the run snapshot.
    +  const agentRunInternal = createAgentRunInternalRoutes({
    +    db, issuer: () => getMcpGrantIssuer(), // returns null while MCP is disabled
    +    mcpUrl: process.env.PROPR_AGENT_MCP_URL || `${process.env.PROPR_INTERNAL_API_URL || 'http://api:4000'}/api/mcp`,
    +  });
    +  app.post('/api/internal/agent-runs/:runId/mcp-grants', createDiscoveryRequestRateLimiter(), agentRunInternal.issue);
    +  app.post('/api/internal/agent-runs/:runId/mcp-grants/revoke', createDiscoveryRequestRateLimiter(), agentRunInternal.revoke);

    (getMcpGrantIssuer() is a small export from mcp/server.ts returning oauthGrantIssuer(provider) once mountMcp has initialized the provider, or null.) Note the revoke route uses POST .../revoke instead of DELETE so the HMAC body is carried uniformly.

    File: src/jobs/agentRuns/mcpGrantClient.ts (new file)

    Why this file: Worker side of the bridge; used by both executors.

    import { createHmac } from 'node:crypto';
    import type { IssuedMcpGrant } from './toolPolicy.js';
    
    const apiBase = () => process.env.PROPR_INTERNAL_API_URL || 'http://api:4000';
    
    function signedBody(runId: string, phase: 'report' | 'action') {
      const secret = process.env.SYSTEM_TASK_SECRET;
      if (!secret) throw new Error('SYSTEM_TASK_SECRET is required for agents that use the ProPR MCP');
      const ts = Date.now();
      return { phase, ts, signature: createHmac('sha256', secret).update(`${runId}:${phase}:${ts}`).digest('hex') };
    }
    
    export async function requestAgentRunMcpGrant(runId: string, phase: 'report' | 'action'): Promise<IssuedMcpGrant> {
      const response = await fetch(`${apiBase()}/api/internal/agent-runs/${encodeURIComponent(runId)}/mcp-grants`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(signedBody(runId, phase)),
        signal: AbortSignal.timeout(15_000),
      });
      const body = await response.json().catch(() => ({})) as { url?: string; token?: string; error?: string };
      // The message is user-facing (stored as the run's failure reason), never the token.
      if (!response.ok || !body.url || !body.token) throw new Error(`Could not obtain ProPR MCP access: ${body.error ?? `HTTP ${response.status}`}`);
      return { url: body.url, token: body.token };
    }
    
    export async function revokeAgentRunMcpGrant(runId: string, phase: 'report' | 'action'): Promise<void> {
      // Best effort: the grant also expires and the daemon sweep revokes leftovers.
      await fetch(`${apiBase()}/api/internal/agent-runs/${encodeURIComponent(runId)}/mcp-grants/revoke`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(signedBody(runId, phase)),
        signal: AbortSignal.timeout(15_000),
      }).catch(() => undefined);
    }

    File: src/jobs/processAgentRunJob.ts

    Why this file: The report phase obtains MCP access only when the definition enables it.

    --- a/src/jobs/processAgentRunJob.ts
    +++ b/src/jobs/processAgentRunJob.ts
    @@
    +      const grant = definition.capabilities.includes('propr_mcp') ? await requestAgentRunMcpGrant(runId, 'report') : null;
    @@
    -        toolPolicy: toolPolicyForCapabilities(definition.capabilities, 'report'),
    +        toolPolicy: toolPolicyForCapabilities(definition.capabilities, 'report', grant),
    @@
         } finally {
    +      if (definition.capabilities.includes('propr_mcp')) await revokeAgentRunMcpGrant(runId, 'report');
           await workspace?.cleanup();

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

    Why this file: Covers the security properties: signature, freshness, state gating, least-privilege scopes.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { AGENT_RUN_PHASE_SCOPES, signAgentRunRequest, verifyAgentRunRequest } from '../mcp/agentRunGrants.js';
    
    test('signatures are bound to run, phase and a short time window', () => {
      const ts = Date.now();
      const signature = signAgentRunRequest('s3cret', 'run-1', 'action', ts);
      assert.equal(verifyAgentRunRequest('s3cret', { runId: 'run-1', phase: 'action', ts, signature }), true);
      assert.equal(verifyAgentRunRequest('s3cret', { runId: 'run-2', phase: 'action', ts, signature }), false);
      assert.equal(verifyAgentRunRequest('s3cret', { runId: 'run-1', phase: 'report', ts, signature }), false);
      assert.equal(verifyAgentRunRequest('s3cret', { runId: 'run-1', phase: 'action', ts, signature }, ts + 6 * 60_000), false);
      assert.equal(verifyAgentRunRequest(undefined, { runId: 'run-1', phase: 'action', ts, signature }), false);
    });
    
    test('phases delegate least privilege', () => {
      assert.deepEqual(AGENT_RUN_PHASE_SCOPES.report, ['read']);
      for (const forbidden of ['merge', 'deploy', 'manage', 'review']) assert.ok(!AGENT_RUN_PHASE_SCOPES.action.includes(forbidden as never));
    });

    Add an integration test in the same file using the in-memory MCP fixture from mcpTaskSubmissions.test.ts: issue an action grant for acme/web, call create_task on acme/other → REPOSITORY_FORBIDDEN; issue a report grant → create_task fails with requires execute.

  2. propr-dev commented on Oct 6, 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: 2808/claude-opus-5-5-agents-v1-9-17-run-scoped-20261006-2058-twh
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2808-20261006-2058-claude-opus-5-5-twh

    🔍 Track Task Execution

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