Open for Freelance & Projects
f in yt wp

Securing WordPress AI REST & MCP Endpoints Against Prompt Injection & Billing Attacks

Abdullah Nahian Updated: November 29, 2026 Reading Time: 6 mins

Connecting WordPress to Large Language Models via custom REST endpoints or the official WordPress MCP Adapter opens up powerful automation—from AI search assistants to automated content auditing. However, exposing an LLM-backed endpoint on the public web introduces two severe risks that traditional WordPress firewalls do not stop: indirect prompt injection (where untrusted post content or user input hijacks an AI agent’s tool calls) and API billing exhaustion (where automated bots drain your OpenAI, Gemini, or Anthropic token budget in minutes).

In this security guide, you will learn how to lock down both custom WordPress AI REST routes and MCP Adapter servers using granular capability checks, ability opt-outs, indirect prompt-injection delimiters, sliding-window rate limits, and daily token caps in pure PHP.

1. Narrow MCP Exposure with meta.mcp.public & Dedicated Users

The WordPress MCP Adapter (0.7.x) automatically bridges any registered WordPress ability marked public to its default HTTP endpoint (/wp-json/mcp/mcp-adapter-default-server). If you install third-party plugins that register write or delete abilities, an over-privileged AI agent could inadvertently modify content or settings.

Enforce a strict allowlist by hooking into wp_register_ability_args inside a custom mu-plugin so only explicitly approved, read-only abilities are exposed over HTTP MCP:

<?php
/**
 * Restrict HTTP MCP exposure strictly to an explicit allowlist of read-only abilities.
 */
add_filter( 'wp_register_ability_args', function ( array $args, string $ability_name ) {
    $allowed_mcp_abilities = array(
        'core/content-query',
        'devnahian/audit-autoload-options',
    );

    if ( ! in_array( $ability_name, $allowed_mcp_abilities, true ) ) {
        $args['meta']['mcp']['public'] = false;
    }

    return $args;
}, 20, 2 );

Pair this filter with a dedicated WordPress user account (for example, mcp_reader assigned a custom role with only read capability) when generating an Application Password. Because the MCP Adapter verifies every ability’s permission_callback against the authenticated user before execution, a least-privilege user blocks destructive actions at the core layer.

2. Defend Against Indirect Prompt Injection

The most dangerous prompt injection attack in WordPress is not a user typing “ignore previous instructions” into a chat box—it is indirect prompt injection hidden inside untrusted database content, such as a WooCommerce product review, contact form submission, or third-party RSS feed summarized by an AI agent.

Protect your AI prompts using three defensive layers:

  • Isolate Untrusted Data with XML Delimiters: Wrap user-submitted text or post content inside explicit tags (such as <untrusted_content>) and instruct the system prompt never to follow commands found inside those tags.
  • Strip Hidden HTML & Zero-Width Characters: Attackers often hide prompt injections inside display:none spans, HTML comments, or zero-width Unicode characters. Always sanitize with wp_strip_all_tags() and strip invisible control characters before sending text to an LLM.
  • Never Pair Untrusted Input with Write Tools: When an AI workflow processes public comments, form entries, or external pages, pass zero state-changing abilities to the resolver.
<?php
/**
 * Sanitize untrusted post or comment text before passing it into an LLM prompt.
 *
 * @param string $raw_text Untrusted database or user input.
 * @param int    $max_words Maximum word budget.
 * @return string
 */
function devnahian_prepare_untrusted_llm_input( string $raw_text, int $max_words = 400 ): string {
    // Remove HTML tags, comments, and script/style blocks
    $text = wp_strip_all_tags( $raw_text, true );

    // Strip zero-width spaces and non-printable control characters
    $text = preg_replace( '/[\x{200B}-\x{200D}\x{FEFF}\x00-\x1F\x7F]/u', '', $text );

    // Enforce strict word cap to bound prompt token usage
    $text = wp_trim_words( $text, $max_words, '' );

    return "<untrusted_content>\n" . $text . "\n</untrusted_content>";
}

