Skip to content

Agents v1 (8/17): Capability enforcement — per-run tool policy for web access and MCP servers in agent containers #2807

Closed

Description

@propr-dev

Context

Agent definitions toggle three capabilities independently: repository code read (enforced by the workspace in issue 7 — no source is mounted when off), web browsing/fetch, and the ProPR MCP. Telling the model "do not browse" in the prompt is not enforcement. This issue adds an explicit, per-run toolPolicy to AgentTaskOptions and makes the Claude and Codex launchers enforce it with their native CLI switches. Issue 9 supplies the run-scoped ProPR MCP credential that this policy carries.

Scope decision for v1 (documented): enforcement is implemented for the runtimes that support it natively — Claude Code (--disallowedTools, --mcp-config) and Codex (-c tools.web_search=…, -c mcp_servers.*). For Antigravity/OpenCode/Vibe, web=false is applied through the prompt only and the UI shows "best effort" for those agents; propr_mcp is already rejected for them by issue 4.

Requirements

  1. Extend AgentTaskOptions in packages/core/src/agents/types.ts:
    toolPolicy?: { allowWeb: boolean; mcpServers?: Array<{ name: string; url: string; bearerTokenEnv: string; bearerToken: string }> }
    Absent toolPolicy = today's behavior (every existing caller is unaffected).
  2. New packages/core/src/agents/agentToolPolicy.ts with pure builders:
    • claudeToolPolicyArgs(policy) → { cliArgs: string[]; env: Record<string,string> }: when !allowWeb add --disallowedTools WebFetch WebSearch; for MCP servers add --mcp-config <inline JSON> whose headers.Authorization uses Bearer ${ENV_NAME} expansion, and put the actual token only in env (so it never appears in ps/logged args).
    • codexToolPolicyArgs(policy) → -c tools.web_search=false when web is off; for each MCP server -c mcp_servers.<name>.url="…" and -c mcp_servers.<name>.bearer_token_env_var="<ENV>"; token in env.
    • promptOnlyToolPolicyNotice(policy) for other runtimes.
  3. Wire the builders into ClaudeAgent.executeTask / buildDockerArgs and CodexAgent.executeTask / codexDockerArgsBuilder: CLI args appended to the agent command; env passed with -e NAME (value via extraEnvVars) — never -e NAME=value in args that get logged.
  4. Replace the stub src/jobs/agentRuns/toolPolicy.ts from issue 7 with the real mapping: report phase → allowWeb = capabilities.includes('web'), MCP only if propr_mcp enabled and a grant was issued (issue 9 passes it in); action phase → MCP always on, web follows the definition.
  5. Redaction: add the bearer env var names to the secret-redaction patterns so a token echoed by the agent is stripped from logs/LLM logs (redactSecrets already handles Bearer …; add a test proving it).
  6. Tests test/agentToolPolicy.test.ts.

Implementation Specification

  • Builders are pure and unit-tested; agent integration changes are a few lines each.
  • The MCP name is fixed to propr so prompts can say "the propr MCP server".
  • Never write the token to a file in the worktree (worktrees are inspectable by the agent and might be retained by push-salvage on other job types).

