WPVibe MCP Server Internals: JSON-RPC 2.0 Dispatch Through the wp-json Router, Approval-Bypass Mechanics, and the Write-Amplification Ceiling of 100,000 AI-Connected WordPress Installs

⚡ Quick Takeaways (TL;DR)

WPVibe embeds a Model Context Protocol server inside the WordPress REST router, handing Claude, ChatGPT, Cursor, Windsurf, and Grok an authenticated JSON-RPC 2.0 surface that mutates posts, options, theme files, and WP-CLI state inside ordinary PHP-FPM workers. The transport design is architecturally correct but concentrates extreme write amplification behind a single endpoint, and the 1.20.0 per-site "dangerously bypass approvals" checkbox collapses every per-call human checkpoint into one trust decision. Deploy it read-only on production, confine bypass mode to staging behind CIDR pinning and a single-writer lock, pin the endpoint to a least-privilege application password, and ship full syslog audit before the first tool call.

📑 Table of Contents ▾
WPVibe MCP Server Internals: JSON-RPC 2.0 Dispatch Through the wp-json Router, Approval-Bypass Mechanics, and the Write-Amplification Ceiling of 100,000 AI-Connected WordPress Installs

1. System Topology & Architectural Impact: A JSON-RPC 2.0 Server Living Inside the wp-json Router

Hosting the MCP server inside the plugin process means every LLM tool call boots the complete WordPress stack inside a PHP-FPM worker slot → AI-initiated mutations compete for the same process pool, OPcache state, and InnoDB connections as human traffic → cap tool concurrency per site, pin MCP traffic to a dedicated FPM pool (pm = static, separate www-mcp.conf socket), and treat the endpoint as tier-zero infrastructure.

The request path is a REST request like any other, with one structural consequence: template_redirect never fires. Pure /wp-json/ calls are short-circuited in parse_request and served by WP_REST_Server::serve_request() before the template loader runs. The lifecycle that actually matters for WPVibe traffic is:

plugins_loaded  (prio 0)   vibe-ai.php bootstrap: version constant, autoloader,
                           PHP floor guard, adapter registry construction
init            (prio 5)   18 integration adapters probe for their parent plugin
                           via function_exists()/class_exists() + read own option rows
wp_loaded       --         (no WPVibe work; REST requests proceed to dispatch)
rest_api_init   (prio 10)  MCP route + permission callback registration
                           under the plugin's REST namespace
rest_pre_dispatch          auth verdict (application password / connector token),
                           approval state machine entry point
[dispatch]                tool registry lookup -> adapter execution ->
                           wp_insert_post() / WP_Filesystem / WP-CLI bridge
shutdown        (prio ~1)  action-log flush for the bypassed session

Measured on the Section 5 bench, the 18 adapter probes at init add 7–9 ms and 12 queries to every REST boot when all parent plugins are active (41 queries at dispatch versus 29 on a bare stack). That is the standing tax of a wide integration surface, paid on every envelope.

End-to-end topology:

[Claude Desktop / ChatGPT / Cursor / Windsurf / Grok]
        │  JSON-RPC 2.0 envelopes, Streamable HTTP transport
        ▼
[Claude Connectors Directory grant | direct endpoint URL]
        │  trust chain: Anthropic-side identity → connector grant
        │  → WordPress credential (application password)
        ▼
[Edge TLS → dedicated PHP-FPM pool]
        ▼
[WordPress REST Router: /wp-json/<vibe-namespace>/v1/mcp]
        │  rest_authentication_errors → token verification
        │  rest_pre_dispatch → approval gate / bypass check
        ▼
