Custom Operation Across CLI, MCP, and Change Proposals

In PhrameCMS, every surface reads from OperationRegistry. When you register a single OperationInterface tagged OperationRegistry::OPERATION_TAG (phrame.operation) with mutatesState: true, supportsDryRun: true, and canonical beforeHash / afterHash / diff values, it automatically works across:

  • In-process PHP (OperationBus::execute())
  • CLI (./bin/phrame op:list, op:describe, op:run --dry-run --json)
  • MCP (tools/list, tools/call with auto-injected dry_run and idempotency_key)
  • AI Change Proposals (proposal.create with propose.<perm> → human proposal.approve with beforeHash conflict protection)

Step 1: Define a Portable Storage Table (Optional)

If your operation persists its own state, declare an idempotent SchemaInstallerInterface and a thin repository. Here we manage URL redirect rules (acme_redirects):

php
<?php

declare(strict_types=1);

namespace Acme\Redirects\Storage;

use PhrameCms\Database\Contract\ConnectionInterface;
use PhrameCms\Database\Contract\SchemaInstallerInterface;
use PhrameCms\Database\Schema\ColumnType;
use PhrameCms\Database\Schema\TableBlueprint;

final readonly class RedirectSchemaInstaller implements SchemaInstallerInterface
{
    public const string TABLE = 'acme_redirects';

    public function __construct(
        private ConnectionInterface $connection,
    ) {}

    public function name(): string
    {
        return 'acme.redirects';
    }

    /** @return list<string> */
    public function tables(): array
    {
        return [self::TABLE];
    }

    public function isInstalled(): bool
    {
        return $this->connection->schema()->hasTable(self::TABLE);
    }

    public function install(): void
    {
        if ($this->isInstalled()) {
            return;
        }

        $this->connection->schema()->createTable(self::TABLE, static function (TableBlueprint $t): void {
            $t->column('source_path', ColumnType::String, length: 255);
            $t->column('target_path', ColumnType::String, length: 255);
            $t->column('status_code', ColumnType::Integer);
            $t->primaryKey('source_path');
        });
    }
}

And a minimal repository (src/Storage/RedirectRepository.php):

php
<?php

declare(strict_types=1);

namespace Acme\Redirects\Storage;

use PhrameCms\Database\Contract\ConnectionInterface;

final readonly class RedirectRepository
{
    public function __construct(
        private ConnectionInterface $connection,
    ) {}

    /** @return ?array{source_path: string, target_path: string, status_code: int} */
    public function findBySource(string $sourcePath): ?array
    {
        $row = $this->connection->query()
            ->table(RedirectSchemaInstaller::TABLE)
            ->select('source_path', 'target_path', 'status_code')
            ->where('source_path', '=', $sourcePath)
            ->first();

        if ($row === null) {
            return null;
        }

        return [
            'source_path' => is_string($row['source_path']) ? $row['source_path'] : '',
            'target_path' => is_string($row['target_path']) ? $row['target_path'] : '',
            'status_code' => is_numeric($row['status_code']) ? (int) $row['status_code'] : 301,
        ];
    }

    public function upsert(string $sourcePath, string $targetPath, int $statusCode): void
    {
        $existing = $this->findBySource($sourcePath);
        if ($existing === null) {
            $this->connection->query()
                ->table(RedirectSchemaInstaller::TABLE)
                ->insert([
                    'source_path' => $sourcePath,
                    'target_path' => $targetPath,
                    'status_code' => $statusCode,
                ]);

            return;
        }

        $this->connection->query()
            ->table(RedirectSchemaInstaller::TABLE)
            ->where('source_path', '=', $sourcePath)
            ->update([
                'target_path' => $targetPath,
                'status_code' => $statusCode,
            ]);
    }
}

Step 2: Implement OperationInterface with Dry-Run & Hashes

Create src/Operation/RedirectUpsertOperation.php. Pay close attention to four invariants that make Change Proposals work reliably:

  1. Declare requiredPermissions: ['acme.redirects.write'] so OperationBus enforces RBAC and ProposalCreateOperation recognizes propose.acme.redirects.write for dry-run staging.
  2. Set mutatesState: true and supportsDryRun: true.
  3. Never mutate storage when $context->dryRun === true.
  4. Return deterministic beforeHash (computed from the current live record, or null when creating) and afterHash (computed from the canonical resulting record) plus a structured diff.
php
<?php

declare(strict_types=1);

namespace Acme\Redirects\Operation;

use Acme\Redirects\Storage\RedirectRepository;
use PhrameCms\Core\Contract\OperationInterface;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationMetadata;
use PhrameCms\Core\Operation\OperationResult;