Acceptance Criteria

  • With toolPolicy: { allowWeb: false }, the Claude command line contains --disallowedTools WebFetch WebSearch; Codex contains -c tools.web_search=false.
  • With an MCP server, neither argument list contains the token value; the env map does.
  • Existing agent tests pass unchanged (no toolPolicy → identical args).
  • redactSecrets('Authorization: Bearer abc.def') removes the token.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Enforcement belongs in the launcher, not the prompt. We add one optional field (toolPolicy) to the agent task contract and two pure argument builders, then make a minimal change in the Claude and Codex launchers to append their output. Keeping the builders pure means the security-relevant part (which flags, where the token goes) is fully unit tested without Docker.

    Secrets handling: tokens travel only as container environment variables referenced by name (Bearer ${PROPR_MCP_TOKEN} expansion for Claude, bearer_token_env_var for Codex). Command-line arguments are logged by the Docker executor and visible in ps; environment values passed with -e NAME + process env are not.

    Alternative considered: a network firewall to block the web. The optional allowlist firewall exists but is inactive by default and is instance-wide; per-run tool switches are the precise, available control. Firewall integration is a possible later hardening.

    File: packages/core/src/agents/types.ts

    Why this file: The agent contract every runtime implements; the new field is optional so all existing callers are unchanged.

    --- a/packages/core/src/agents/types.ts
    +++ b/packages/core/src/agents/types.ts
    @@ export interface AgentTaskOptions {
    +    /**
    +     * Per-run tool restrictions for Agents. Absent means the runtime's default
    +     * tool set (every existing job). Enforced natively by Claude and Codex;
    +     * other runtimes receive it as a prompt notice only.
    +     */
    +    toolPolicy?: AgentToolPolicy;
     }
    +
    +export interface AgentToolPolicy {
    +    allowWeb: boolean;
    +    mcpServers?: Array<{ name: string; url: string; bearerTokenEnv: string; bearerToken: string }>;
    +}

    File: packages/core/src/agents/agentToolPolicy.ts (new file)

    Why this file: Pure translation from policy to CLI flags + env, per runtime. Unit-testable and reviewed in one place.

    import type { AgentToolPolicy } from './types.js';
    
    export interface ToolPolicyLaunch { cliArgs: string[]; env: Record<string, string> }
    
    function tokenEnv(policy: AgentToolPolicy): Record<string, string> {
      // Tokens are delivered only through the container environment, never argv.
      return Object.fromEntries((policy.mcpServers ?? []).map(server => [server.bearerTokenEnv, server.bearerToken]));
    }
    
    export function claudeToolPolicyArgs(policy: AgentToolPolicy | undefined): ToolPolicyLaunch {
      if (!policy) return { cliArgs: [], env: {} };
      const cliArgs: string[] = [];
      // Claude Code's built-in web tools; disallowing them is enforced by the CLI.
      if (!policy.allowWeb) cliArgs.push('--disallowedTools', 'WebFetch', 'WebSearch');
      if (policy.mcpServers?.length) {
        const config = { mcpServers: Object.fromEntries(policy.mcpServers.map(server => [server.name, {
          type: 'http', url: server.url,
          // ${VAR} is expanded by Claude Code from the container env at load time.
          headers: { Authorization: `Bearer \${${server.bearerTokenEnv}}` },
        }])) };
        cliArgs.push('--mcp-config', JSON.stringify(config));
      }
      return { cliArgs, env: tokenEnv(policy) };
    }
    
    export function codexToolPolicyArgs(policy: AgentToolPolicy | undefined): ToolPolicyLaunch {
      if (!policy) return { cliArgs: [], env: {} };
      const cliArgs: string[] = [];
      if (!policy.allowWeb) cliArgs.push('-c', 'tools.web_search=false');
      for (const server of policy.mcpServers ?? []) {
        cliArgs.push('-c', `mcp_servers.${server.name}.url=${JSON.stringify(server.url)}`);
        // Codex reads the bearer from the named variable; the value never reaches argv.
        cliArgs.push('-c', `mcp_servers.${server.name}.bearer_token_env_var=${JSON.stringify(server.bearerTokenEnv)}`);
      }
      return { cliArgs, env: tokenEnv(policy) };
    }
    
    /** Runtimes without native switches get an honest instruction instead. */
    export function promptOnlyToolPolicyNotice(policy: AgentToolPolicy | undefined): string {
      if (!policy || policy.allowWeb) return '';
      return 'Tool policy for this run: do NOT browse or fetch web content.';
    }

    File: packages/core/src/agents/impl/ClaudeAgent.ts (and claudeHelpers.buildDockerArgs)

    Why this file: Claude Code is one of the two runtimes that enforce the policy natively.

    --- a/packages/core/src/agents/impl/ClaudeAgent.ts
    +++ b/packages/core/src/agents/impl/ClaudeAgent.ts
    @@ async executeTask(options: AgentTaskOptions) {
    +        // Agents tool policy: flags appended to the claude command, secrets via env only.
    +        const toolPolicy = claudeToolPolicyArgs(options.toolPolicy);
             const dockerArgs = buildDockerArgs({
                 ...existingParams,
    +            extraCliArgs: toolPolicy.cliArgs,
             });
             const result = await executeDockerCommand('docker', dockerArgs, {
                 ...existingOptions,
    +            extraEnvVars: { ...existingOptions.extraEnvVars, ...toolPolicy.env },
             });

    In buildDockerArgs (packages/core/src/claude/claudeHelpers.ts) accept extraCliArgs?: string[] and append them after the existing claude flags; for each key of extraEnvVars the executor already emits -e KEY with the value from the process environment — verify that path does not inline KEY=value; if it does, change it to -e KEY plus env on spawn for these keys.

    File: packages/core/src/agents/impl/CodexAgent.ts (and codexDockerArgsBuilder)

    --- a/packages/core/src/agents/impl/CodexAgent.ts
    +++ b/packages/core/src/agents/impl/CodexAgent.ts
    @@ async executeTask(options: AgentTaskOptions) {
    +        const toolPolicy = codexToolPolicyArgs(options.toolPolicy);
             const dockerArgs = buildCodexDockerArgs({
                 ...existingParams,
    +            extraCliArgs: toolPolicy.cliArgs,
             });
    @@
    -            extraEnvVars: existingEnv,
    +            extraEnvVars: { ...existingEnv, ...toolPolicy.env },

    For Antigravity, OpenCode and Vibe: prepend promptOnlyToolPolicyNotice(options.toolPolicy) to the prompt (one line each in their executeTask).

    File: src/jobs/agentRuns/toolPolicy.ts

    Why this file: Maps definition capabilities + phase to a concrete policy (replaces the issue-7 stub).

    import type { AgentToolPolicy } from '@propr/core';
    import type { AgentCapability } from '@propr/shared';
    
    export interface IssuedMcpGrant { url: string; token: string }
    
    export const PROPR_MCP_SERVER_NAME = 'propr';
    export const PROPR_MCP_TOKEN_ENV = 'PROPR_AGENT_MCP_TOKEN';
    
    /**
     * Report phase: exactly what the definition enables.
     * Action phase: the ProPR MCP is the acting agent's only way to act, so it is
     * always on; web still follows the definition.
     */
    export function toolPolicyForCapabilities(capabilities: AgentCapability[], phase: 'report' | 'action', grant?: IssuedMcpGrant | null): AgentToolPolicy {
      const wantsMcp = phase === 'action' || capabilities.includes('propr_mcp');
      return {
        allowWeb: capabilities.includes('web'),
        mcpServers: wantsMcp && grant
          ? [{ name: PROPR_MCP_SERVER_NAME, url: grant.url, bearerTokenEnv: PROPR_MCP_TOKEN_ENV, bearerToken: grant.token }]
          : [],
      };
    }

    File: test/agentToolPolicy.test.ts (new file)

    Why this file: Proves enforcement flags and that tokens never reach argv.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import { closeConnection, redactSecrets } from '@propr/core';
    import { claudeToolPolicyArgs, codexToolPolicyArgs } from '../packages/core/src/agents/agentToolPolicy.js';
    
    after(closeConnection);
    const mcp = [{ name: 'propr', url: 'http://api:4000/api/mcp', bearerTokenEnv: 'PROPR_AGENT_MCP_TOKEN', bearerToken: 'propr_mcp_secretvalue123' }];
    
    test('web off is enforced by native switches', () => {
      assert.deepEqual(claudeToolPolicyArgs({ allowWeb: false }).cliArgs, ['--disallowedTools', 'WebFetch', 'WebSearch']);
      assert.deepEqual(codexToolPolicyArgs({ allowWeb: false }).cliArgs, ['-c', 'tools.web_search=false']);
      assert.deepEqual(claudeToolPolicyArgs(undefined), { cliArgs: [], env: {} });
    });
    
    test('MCP tokens travel only through env', () => {
      for (const launch of [claudeToolPolicyArgs({ allowWeb: true, mcpServers: mcp }), codexToolPolicyArgs({ allowWeb: true, mcpServers: mcp })]) {
        assert.ok(!launch.cliArgs.join(' ').includes('propr_mcp_secretvalue123'));
        assert.equal(launch.env.PROPR_AGENT_MCP_TOKEN, 'propr_mcp_secretvalue123');
      }
      assert.ok(!redactSecrets('Authorization: Bearer propr_mcp_secretvalue123').includes('secretvalue123'));
    });
  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: 2807/claude-opus-5-5-agents-v1-8-17-capability-20261006-1831-y1f
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2807-20261006-1831-claude-opus-5-5-y1f

    🔍 Track Task Execution

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