3. Stop API Billing Attacks with Rate Limiting & Daily Token Caps

If your site exposes a public-facing AI REST endpoint (such as a frontend AI search bar or product advisor), an attacker or scraper can replay requests thousands of times per hour—turning a $5/month API key into a $2,000 overnight bill. Even if your provider dashboard has a hard monthly spend limit, hitting it knocks out legitimate site features for the rest of the month.

Implement both a per-user/IP sliding rate limit and a site-wide daily request/token circuit breaker inside your REST route’s permission_callback:

<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'devnahian/v1', '/ai-search', array(
        'methods'             => 'POST',
        'callback'            => 'devnahian_handle_ai_search_request',
        'permission_callback' => 'devnahian_check_ai_rate_and_budget',
        'args'                => array(
            'query' => array(
                'required'          => true,
                'type'              => 'string',
                'minLength'         => 3,
                'maxLength'         => 200,
                'sanitize_callback' => 'sanitize_text_field',
            ),
        ),
    ) );
} );

/**
 * Enforce nonce verification, per-client rate limiting, and a daily global budget cap.
 *
 * @param WP_REST_Request $request Incoming REST request.
 * @return bool|WP_Error
 */
function devnahian_check_ai_rate_and_budget( WP_REST_Request $request ) {
    // 1. Require a valid REST nonce for browser requests
    $nonce = $request->get_header( 'X-WP-Nonce' );
    if ( ! $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
        return new WP_Error( 'invalid_nonce', __( 'Invalid security token.', 'devnahian' ), array( 'status' => 403 ) );
    }

    // 2. Global daily circuit breaker (max 1,000 AI calls per 24 hours)
    $daily_key   = 'devnahian_ai_daily_calls_' . gmdate( 'Y_m_d' );
    $daily_calls = (int) get_transient( $daily_key );

    if ( $daily_calls >= 1000 ) {
        return new WP_Error( 'daily_budget_exceeded', __( 'AI search is temporarily unavailable.', 'devnahian' ), array( 'status' => 429 ) );
    }

    // 3. Per-user or hashed IP rate limit (max 10 requests per minute)
    $identifier = is_user_logged_in()
        ? 'user_' . get_current_user_id()
        : 'ip_' . wp_hash( $_SERVER['REMOTE_ADDR'] ?? 'unknown' );

    $rate_key   = 'devnahian_ai_rl_' . $identifier;
    $user_calls = (int) get_transient( $rate_key );

    if ( $user_calls >= 10 ) {
        return new WP_Error( 'rate_limit_exceeded', __( 'Too many AI requests. Please wait a minute.', 'devnahian' ), array( 'status' => 429 ) );
    }

    set_transient( $rate_key, $user_calls + 1, MINUTE_IN_SECONDS );
    set_transient( $daily_key, $daily_calls + 1, DAY_IN_SECONDS );

    return true;
}

4. Deterministic Prompt Caching & Output Caps

Beyond rate limiting, two simple engineering guardrails cut both latency and attack surface on every LLM call:

  1. Hash Normalized Prompts Before Calling the API: Normalize lowercase, trimmed queries with md5( strtolower( trim( $query ) ) ) and check get_transient() first. Repeated identical queries return in under 2 milliseconds at zero token cost.
  2. Always Set max_tokens & Short Timeouts: Cap completion output with using_max_tokens( 300 ) (or max_tokens in your JSON payload) and set HTTP timeouts to 10–15 seconds so stalled upstream connections cannot exhaust PHP-FPM workers during traffic spikes.
  3. Escape LLM Output Before Rendering: Treat every model response as untrusted third-party text. Render plain responses with esc_html() or pass formatted responses through wp_kses_post() so an injected markdown link or script payload can never execute in a visitor’s browser.

Final Thoughts

Securing WordPress AI endpoints requires thinking beyond traditional SQL injection and CSRF checks. By allowlisting public MCP abilities, isolating untrusted database text with XML delimiters, enforcing sliding rate limits alongside daily circuit breakers, and escaping every LLM response, you can run fast, reliable AI features in production without exposing your site or your API budget.