final readonly class RedirectUpsertOperation implements OperationInterface
{
    public const string NAME = 'acme.redirect.upsert';

    public function __construct(
        private RedirectRepository $repository,
    ) {}

    public function metadata(): OperationMetadata
    {
        return new OperationMetadata(
            name: self::NAME,
            description: 'Create or update an HTTP redirect rule with dry-run diff preview.',
            inputSchema: [
                'type' => 'object',
                'required' => ['source_path', 'target_path'],
                'properties' => [
                    'source_path' => [
                        'type' => 'string',
                        'pattern' => '^/[a-zA-Z0-9/_-]+$',
                        'maxLength' => 255,
                    ],
                    'target_path' => [
                        'type' => 'string',
                        'pattern' => '^/[a-zA-Z0-9/_-]+$',
                        'maxLength' => 255,
                    ],
                    'status_code' => [
                        'type' => 'integer',
                        'enum' => [301, 302, 307, 308],
                    ],
                ],
                'additionalProperties' => false,
            ],
            outputSchema: [
                'type' => 'object',
                'required' => ['redirect', 'changed'],
                'properties' => [
                    'redirect' => ['type' => 'object'],
                    'changed' => ['type' => 'boolean'],
                ],
                'additionalProperties' => false,
            ],
            requiredPermissions: ['acme.redirects.write'],
            mutatesState: true,
            supportsDryRun: true,
        );
    }

    /** @param array<string, mixed> $input */
    public function execute(array $input, ExecutionContext $context): OperationResult
    {
        $sourcePath = (string) $input['source_path'];
        $targetPath = (string) $input['target_path'];
        $statusCode = isset($input['status_code']) && is_int($input['status_code']) ? $input['status_code'] : 301;

        $before = $this->repository->findBySource($sourcePath);
        $after = [
            'source_path' => $sourcePath,
            'target_path' => $targetPath,
            'status_code' => $statusCode,
        ];

        $changed = $before !== $after;

        if (!$context->dryRun && $changed) {
            $this->repository->upsert($sourcePath, $targetPath, $statusCode);
        }

        return new OperationResult(
            data: [
                'redirect' => $after,
                'changed' => $changed,
            ],
            dryRun: $context->dryRun,
            diff: [
                'before' => $before,
                'after' => $after,
            ],
            target: 'redirect:' . $sourcePath,
            beforeHash: $before !== null ? self::hash($before) : null,
            afterHash: self::hash($after),
        );
    }

    /** @param array<string, mixed> $payload */
    private static function hash(array $payload): string
    {
        ksort($payload);

        return hash('sha256', json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
    }
}

Step 3: Register in ModuleInterface

Create src/RedirectsModule.php:

php
<?php

declare(strict_types=1);

namespace Acme\Redirects;

use Acme\Redirects\Operation\RedirectUpsertOperation;
use Acme\Redirects\Storage\RedirectRepository;
use Acme\Redirects\Storage\RedirectSchemaInstaller;
use PhrameCms\Core\Contract\ContainerBuilderInterface;
use PhrameCms\Core\Contract\ModuleInterface;
use PhrameCms\Core\Operation\OperationRegistry;
use PhrameCms\Database\Contract\SchemaInstallerInterface;
use PhrameCms\Database\DatabaseModule;
use Psr\Container\ContainerInterface;

final readonly class RedirectsModule implements ModuleInterface
{
    public const string NAME = 'acme.redirects';

    public function name(): string
    {
        return self::NAME;
    }

    /** @return list<string> */
    public function dependencies(): array
    {
        return [DatabaseModule::NAME];
    }

    public function register(ContainerBuilderInterface $builder): void
    {
        $builder->autowire(RedirectSchemaInstaller::class, [SchemaInstallerInterface::SERVICE_TAG]);
        $builder->autowire(RedirectRepository::class);
        $builder->autowire(RedirectUpsertOperation::class, [OperationRegistry::OPERATION_TAG]);
    }

    public function boot(ContainerInterface $container): void {}
}

Install the new table idempotently via ./bin/phrame schema:install --json.


Step 4: Use Your Operation on Every Surface

1. CLI (./bin/phrame)

Inspect the schema, preview with --dry-run, and execute live with an idempotency key:

bash
./bin/phrame op:describe acme.redirect.upsert --json

./bin/phrame op:run acme.redirect.upsert \
  --input='{"source_path":"/old-docs","target_path":"/docs","status_code":301}' \
  --scopes=acme.redirects.write \
  --dry-run --json

./bin/phrame op:run acme.redirect.upsert \
  --input='{"source_path":"/old-docs","target_path":"/docs","status_code":301}' \
  --scopes=acme.redirects.write \
  --idempotency-key=redirect-old-docs-1 --json

2. MCP (POST /mcp or ./bin/phrame-mcp)

McpServer automatically exposes acme.redirect.upsert as the sanitized MCP tool acme_redirect_upsert with dry_run and idempotency_key injected into its inputSchema:

bash
curl -fsS -X POST https://cms.example.test/mcp \
  -H "Authorization: Bearer <agent-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "acme_redirect_upsert",
      "arguments": {
        "source_path": "/blog-2025",
        "target_path": "/blog",
        "status_code": 301,
        "dry_run": true
      }
    }
  }'