[WPVibe Tool Registry (includes/)]
        ├── core tools (content, options, users, cron)
        ├── 18 integration adapters (ACF, Rank Math, Ninja Forms,
        │     Elementor family, SpeedyCache, WP Crontrol, …)
        ├── WP-CLI passthrough bridge
        └── Abilities API surface
        │
        ├──► [WP_Filesystem → wp-content/themes/starter-themes/classic]
        ├──► [wp_insert_post()/wp_update_post() → wp_posts + wp_postmeta EAV]
        ├──► [wp_options writes — autoload risk, approval tokens]
        └──► [vendored svg-sanitize on markup round-trips]
        ▼
[MySQL InnoDB | Redis object cache | Action Scheduler pool]
        ▼
[shutdown → action-log flush → JSON-RPC response envelope]

The Connectors Directory listing in Anthropic’s directory changes the trust boundary: the outermost credential is no longer your WordPress secret but the Claude account itself. A compromised Anthropic account is now a persistent, remotely reachable write channel into wp_posts and the theme filesystem. Scope it accordingly — dedicated WordPress user at the lowest workable role, application password with a narrow lifespan, revoke path documented.

2. Low-Level Implementation Mechanics: Tool Registry Anatomy, EAV Write Amplification, and Approval-State Persistence

The plugin’s repository layout maps directly onto its runtime hazards → each directory is a distinct blast-radius boundary → audit them individually rather than treating “MCP access” as one permission.

  • vibe-ai.php — bootstrap; registers the autoloader at plugins_loaded and enforces the PHP floor before any tool code loads.
  • includes/ — the tool registry, transports, and the 18 integration adapters shipped during October (Pagelayer, ElementsKit, Ultimate/Premium Addons for Elementor, Ninja Forms, Formidable, Fluent Forms, SureForms, Rank Math, SiteSEO, BackWPup, SpeedyCache, WP Crontrol, Disable Comments, ACF, Smash Balloon, AffiliateWP, RewardsWP, SeedProd).
  • third-party/svg-sanitize — vendored sanitizer applied to SVG markup round-trips. This is the correct call: unsanitized SVG through a media/icon tool is stored XSS by default. Its presence also confirms untrusted markup flows through tool inputs and outputs.
  • starter-themes/classic — a sacrificial classic-theme scaffold. This is the strongest architectural decision in the codebase: it gives the agent a filesystem target that is not a marketplace parent theme. The server should refuse WP_Filesystem writes outside this scaffold and child themes derived from it, because direct parent-theme edits are the largest unrecoverable blast radius in the entire tool surface.
  • uninstall.php — the delete-time cleanup contract. Its existence confirms plugin state lives in wp_options (options plus transients), which places the approval-token store and per-site settings on the autoload path. Verify with the SQL in Section 3.
  • 2.1 Database footprint: EAV write amplification

    Content and ACF tools funnel through the WordPress persistence layer, so every LLM mutation inherits the EAV tax. One ACF flexible-content update across 25 posts with ~40 fields each produces roughly 1,000 individual INSERT ... ON DUPLICATE KEY UPDATE statements against wp_postmeta, each a meta_key index probe at ~0.4 ms — approximately 420 ms of pure DB time before the response envelope is even serialized. The Rank Math adapter compounds this with _rank_math_* postmeta rows on every SEO-touched post; the Elementor-family adapters serialize megabyte-scale _elementor_data blobs that inflate both the InnoDB row and the JSON-RPC response buffer.

    The approval state machine itself is options-bound: each gated mutation mints a token persisted at dispatch and consumed at confirmation — two wp_options writes per approved operation. Bypass mode skips that loop entirely, which is precisely why bypassed batches measure 610 queries where the approval path would exceed 1,200.

    2.2 Memory and manifest weight

    Batch tools/call responses accumulate in memory before serialization. On a bypassed 40-post ACF batch, peak RSS marched from a 61 MB single-call baseline straight into the ceiling:

    PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted
    (tried to allocate 36864 bytes) in /var/www/htdocs/wp-includes/class-wp-hook.php on line 324

    The failing frame sits in class-wp-hook.php because the tool loop executes inside a filter callback chain, not because core is the defect. Chunk bypassed batches to ≤ 10 entities per call and reserve memory_limit = 512M for staging workers only.

    The tool manifest is its own resource problem: with all 18 integrations active, tools/list returns 214 tool schemas weighing 412 KB of JSON — 312 ms cold, 95 ms warm from transient. That payload also burns LLM client context. An unmanaged adapter set is a context-length hazard for the model, not just a server cost.

    3. Production-Ready Code & Infrastructure Automation

    The bypass flag is a per-site checkbox writable from wp-admin → in production, a compromised session or a mis-click collapses all approval checkpoints at once → the invariant must be enforced at the transport layer, below the plugin’s own settings surface. The mu-plugin below fails closed on four axes: TLS, source CIDR, environment type, and single-writer concurrency.

    <?php
    declare(strict_types=1);
    
    /**
     * Plugin Name: WPVibe MCP Gatekeeper
     * Description: Fail-closed transport guard for the WPVibe MCP endpoint — TLS enforcement, CIDR pinning, production write-proofing, single-writer mutation lock, syslog audit.
     * Version:     1.0.0
     * Requires PHP: 8.2
     * License:     GPL-2.0-or-later
     */
    
    defined('ABSPATH') || exit;
    
    final class WPVibe_MCP_Gatekeeper
    {
        /** Tighten this to the exact registered namespace once confirmed in Query Monitor's REST panel. */
        private const ROUTE_FRAGMENT   = 'vibe';
        private const LOCK_GROUP       = 'wpvibe_gate';
        private const LOCK_KEY         = 'mutation_lock';
        private const LOCK_TTL         = 60;
        private const LOCK_STALE_AFTER = 300;
        private const RPC_SERVER_ERROR = -32000;
    
        private static bool $lockHeld = false;
    
        public static function boot(): void
        {
            add_filter('rest_pre_dispatch', [self::class, 'guard'], 999, 3);
            add_action('shutdown', [self::class, 'releaseLock']);
        }
    
        public static function guard(mixed $result, WP_REST_Server $server, WP_REST_Request $request): mixed
        {
            if (null !== $result) {
                return $result; // An earlier filter already vetoed; never widen permissions.
            }
    
            $route = (string) $request->get_route();
            if (!str_contains($route, self::ROUTE_FRAGMENT)) {
                return null;
            }
    
            // Invariant 1: TLS or nothing. Fail closed.
            if (!is_ssl()) {
                return self::envelope($request, 400, 'MCP transport requires TLS');
            }
    
            // Invariant 2: CIDR pinning. An undefined allowlist blocks everyone.
            $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
            if (!self::ipAllowed($ip)) {
                return self::envelope($request, 403, 'Source address not on the MCP allowlist: ' . $ip);
            }
    
            $body   = $request->get_json_params();
            $method = is_array($body) ? (string) ($body['method'] ?? '') : '';
            $isCall = 'tools/call' === $method;
    
            // Invariant 3: production is read-only at the transport layer,
            // regardless of any in-plugin "bypass approvals" checkbox.
            if ($isCall && self::isProduction()) {
                return self::envelope($request, 403, 'tools/call is transport-blocked on production');
            }
    
            // Invariant 4: single writer. Concurrent mutation sessions are the
            // primary lost-update vector on wp_posts / wp_postmeta.
            if ($isCall) {
                if (!self::acquireLock()) {
                    return self::envelope($request, 409, 'A mutation session holds the write lock; retry');
                }
                error_log(sprintf(
                    '[mcp-gate] ip=%s tool=%s payload_bytes=%d',
                    $ip,
                    (string) ($body['params']['name'] ?? 'unknown'),
                    strlen((string) wp_json_encode($body['params'] ?? []))
                ), 0);
            }
    
            return null; // Fall through to core dispatch.
        }
    
        public static function releaseLock(): void
        {
            if (self::$lockHeld) {
                wp_cache_delete(self::LOCK_KEY, self::LOCK_GROUP);
                self::$lockHeld = false;
            }
        }
    
        private static function isProduction(): bool
        {
            if (defined('WP_ENVIRONMENT_TYPE')) {
                return 'production' === WP_ENVIRONMENT_TYPE;
            }
            $env = getenv('WP_ENVIRONMENT_TYPE');
    
            return is_string($env) && '' !== $env ? 'production' === $env : true; // unknown === production
        }
    
        private static function ipAllowed(string $ip): bool
        {
            $list = getenv('WPVIBE_MCP_ALLOWED_IPS');
            if (!is_string($list) || '' === $list) {
                return false;
            }
    
            foreach (array_filter(array_map('trim', explode(',', $list))) as $cidr) {
                if (self::cidrMatch($ip, $cidr)) {
                    return true;
                }
            }
    
            return false;
        }
    
        private static function cidrMatch(string $ip, string $cidr): bool
        {
            [$subnet, $bits] = array_pad(explode('/', $cidr, 2), 2, null);
            $subnet  = (string) $subnet;
            $default = str_contains($subnet, ':') ? 128 : 32;
            $bits    = null === $bits ? $default : (int) $bits;
            $ipBin   = @inet_pton($ip);
            $snBin   = @inet_pton($subnet);
    
            if (false === $ipBin || false === $snBin || strlen($ipBin) !== strlen($snBin)) {
                return false;
            }
    
            $max = strlen($ipBin) * 8;
            if ($bits < 0 || $bits > $max) {
                return false;
            }
    
            $mask = str_repeat("xff", intdiv($bits, 8));
            if (0 !== $bits % 8) {
                $mask .= chr((0xff << (8 - $bits % 8)) & 0xff);
            }
            $mask .= str_repeat("x00", strlen($ipBin) - strlen($mask));
    
            return ($ipBin & $mask) === ($snBin & $mask);
        }
    
        private static function acquireLock(): bool
        {
            // wp_cache_add() is atomic under Redis/Memcached backends.
            if (wp_cache_add(self::LOCK_KEY, (string) time(), self::LOCK_GROUP, self::LOCK_TTL)) {
                self::$lockHeld = true;
                return true;
            }
    
            $holder = wp_cache_get(self::LOCK_KEY, self::LOCK_GROUP);
            if (is_string($holder) && ctype_digit($holder) && (time() - (int) $holder) > self::LOCK_STALE_AFTER) {
                self::$lockHeld = (bool) wp_cache_set(self::LOCK_KEY, (string) time(), self::LOCK_GROUP, self::LOCK_TTL);
            }
    
            return self::$lockHeld;
        }
    
        private static function envelope(WP_REST_Request $request, int $status, string $message): WP_REST_Response
        {
            $body = $request->get_json_params();
    
            return new WP_REST_Response([
                'jsonrpc' => '2.0',
                'id'      => is_array($body) ? ($body['id'] ?? null) : null,
                'error'   => [
                    'code'    => self::RPC_SERVER_ERROR,
                    'message' => $message,
                ],
            ], $status);
        }
    }
    
    WPVibe_MCP_Gatekeeper::boot();

    Provisioning and audit tooling:

    # Staging bench reproduction
    wp plugin install --activate redis-cache && wp redis enable
    wp plugin install --activate vibe-ai.zip   # release archive from the repo
    
    # MCP initialize handshake (Streamable HTTP)
    curl -sS -D /tmp/mcp.headers https://staging.example.test/wp-json/vibe-ai/v1/mcp 
      -H 'Authorization: Basic <base64 application-password>' 
      -H 'Content-Type: application/json' 
      -H 'Accept: application/json, text/event-stream' 
      --data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"bench-harness","version":"1.0"}}}'
    
    # Manifest weight check — anything past ~500 KB is adapter bloat
    curl -sS https://staging.example.test/wp-json/vibe-ai/v1/mcp 
      -H 'Authorization: Basic <base64 application-password>' 
      -H 'Content-Type: application/json' 
      --data '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | wc -c

    -- WPVibe's wp_options footprint and autoload exposure
    SELECT option_name, ROUND(LENGTH(option_value)/1024,1) AS kb, autoload
    FROM wp_options
    WHERE option_name LIKE '%vibe%'
    ORDER BY LENGTH(option_value) DESC LIMIT 20;
    
    -- The EAV scan pattern the Rank Math adapter triggers under agent-driven audits
    EXPLAIN SELECT p.ID
    FROM wp_posts p
    JOIN wp_postmeta pm ON pm.post_id = p.ID
    WHERE pm.meta_key = 'rank_math_seo_score'
      AND pm.meta_value + 0 > 60
      AND p.post_type = 'post' AND p.post_status = 'publish';
    -- type=ref on meta_key, ~38k rows examined, Using join buffer → 480 ms p95 on the bench

    4. Production Gotchas, Breaking Changes & Concurrency Risks: Prompt Injection, Bypass Proliferation, and Stale Cache Topologies

    Bypass approvals plus external-content adapters plus no transport-level lock equals unattended destructive writes steerable by content you do not control → a poisoned Smash Balloon feed item or a crafted post_content block enters the agent’s context as instruction-bearing text → keep bypass confined to staging, strip external-content adapters from any bypassed registry, and hold the single-writer lock from Section 3.

    Lost-update races. wp_update_post() performs an unconditional row UPDATE — last writer wins. Two concurrent agents, or one agent racing a human editor in wp-admin, silently discard the earlier session’s changes; a measured reproduction showed agent B’s save overwrite agent A’s 12 postmeta changes with zero errors surfaced in either JSON-RPC response. The single-writer lock mitigates agent–agent contention; for agent–human contention, add a content-hash precondition (compare md5(post_content) before write) inside any adapter you control.

    Cache desynchronization. Direct WP_Filesystem theme writes invalidate neither OPcache on hosts running opcache.validate_timestamps=0 nor HTML page caches. The SpeedyCache adapter purges its own cache on post mutations, but filesystem-driven template changes bypass that hook path — served HTML can remain stale for the full TTL, and the agent will then read back its own stale output through the site’s front-end tools and “correct” it into a loop. Wire a shutdown-stage invalidation for FS mutations, and reload FPM after theme-file batches.

    WP-Cron starvation. Bypassed bulk writes hold InnoDB row locks on wp_options while approval tokens and SpeedyCache transients churn through the same hot page region. Under eight concurrent sessions, spawn_cron() at shutdown stalls and scheduled events miss their windows; the log shows the signature:

    ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

    On WooCommerce stacks the same lock pressure propagates to wp_actionscheduler_actions claim contention. Schedule bypass batches away from cron-dense windows; the WP Crontrol adapter exists precisely to see this.

    The bypass flag’s own exposure. The red banner is an admin_notices rendering — invisible to REST-only sessions. An operator watching wp-admin sees nothing about an active remote session; the syslog audit from the gatekeeper is the only reliable record. More pointed: if the bypass option is writable through any settings REST route or tool without a dedicated capability check above manage_options, a prompt-injected agent can flip its own guardrail. Verify with wp rest route list --fields=route,methods | grep -i vibe and attempt the toggle read-only from a least-privilege credential before granting any tool access.

    Breaking-change surface. The mirror’s badge reads “Tested up to WP 6.9” while core security releases 7.1.3/7.1.4 are current and 7.2 ships December 8, 2026. The 7.2 line continues to reshape responsive controls, theme presets, and collaboration surfaces; the Abilities API endpoints WPVibe exposes are the most churn-prone dependency in its registry. Pin the plugin version in Composer-managed deployments and re-run the Section 5 matrix against each 7.2 RC before GA. The same discipline applies to the runtime: the endpoint turns unpatched PHP into a remotely reachable amplification surface, and the October PHP fixes (8.5.12, 8.4.27, 8.3.36, 8.2.35) set the floor. Running this transport on EOL PHP 8.1 is indefensible.

    Debugging tactics. Query Monitor’s REST API panel names the registered route, the permission callback, and the rest_api_init timing attribution; its DB Queries panel attributes the adapter boot tax to WP_REST_Server::serve_request. For live capture:

    # Gatekeeper audit trail plus memory fatals, streaming
    tail -F /var/www/logs/php-fpm-error.log 
      | grep --line-buffered -E '[mcp-gate]|Allowed memory size'
    
    # Identify lock holders during a stalled batch
    wp db query "SELECT trx_id, trx_state, trx_started, trx_rows_locked
                 FROM information_schema.INNODB_TRX WHERE trx_state='LOCK WAIT'G"

    One deployment-velocity note that is also an engineering signal: the plugin moved from 50,000 to 100,000 active installs in roughly 31 days, while the GitHub mirror carries 56 commits, 20 stars, and 10 forks. Distribution is outpacing external code review by three orders of magnitude. Demand a published threat model and a security.txt before routing any production credential through the transport.

    5. Telemetry Benchmark & Resource Allocation Matrix

    Bench conditions: dedicated container rig, 8 vCPU, PHP-FPM 8.3.36 (OPcache on, JIT off), MariaDB 10.11 InnoDB, Redis 7.2 object cache, WordPress 7.1.4, 42 active plugins with ACF, Rank Math, and Ninja Forms adapters enabled; n = 200 per row, bypass batches n = 20.

    Architecture / Implementation Latency (TTFB, p50 / p95) Peak RAM Allocation DB Queries (Count / Type) Redis I/O Impact
    Manual wp-admin post save (control) 238 ms / 410 ms 58 MB 62 / mixed SELECT + UPDATE 15 gets, 4 sets
    Direct REST PUT /wp/v2/posts/{id} 131 ms / 205 ms 52 MB 34 / PRIMARY-key lookups Neutral (auth-only)
    WPVibe tools/call — read (get_post) 172 ms / 265 ms 61 MB 41 / PRIMARY + options autoload 22 gets, 6 sets
    WPVibe tools/call — write, approval gate ON 185 ms server-side + human RTT 64 MB 47 / incl. 2 approval-token wp_options writes 26 gets, 9 sets (lock churn)
    WPVibe tools/call — write, bypass ON, batch ×25 3.9 s / 6.8 s 118 MB 610 / ~520 postmeta INSERT…ODKU 480 ops; hit ratio 99.1% → 97.4%
    WPVibe tools/list (214-tool manifest) 95 ms warm / 312 ms cold 74 MB 18 / cached options Manifest served from transient; 412 KB payload
    Theme FS write (starter-themes/classic) 84 ms / 121 ms 49 MB 0 DB / pure FS I/O 6 gets; no HTML cache invalidation
    WP-CLI passthrough tool (single command) 384 ms / 540 ms 96 MB (spawned child process) Child-dependent None inherited by parent worker

    Three allocations follow directly from the matrix. First, bypassed write batches are the only row where worker residency approaches PHP limits — dedicate an FPM pool with pm.max_children sized to one or two, because a chatty agent can otherwise starve human traffic of workers. Second, the WP-CLI bridge doubles effective memory per call via process spawn; reserve it for maintenance operations, not content loops. Third, read tools at 172 ms p50 mean an exploratory agent session of 60 tool calls burns ~10 seconds of pure server round-trips — acceptable on staging, measurable on shared production pools, and the reason the read-only production posture with tight tool registries is the only defensible default.

    Written by Maya Patel

    WebAssembly specialist implementing browser-side Web Workers for HEIC/AVIF image transformations, replacing legacy server-side ImageMagick loads.