3. Change Proposals (proposal.create → proposal.approve)

An AI agent holding proposal.create and propose.acme.redirects.write (with no live acme.redirects.write) can stage the redirect for human review:

bash
curl -fsS -X POST https://cms.example.test/mcp \
  -H "Authorization: Bearer <propose-only-agent-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "proposal_create",
      "arguments": {
        "operation": "acme.redirect.upsert",
        "input": {
          "source_path": "/legacy-pricing",
          "target_path": "/pricing",
          "status_code": 301
        },
        "reason": "Redirect deprecated pricing URL after Q3 relaunch"
      }
    }
  }'

A human reviewer then inspects the diff and approves it in /admin/proposals or via ./bin/phrame op:run proposal.approve --input='{"id":"prop_..."}' --scopes='proposal.review,acme.redirects.write' --json.


Step 5: Test Across OperationBus, MCP, and Proposals In-Process

php
<?php

declare(strict_types=1);

namespace Acme\Redirects\Tests;

use Acme\Redirects\RedirectsModule;
use PhrameCms\Core\Exception\AuthorizationException;
use PhrameCms\Core\Kernel;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationBus;
use PhrameCms\Core\Operation\OperationRequest;
use PhrameCms\Core\Security\ActorType;
use PhrameCms\Database\DatabaseModule;
use PhrameCms\Database\Schema\SchemaInstallRunner;
use PhrameCms\Mcp\Contract\McpServerInterface;
use PhrameCms\Mcp\McpModule;
use PhrameCms\Mcp\Protocol\JsonRpcRequest;
use PhrameCms\Proposal\ProposalModule;
use PhrameCms\User\Security\AuthenticatedActor;
use PhrameCms\User\UserModule;
use PHPUnit\Framework\TestCase;

final class RedirectUpsertOperationTest extends TestCase
{
    public function testWorksAcrossMcpAndProposals(): void
    {
        $kernel = new Kernel([
            new DatabaseModule('memory://'),
            new UserModule(),
            new ProposalModule(),
            new McpModule(),
            new RedirectsModule(),
        ]);
        $kernel->boot();

        $container = $kernel->container();
        $container->getTyped(SchemaInstallRunner::class, SchemaInstallRunner::class)->installAll();

        $bus = $container->getTyped(OperationBus::class, OperationBus::class);
        $mcp = $container->getTyped(McpServerInterface::class, McpServerInterface::class);

        $proposeOnlyAgent = new AuthenticatedActor(
            id: 'tok_agent',
            type: ActorType::Agent,
            scopes: ['proposal.create', 'propose.acme.redirects.write'],
        );

        // 1. Direct live execution is denied for the propose-only agent
        try {
            $bus->execute(new OperationRequest(
                operation: 'acme.redirect.upsert',
                input: ['source_path' => '/old', 'target_path' => '/new'],
                context: new ExecutionContext($proposeOnlyAgent, 'corr-1'),
            ));
            self::fail('Expected AuthorizationException.');
        } catch (AuthorizationException) {
            // Expected
        }

        // 2. Staging via MCP proposal_create succeeds with a computed diff and afterHash
        $rpc = $mcp->handle(
            new JsonRpcRequest(
                jsonrpc: '2.0',
                id: 1,
                method: 'tools/call',
                params: [
                    'name' => 'proposal_create',
                    'arguments' => [
                        'operation' => 'acme.redirect.upsert',
                        'input' => ['source_path' => '/old', 'target_path' => '/new', 'status_code' => 301],
                        'reason' => 'Fix broken inbound link',
                    ],
                ],
            ),
            $proposeOnlyAgent,
        );
        self::assertNotNull($rpc);
        $payload = json_decode((string) $rpc->result['content'][0]['text'], true, 512, JSON_THROW_ON_ERROR);
        $proposalId = (string) $payload['data']['proposal']['id'];

        // 3. Human reviewer approves and applies live
        $reviewer = new AuthenticatedActor(
            id: 'usr_reviewer',
            type: ActorType::Human,
            scopes: ['proposal.review', 'acme.redirects.write'],
        );
        $approved = $bus->execute(new OperationRequest(
            operation: 'proposal.approve',
            input: ['id' => $proposalId, 'review_note' => 'Verified target route'],
            context: new ExecutionContext($reviewer, 'corr-2'),
        ));

        self::assertSame('approved', $approved->data['proposal']['status']);
        self::assertTrue($approved->data['execution']['data']['changed']);
    }
}