'mcp-adapter-default-server', 'server_route_namespace' => 'mcp', 'server_route' => 'mcp-adapter-default-server', 'server_name' => 'MCP Adapter Default Server', 'server_description' => 'Default MCP server for WordPress abilities discovery and execution', 'server_version' => 'v1.0.0', 'mcp_transports' => [ 'WP\\MCP\\Transport\\HttpTransport' ], 'error_handler' => 'WP\\MCP\\Infrastructure\\ErrorHandling\\ErrorLogMcpErrorHandler', 'observability_handler' => 'WP\\MCP\\Infrastructure\\Observability\\NullMcpObservabilityHandler', 'tools' => [ 'mcp-adapter/discover-abilities', 'mcp-adapter/get-ability-info', 'mcp-adapter/execute-ability', ], 'resources' => [], 'prompts' => [], ]; /** Register this view's admin asset hook; detection waits for render. */ public function __construct() { add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] ); } /** * Enqueue the view's assets on the Overview screen's AI Access view only. * * @param string $hook_suffix Current admin page hook suffix. * @return void */ public function enqueue_assets( $hook_suffix ): void { $view = isset( $_GET['module'] ) && is_string( $_GET['module'] ) ? sanitize_key( wp_unslash( $_GET['module'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only navigation state. if ( 'toplevel_page_' . ADMINOPTIMIZER_MODULES_MENU_SLUG !== $hook_suffix || self::VIEW_ID !== $view ) { return; } wp_enqueue_style( 'adminoptim-ai-access', ADMINOPTIMIZER_URI . 'infrastructure/ai-access/assets/css/ai-access.min.css', [], ADMINOPTIMIZER_VERSION ); // Core's plugin installer, only for users who may use it. $deps = current_user_can( 'install_plugins' ) ? [ 'updates' ] : []; wp_enqueue_script( 'adminoptim-ai-access', ADMINOPTIMIZER_URI . 'infrastructure/ai-access/assets/js/ai-access.min.js', $deps, ADMINOPTIMIZER_VERSION, true ); wp_localize_script( 'adminoptim-ai-access', 'AdminOptimizerAIAccess', [ 'copied' => __( 'Copied ✓', 'admin-optimizer' ), 'copiedAnnounce' => __( 'Copied to clipboard.', 'admin-optimizer' ), 'copyFailed' => __( 'Copy failed. Select the text and copy it manually.', 'admin-optimizer' ), 'confirmInstall' => __( 'Install and activate the WordPress MCP Adapter from WordPress.org?', 'admin-optimizer' ), 'installing' => __( 'Installing…', 'admin-optimizer' ), 'activating' => __( 'Activating…', 'admin-optimizer' ), 'installFailed' => __( "The MCP Adapter couldn't be installed. Try again from Plugins → Add New.", 'admin-optimizer' ), ] ); } /** * Gather everything the view shows. The renderer reads only this output. * Abilities are read through their getters only; nothing is executed or * permission-checked. * * @return array */ public function get_state(): array { // --- 1. Abilities API support --- $state = [ 'supported' => self::is_abilities_api_supported(), 'report' => [ 'rows' => [], 'unreadable' => 0, 'contradictions' => 0, ], 'abilities' => [], 'access' => 'readonly', 'adapter' => self::ADAPTER_NOT_INSTALLED, 'adapter_plugin' => null, 'adapter_info' => [ 'version' => null, 'bundled' => false, 'bundler' => '', ], 'endpoint' => null, 'rest_run_url' => '', 'default_server' => false, 'mcp_live' => false, 'can_install' => false, 'can_activate' => false, 'activate_url' => '', 'app_passwords' => false, 'clients' => [], 'prompts' => [], 'show_pro_strip' => false, ]; if ( ! $state['supported'] ) { return $state; } // --- 2. MCP Adapter state and endpoint --- if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $plugin_file = self::find_adapter_plugin( get_plugins() ); $state['adapter_plugin'] = $plugin_file; $state['adapter'] = self::adapter_state( class_exists( self::ADAPTER_CLASS, false ), $plugin_file, null !== $plugin_file && is_plugin_active( $plugin_file ) ); $state['endpoint'] = self::resolve_endpoint( $state['adapter'] ); $state['default_server'] = self::ADAPTER_ACTIVE === $state['adapter'] && self::is_default_server_enabled(); $state['mcp_live'] = $state['default_server']; $state['adapter_info'] = self::adapter_info( null !== $plugin_file && is_plugin_active( $plugin_file ) ); // Developers' REST run URL, from the site's real REST base. $state['rest_run_url'] = rest_url( 'wp-abilities/v1/abilities/{ability-id}/run' ); // --- 3. Every ability on the site --- // wp_get_abilities() initializes the native registry (firing // wp_abilities_api_init) on first use, so registration has run. $state['report'] = self::build_report( wp_get_abilities(), self::category_labels(), self::mcp_rule( $state['adapter'] ), self::default_server_tools( $state['adapter'] ) ); // --- 4. Admin Optimizer's own abilities (intro badge, Pro strip) --- $state['abilities'] = array_values( array_filter( $state['report']['rows'], static function ( array $row ): bool { return $row['is_ao']; } ) ); $state['access'] = self::access_level( $state['abilities'] ); $state['show_pro_strip'] = self::should_show_pro_strip( $state['abilities'], Module_Registry::is_pro_active() ); // --- 5. What the current user can do about the adapter --- $state['can_install'] = current_user_can( 'install_plugins' ); $state['can_activate'] = current_user_can( 'activate_plugins' ); if ( self::ADAPTER_INACTIVE === $state['adapter'] && null !== $plugin_file ) { $state['activate_url'] = self::activate_url( $plugin_file ); } // --- 6. Application Passwords and client instructions --- $state['app_passwords'] = function_exists( 'wp_is_application_passwords_available' ) && wp_is_application_passwords_available(); $state['clients'] = self::get_clients(); // --- 7. Sample prompts the site's abilities can answer --- $state['prompts'] = self::get_sample_prompts( $state['report']['rows'] ); return $state; } /** * Core's plugin activation URL for the adapter, with its nonce. * * @param string $plugin_file Plugin basename. * @return string Unescaped URL. */ public static function activate_url( string $plugin_file ): string { return wp_nonce_url( add_query_arg( [ 'action' => 'activate', 'plugin' => $plugin_file, ], self_admin_url( 'plugins.php' ) ), 'activate-plugin_' . $plugin_file ); } /** * AI assistants offered in step 3, keyed by a stable ID, in display order. * Adding one is a new entry here (or through the filter). Entries without * a label or text are dropped. Panels show text only, never a link. * * @return array */ public static function get_clients(): array { $clients = [ 'claude-desktop' => [ 'label' => __( 'Claude Desktop', 'admin-optimizer' ), 'text' => __( 'Add the WordPress MCP proxy (@automattic/mcp-wordpress-remote) to Claude Desktop’s config file with your MCP endpoint, username and Application Password. Requires Node.js.', 'admin-optimizer' ), ], 'claude-code' => [ 'label' => __( 'Claude Code', 'admin-optimizer' ), 'text' => __( 'Add your site to Claude Code’s MCP settings (.mcp.json or claude mcp add) with your MCP endpoint and Application Password.', 'admin-optimizer' ), ], 'chatgpt' => [ 'label' => __( 'ChatGPT', 'admin-optimizer' ), 'text' => __( 'In ChatGPT on the web, open Plugins and choose Add custom MCP server, where your workspace permits it. Enter a reachable HTTPS MCP endpoint. ChatGPT requires a supported authentication method, such as OAuth; the WordPress Application Password alone cannot be entered directly. Use an authenticated MCP gateway that supports ChatGPT and forwards requests to your site.', 'admin-optimizer' ), ], 'codex' => [ 'label' => __( 'Codex', 'admin-optimizer' ), 'text' => __( 'In Codex CLI or the IDE extension, add your MCP endpoint as the url under [mcp_servers.wordpress] in ~/.codex/config.toml. Use env_http_headers to supply an Authorization header from an environment variable containing Basic followed by a space and the Base64-encoded WordPress username:Application Password. In Codex CLI, run /mcp to check the connection.', 'admin-optimizer' ), ], 'gemini' => [ 'label' => __( 'Gemini', 'admin-optimizer' ), 'text' => __( 'Use Gemini CLI: add your MCP endpoint as an HTTP server in mcpServers in .gemini/settings.json, using httpUrl. Configure an Authorization header with HTTP Basic credentials made from your WordPress username and Application Password. Run /mcp to check the connection. These instructions are for Gemini CLI.', 'admin-optimizer' ), ], 'other' => [ 'label' => __( 'Other AI assistants', 'admin-optimizer' ), 'text' => __( 'Clients differ: some take a remote HTTP URL, others need a local proxy command. Check your client’s MCP documentation, then use your MCP endpoint and Application Password.', 'admin-optimizer' ), ], ]; /** * Filters the AI assistants listed in AI Access step 3. * * @param array $clients Assistants keyed by ID. */ $filtered = apply_filters( 'adminoptimizer_ai_access_clients', $clients ); if ( ! is_array( $filtered ) ) { return $clients; } $valid = []; foreach ( $filtered as $id => $client ) { $id = sanitize_key( (string) $id ); if ( '' === $id || ! is_array( $client ) || empty( $client['label'] ) || ! is_string( $client['label'] ) || empty( $client['text'] ) || ! is_string( $client['text'] ) ) { continue; } $valid[ $id ] = [ 'label' => $client['label'], 'text' => $client['text'], ]; } return $valid; } /** * Sample prompts for "Try asking your AI assistant": the built-in list * plus filtered additions, validated, kept only when every ability they * require is registered, sorted and capped. Each carries its "Uses" * names. The adapter's state doesn't matter; the view explains it. * * @param array $rows Report rows from build_report(). * @return array */ public static function get_sample_prompts( array $rows ): array { return self::qualifying_prompts( self::filtered_prompts(), $rows ); } /** * Built-in prompts, in registration order. Each `requires` entry is an * ability ID or PROMPT_REQUIRES_ADAPTER. * * @return array */ public static function builtin_prompts(): array { $seo = 'admin-optimizer/get-seo-health'; $security = 'admin-optimizer/get-security-health'; return [ [ 'id' => 'seo_health', 'text' => __( 'How is the SEO health of my site? List anything that needs attention, most important first.', 'admin-optimizer' ), 'requires' => [ $seo ], ], [ 'id' => 'security_health', 'text' => __( "Check my site's security health and explain any critical items in plain language.", 'admin-optimizer' ), 'requires' => [ $security ], ], [ 'id' => 'fix_first', 'text' => __( 'Check both SEO and security health, then tell me the three things I should fix first.', 'admin-optimizer' ), 'requires' => [ $seo, $security ], ], [ 'id' => 'client_summary', 'text' => __( 'Write a short health summary of this site that I can send to my client.', 'admin-optimizer' ), 'requires' => [ $seo, $security ], ], [ 'id' => 'list_forms', 'text' => __( 'List the forms I can manage on this site, including their IDs and publication status.', 'admin-optimizer' ), 'requires' => [ 'admin-optimizer/list-forms' ], ], [ 'id' => 'list_form_entries', 'text' => __( 'Help me choose a form, then list its latest submissions without submitted values. If AI access is disabled, explain how to enable Allow AI Access to Form Submissions in that form’s settings.', 'admin-optimizer' ), 'requires' => [ 'admin-optimizer/list-forms', 'admin-optimizer/list-form-entries' ], ], [ 'id' => 'get_form_entry', 'text' => __( 'Ask me for a form ID and submission ID, then retrieve that submission’s metadata without submitted values. Respect the form’s AI Access setting and my WordPress permissions.', 'admin-optimizer' ), 'requires' => [ 'admin-optimizer/get-form-entry' ], ], [ 'id' => 'list_abilities', 'text' => __( 'Which abilities can you use on my site, and which of them can make changes?', 'admin-optimizer' ), 'requires' => [ self::PROMPT_REQUIRES_ADAPTER ], ], ]; } /** * The built-in list after `adminoptimizer_ai_access_prompts`, validated. * A non-array result or any Throwable falls back to the built-in list. * * @return array Validated prompts. */ public static function filtered_prompts(): array { $builtin = self::builtin_prompts(); try { /** * Filters the sample prompts on the AI Access tab. Modules and * Pro add prompts for their own abilities here. * * @param array $prompts List of prompts: id, text, requires, optional priority. */ $filtered = apply_filters( 'adminoptimizer_ai_access_prompts', $builtin ); } catch ( \Throwable $e ) { $filtered = $builtin; } return self::validate_prompts( is_array( $filtered ) ? $filtered : $builtin ); } /** * Keep well-formed prompts only. Drops non-arrays and entries without a * valid id, text or requires; the first of a duplicate id wins. Text is * trimmed and capped at PROMPT_TEXT_LIMIT characters; priority defaults * to 10. * * @param array $prompts Raw prompts. * @return array */ public static function validate_prompts( array $prompts ): array { $valid = []; foreach ( $prompts as $prompt ) { if ( ! is_array( $prompt ) ) { continue; } $id = $prompt['id'] ?? null; $text = isset( $prompt['text'] ) && is_string( $prompt['text'] ) ? trim( $prompt['text'] ) : ''; $requires = $prompt['requires'] ?? null; if ( ! is_string( $id ) || 1 !== preg_match( '/^[a-z0-9_-]+$/', $id ) || isset( $valid[ $id ] ) || '' === $text || ! is_array( $requires ) || empty( $requires ) ) { continue; } foreach ( $requires as $requirement ) { if ( ! is_string( $requirement ) || '' === $requirement ) { continue 2; } } if ( mb_strlen( $text ) > self::PROMPT_TEXT_LIMIT ) { $text = rtrim( mb_substr( $text, 0, self::PROMPT_TEXT_LIMIT - 1 ) ) . '…'; } $valid[ $id ] = [ 'id' => $id, 'text' => $text, 'requires' => array_values( array_unique( $requires ) ), 'priority' => isset( $prompt['priority'] ) && is_int( $prompt['priority'] ) ? $prompt['priority'] : 10, ]; } return array_values( $valid ); } /** * Prompts whose required abilities are all registered (present in the * report), sorted by priority then registration order, capped at * PROMPT_LIMIT, each with its "Uses" names. PROMPT_REQUIRES_ADAPTER is * always met. * * @param array $prompts Validated prompts. * @param array $rows Report rows. * @return array */ public static function qualifying_prompts( array $prompts, array $rows ): array { $by_id = []; foreach ( $rows as $row ) { $by_id[ $row['id'] ] = $row; } $shown = []; foreach ( array_values( $prompts ) as $order => $prompt ) { foreach ( $prompt['requires'] as $requirement ) { if ( self::PROMPT_REQUIRES_ADAPTER !== $requirement && ! isset( $by_id[ $requirement ] ) ) { continue 2; } } $prompt['uses'] = self::prompt_uses( $prompt['requires'], $by_id ); $prompt['order'] = $order; $shown[] = $prompt; } usort( $shown, static function ( array $a, array $b ): int { $by_priority = $a['priority'] <=> $b['priority']; return 0 !== $by_priority ? $by_priority : $a['order'] <=> $b['order']; } ); $shown = array_slice( $shown, 0, self::PROMPT_LIMIT ); foreach ( $shown as &$prompt ) { unset( $prompt['order'] ); } unset( $prompt ); return $shown; } /** * "Uses" names: each ability's report label, AO labels without a leading * "Get ". PROMPT_REQUIRES_ADAPTER reads as the adapter's Discover * Abilities label when that ability is registered, else "MCP Adapter". * Joined with ", ". * * @param string[] $requires Requirements. * @param array $by_id Report rows keyed by ability ID. * @return string Plain text. */ public static function prompt_uses( array $requires, array $by_id ): string { $names = []; foreach ( $requires as $requirement ) { if ( self::PROMPT_REQUIRES_ADAPTER === $requirement ) { $discover = $by_id[ self::ADAPTER_DISCOVER_ABILITY ]['label'] ?? ''; $names[] = '' !== $discover ? (string) $discover : __( 'MCP Adapter', 'admin-optimizer' ); continue; } $row = $by_id[ $requirement ] ?? null; if ( null === $row ) { $names[] = $requirement; continue; } $label = (string) $row['label']; $names[] = ! empty( $row['is_ao'] ) && 0 === strpos( $label, 'Get ' ) && strlen( $label ) > 4 ? substr( $label, 4 ) : $label; } return implode( ', ', $names ); } /** * Whether this WordPress version provides the native Abilities API. * * @return bool */ public static function is_abilities_api_supported(): bool { return function_exists( 'wp_register_ability' ) && function_exists( 'wp_get_abilities' ); } /** * Category labels keyed by slug, from core's categories API. A category * that can't be read is left out, so its abilities show their slug. * * @return array */ public static function category_labels(): array { $labels = []; if ( ! function_exists( 'wp_get_ability_categories' ) ) { return $labels; } foreach ( wp_get_ability_categories() as $category ) { try { $label = self::plain_text( $category->get_label() ); if ( '' !== $label ) { $labels[ $category->get_slug() ] = $label; } } catch ( \Throwable $e ) { continue; } } return $labels; } /** * Which MCP exposure rule applies. With the adapter loaded, its own * McpAbilityExposure helper is used (0.7.x); a loaded adapter without * it (e.g. Rank Math's bundled 0.4.1) uses 0.4.1's rule. With no adapter * loaded, the WordPress.org version's (0.7.1) rule says what would be * exposed once it is installed. * * @param string $adapter_state One of the ADAPTER_* constants. * @return string One of the MCP_RULE_* constants. */ public static function mcp_rule( string $adapter_state ): string { if ( self::ADAPTER_ACTIVE !== $adapter_state ) { return self::MCP_RULE_CURRENT; } return class_exists( self::EXPOSURE_CLASS ) && method_exists( self::EXPOSURE_CLASS, 'is_meta_public' ) ? self::MCP_RULE_ADAPTER : self::MCP_RULE_LEGACY; } /** * Whether the adapter's default MCP server exposes an ability with this * meta, under the given rule. * * 0.7.1: a non-array `meta.mcp` is not exposed; a set `meta.mcp.public` * decides; otherwise only `meta.public === true` exposes it. * 0.4.1: only a truthy `meta.mcp.public` exposes it. * * @param array $meta Ability meta from get_meta(). * @param string $rule One of the MCP_RULE_* constants. * @return bool */ public static function is_mcp_exposed( array $meta, string $rule ): bool { if ( self::MCP_RULE_ADAPTER === $rule ) { return (bool) call_user_func( [ self::EXPOSURE_CLASS, 'is_meta_public' ], $meta ); } $mcp = $meta['mcp'] ?? []; if ( ! is_array( $mcp ) ) { return false; } if ( self::MCP_RULE_LEGACY === $rule ) { return (bool) ( $mcp['public'] ?? false ); } if ( isset( $mcp['public'] ) ) { return (bool) $mcp['public']; } return true === ( $meta['public'] ?? false ); } /** * Whether an ability declares that it changes data. Only explicit * booleans count; anything else is "not declared", never read-only. * * @param mixed $annotations `meta.annotations`. * @return string One of the CHANGES_* constants. */ public static function changes_data( $annotations ): string { $annotations = is_array( $annotations ) ? $annotations : []; if ( true === ( $annotations['destructive'] ?? null ) ) { return self::CHANGES_DESTRUCTIVE; } if ( true === ( $annotations['readonly'] ?? null ) ) { return self::CHANGES_READONLY; } if ( false === ( $annotations['readonly'] ?? null ) ) { return self::CHANGES_WRITE; } return self::CHANGES_UNDECLARED; } /** * Ability text as plain text: tags stripped, entities decoded, * whitespace collapsed and, with a limit, cut near a word boundary. * * @param mixed $text Raw text. * @param int $limit Maximum characters before the ellipsis; 0 for none. * @return string */ public static function plain_text( $text, int $limit = 0 ): string { $text = html_entity_decode( wp_strip_all_tags( (string) $text ), ENT_QUOTES, 'UTF-8' ); $text = trim( (string) preg_replace( '/\s+/u', ' ', $text ) ); if ( $limit > 0 && mb_strlen( $text ) > $limit ) { $cut = mb_substr( $text, 0, $limit ); $space = mb_strrpos( $cut, ' ' ); if ( false !== $space && $space > $limit - 40 ) { $cut = mb_substr( $cut, 0, $space ); } $text = rtrim( $cut, " \t.,;:" ) . '…'; } return $text; } /** * One normalized row for one ability, read through its getters only. * Throws when the ability can't be read; build_report() counts that. * * @param object $ability Native WP_Ability. * @param array $category_labels category_labels() output. * @param string $mcp_rule One of the MCP_RULE_* constants. * @param array $tools default_server_tools(): abilities the default server lists as tools. * @return array * @throws \InvalidArgumentException When given something that isn't an ability. */ public static function normalize_ability( $ability, array $category_labels, string $mcp_rule, array $tools = [] ): array { if ( ! is_object( $ability ) ) { throw new \InvalidArgumentException( 'Not an ability.' ); } // --- 1. Identity and category --- $id = (string) $ability->get_name(); if ( '' === $id ) { throw new \InvalidArgumentException( 'Ability without a name.' ); } $category_slug = (string) $ability->get_category(); $is_ao = self::ABILITY_CATEGORY === $category_slug; $meta = $ability->get_meta(); $meta = is_array( $meta ) ? $meta : []; $annotations = isset( $meta['annotations'] ) && is_array( $meta['annotations'] ) ? $meta['annotations'] : []; // --- 2. Text: AO keeps its presentation metadata --- $label = self::plain_text( $ability->get_label() ); $module = ''; $ao_meta = $is_ao && isset( $meta['adminoptimizer'] ) && is_array( $meta['adminoptimizer'] ) ? $meta['adminoptimizer'] : []; if ( $is_ao ) { $summary = self::plain_text( $ao_meta['summary'] ?? '' ); $description = '' !== $summary ? $summary : self::plain_text( $ability->get_description() ); $module_def = isset( $ao_meta['module'] ) && is_string( $ao_meta['module'] ) ? Module_Registry::get_module( $ao_meta['module'] ) : null; $module = null !== $module_def ? (string) $module_def['name'] : ''; } else { $description = self::plain_text( $ability->get_description(), self::DESCRIPTION_LIMIT ); } // --- 3. Declared behaviour and exposure --- $rest = true === ( $meta['show_in_rest'] ?? false ); $is_tool = in_array( $id, $tools, true ); return [ 'id' => $id, 'label' => '' !== $label ? $label : $id, 'description' => $description, 'category' => $category_labels[ $category_slug ] ?? $category_slug, 'category_slug' => $category_slug, 'module' => $module, 'is_ao' => $is_ao, 'changes' => self::changes_data( $annotations ), 'contradiction' => true === ( $annotations['readonly'] ?? null ) && true === ( $annotations['destructive'] ?? null ), 'readonly' => true === ( $annotations['readonly'] ?? null ), 'rest' => $rest, 'mcp' => $is_tool || self::is_mcp_exposed( $meta, $mcp_rule ), 'adapter_tool' => $is_tool && self::ADAPTER_CATEGORY === $category_slug, ]; } /** * Normalize every ability, skipping and counting any that can't be read, * then sort for display. * * @param iterable $abilities Native WP_Ability objects. * @param array $category_labels category_labels() output. * @param string $mcp_rule One of the MCP_RULE_* constants. * @param array $tools default_server_tools(). * @return array{rows:array,unreadable:int,contradictions:int} */ public static function build_report( $abilities, array $category_labels, string $mcp_rule, array $tools = [] ): array { $rows = []; $unreadable = 0; $contradictions = 0; foreach ( $abilities as $ability ) { try { $row = self::normalize_ability( $ability, $category_labels, $mcp_rule, $tools ); } catch ( \Throwable $e ) { ++$unreadable; continue; } $contradictions += $row['contradiction'] ? 1 : 0; $rows[] = $row; } return [ 'rows' => self::sort_rows( $rows, $tools ), 'unreadable' => $unreadable, 'contradictions' => $contradictions, ]; } /** * Display order: Admin Optimizer abilities first; then the MCP Adapter's * own tools in the default server's tool order; then other abilities. * Within the Admin Optimizer and other groups, sort available * to AI assistants (MCP) first; then Destructive, Can make changes, Not * declared, Read-only; then category, then label. * * @param array $rows Normalized rows. * @param array $tools default_server_tools(), for the adapter tools' order. * @return array */ public static function sort_rows( array $rows, array $tools = [] ): array { $ao_rows = []; $adapter_tools = []; $others = []; foreach ( $rows as $row ) { if ( ! empty( $row['is_ao'] ) ) { $ao_rows[] = $row; } elseif ( ! empty( $row['adapter_tool'] ) ) { $adapter_tools[] = $row; } else { $others[] = $row; } } $position = array_flip( $tools ); usort( $adapter_tools, static function ( array $a, array $b ) use ( $position ): int { $by_position = ( $position[ $a['id'] ] ?? PHP_INT_MAX ) <=> ( $position[ $b['id'] ] ?? PHP_INT_MAX ); return 0 !== $by_position ? $by_position : strcmp( $a['id'], $b['id'] ); } ); $risk = [ self::CHANGES_DESTRUCTIVE => 0, self::CHANGES_WRITE => 1, self::CHANGES_UNDECLARED => 2, self::CHANGES_READONLY => 3, ]; $compare = static function ( array $a, array $b ) use ( $risk ): int { return ( (int) $b['mcp'] <=> (int) $a['mcp'] ) ?: ( $risk[ $a['changes'] ] <=> $risk[ $b['changes'] ] ) ?: strnatcasecmp( $a['category'], $b['category'] ) ?: strnatcasecmp( $a['label'], $b['label'] ) ?: strcmp( $a['id'], $b['id'] ); }; usort( $ao_rows, $compare ); usort( $others, $compare ); return array_merge( $ao_rows, $adapter_tools, $others ); } /** * The summary line's items, built only from normalized rows. The MCP * Adapter's own tools are left out of every count. * * @param array $rows Normalized rows. * @param int $unreadable Abilities that couldn't be read. * @param bool $mcp_live Whether the adapter's default server is running. * @return array */ public static function summary( array $rows, int $unreadable, bool $mcp_live ): array { // MCP Adapter tools are left out of every count. $rows = array_values( array_filter( $rows, static function ( array $row ): bool { return empty( $row['adapter_tool'] ); } ) ); $counts = [ 'total' => count( $rows ), 'mcp' => 0, 'changes' => 0, 'undeclared' => 0, ]; foreach ( $rows as $row ) { $counts['mcp'] += $row['mcp'] ? 1 : 0; $counts['changes'] += in_array( $row['changes'], [ self::CHANGES_DESTRUCTIVE, self::CHANGES_WRITE ], true ) ? 1 : 0; $counts['undeclared'] += self::CHANGES_UNDECLARED === $row['changes'] ? 1 : 0; } $format = static function ( string $text, int $count ): string { return sprintf( $text, number_format_i18n( $count ) ); }; $items = [ [ 'key' => 'total', 'count' => $counts['total'], /* translators: %s: number of abilities. */ 'text' => $format( _n( '%s ability on this site', '%s abilities on this site', $counts['total'], 'admin-optimizer' ), $counts['total'] ), ], [ 'key' => 'mcp', 'count' => $counts['mcp'], 'text' => $mcp_live /* translators: %s: number of abilities. */ ? $format( _n( '%s available to AI assistants', '%s available to AI assistants', $counts['mcp'], 'admin-optimizer' ), $counts['mcp'] ) /* translators: %s: number of abilities. */ : $format( _n( '%s would be available to AI assistants', '%s would be available to AI assistants', $counts['mcp'], 'admin-optimizer' ), $counts['mcp'] ), ], [ 'key' => 'changes', 'count' => $counts['changes'], /* translators: %s: number of abilities. */ 'text' => $format( _n( '%s can make changes', '%s can make changes', $counts['changes'], 'admin-optimizer' ), $counts['changes'] ), ], [ 'key' => 'undeclared', 'count' => $counts['undeclared'], /* translators: %s: number of abilities. */ 'text' => $format( _n( "%s doesn't declare whether it changes data", "%s don't declare whether they change data", $counts['undeclared'], 'admin-optimizer' ), $counts['undeclared'] ), ], ]; if ( $unreadable > 0 ) { $items[] = [ 'key' => 'unreadable', 'count' => $unreadable, /* translators: %s: number of abilities. */ 'text' => $format( _n( "%s couldn't be read", "%s couldn't be read", $unreadable, 'admin-optimizer' ), $unreadable ), ]; } return $items; } /** * Overall access level: `readonly` when every listed ability is * read-only (including when none are listed), `readwrite` otherwise. * * @param array $rows Rows from describe_abilities(). * @return string */ public static function access_level( array $rows ): string { foreach ( $rows as $row ) { if ( empty( $row['readonly'] ) ) { return 'readwrite'; } } return 'readonly'; } /** * The "only read data" strip shows only while every listed ability is * read-only, at least one is listed, and Pro is not active. * * @param array $rows Rows from describe_abilities(). * @param bool $pro_active Module_Registry::is_pro_active(). * @return bool */ public static function should_show_pro_strip( array $rows, bool $pro_active ): bool { return ! $pro_active && ! empty( $rows ) && 'readonly' === self::access_level( $rows ); } /** * Find the MCP Adapter's plugin file in a get_plugins() list. The * WordPress.org basename wins; a renamed folder (e.g. a release zip) is * matched on its main file name plus the adapter's text domain. * * @param array $plugins get_plugins() output keyed by plugin file. * @return string|null */ public static function find_adapter_plugin( array $plugins ): ?string { if ( isset( $plugins[ self::ADAPTER_PLUGIN ] ) ) { return self::ADAPTER_PLUGIN; } foreach ( $plugins as $file => $headers ) { if ( 'mcp-adapter.php' === basename( (string) $file ) && self::ADAPTER_SLUG === ( $headers['TextDomain'] ?? '' ) ) { return (string) $file; } } return null; } /** * Exactly one adapter state. A loaded adapter class counts as active, * even when another plugin bundles it as a Composer package. * * @param bool $class_loaded Whether the adapter's main class is loaded. * @param string|null $plugin_file Adapter plugin file, when installed. * @param bool $plugin_active Whether WordPress reports that file active. * @return string One of the ADAPTER_* constants. */ public static function adapter_state( bool $class_loaded, ?string $plugin_file, bool $plugin_active ): string { if ( $class_loaded || ( null !== $plugin_file && $plugin_active ) ) { return self::ADAPTER_ACTIVE; } return null !== $plugin_file ? self::ADAPTER_INACTIVE : self::ADAPTER_NOT_INSTALLED; } /** * The loaded adapter's version and whether another plugin bundles it. * The version comes from McpAdapter::VERSION; nothing is guessed. * * @param bool $plugin_active Whether the adapter's own plugin is active. * @return array{version:?string,bundled:bool,bundler:string} */ public static function adapter_info( bool $plugin_active ): array { $info = [ 'version' => null, 'bundled' => false, 'bundler' => '', ]; if ( ! class_exists( self::ADAPTER_CLASS, false ) ) { return $info; } $constant = self::ADAPTER_CLASS . '::VERSION'; if ( defined( $constant ) && is_string( constant( $constant ) ) && 1 === preg_match( '/^\d+(\.\d+)*[\w.-]*$/', constant( $constant ) ) ) { $info['version'] = constant( $constant ); } $info['bundled'] = ! $plugin_active; if ( $info['bundled'] && defined( 'WP_PLUGIN_DIR' ) ) { try { $file = ( new \ReflectionClass( self::ADAPTER_CLASS ) )->getFileName(); } catch ( \Throwable $e ) { $file = false; } if ( is_string( $file ) ) { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $info['bundler'] = self::bundling_plugin( $file, WP_PLUGIN_DIR, get_plugins() ); } } return $info; } /** * Name of the plugin whose folder contains the adapter file, only when * that is certain: the file sits inside one plugin folder that holds * exactly one plugin. Otherwise an empty string. * * @param string $adapter_file Path of the loaded adapter class file. * @param string $plugins_dir WP_PLUGIN_DIR. * @param array $plugins get_plugins() output. * @return string */ public static function bundling_plugin( string $adapter_file, string $plugins_dir, array $plugins ): string { $plugins_dir = rtrim( str_replace( '\\', '/', $plugins_dir ), '/' ) . '/'; $adapter = str_replace( '\\', '/', $adapter_file ); if ( 0 !== strpos( $adapter, $plugins_dir ) ) { return ''; } $relative = substr( $adapter, strlen( $plugins_dir ) ); $folder = strstr( $relative, '/', true ); if ( false === $folder || '' === $folder ) { return ''; } $matches = []; foreach ( $plugins as $plugin_file => $headers ) { if ( 0 === strpos( (string) $plugin_file, $folder . '/' ) ) { $matches[] = $headers; } } if ( 1 !== count( $matches ) ) { return ''; } return self::plain_text( $matches[0]['Name'] ?? '' ); } /** * Whether a known adapter version is below 0.7 (no top-level * `meta.public` support). * * @param string|null $version Loaded adapter version. * @return bool */ public static function is_pre_0_7_adapter( ?string $version ): bool { return null !== $version && version_compare( $version, '0.7', '<' ); } /** * Whether the adapter would create its default server, using the same * filter and default the adapter uses. * * @return bool */ public static function is_default_server_enabled(): bool { try { return (bool) apply_filters( 'mcp_adapter_create_default_server', true ); } catch ( \Throwable $e ) { return false; } } /** * The default MCP server's endpoint, or null when it can't be known. * * The adapter only creates its servers on `rest_api_init`, so its own * `get_server()` is empty on admin screens. The URL is instead built from * the same filters the adapter applies to its default server, without * creating a server. Returns null unless the adapter is active, when the * default server is disabled, or when the filtered config has no usable * namespace or route. * * @param string $adapter_state One of the ADAPTER_* constants. * @return string|null */ public static function resolve_endpoint( string $adapter_state ): ?string { if ( self::ADAPTER_ACTIVE !== $adapter_state ) { return null; } $config = self::default_server_config(); if ( null === $config ) { return null; } $namespace = is_string( $config['server_route_namespace'] ) ? trim( $config['server_route_namespace'], '/' ) : ''; $route = is_string( $config['server_route'] ) ? trim( $config['server_route'], '/' ) : ''; if ( '' === $namespace || '' === $route ) { return null; } return rest_url( $namespace . '/' . $route ); } /** * The default server's config as the adapter builds it, or null when the * default server is disabled or the filters throw. Mirrors * DefaultServerFactory::create() (0.4.1 and 0.7.1): a non-array result * falls back to the defaults, an array is merged over them. * * @return array|null */ public static function default_server_config(): ?array { try { if ( ! self::is_default_server_enabled() ) { return null; } $config = apply_filters( 'mcp_adapter_default_server_config', self::ADAPTER_DEFAULT_SERVER_CONFIG ); return is_array( $config ) ? array_merge( self::ADAPTER_DEFAULT_SERVER_CONFIG, $config ) : self::ADAPTER_DEFAULT_SERVER_CONFIG; } catch ( \Throwable $e ) { return null; } } /** * Ability names the default server registers as MCP tools, in order. * The adapter registers each listed ability as a tool by name, with no * `mcp.public` check, so a listed ability is reachable by AI assistants. * Empty unless the adapter is active and its default server enabled. * * @param string $adapter_state One of the ADAPTER_* constants. * @return string[] */ public static function default_server_tools( string $adapter_state ): array { if ( self::ADAPTER_ACTIVE !== $adapter_state ) { return []; } $config = self::default_server_config(); $tools = null !== $config && is_array( $config['tools'] ?? null ) ? $config['tools'] : []; return array_values( array_unique( array_filter( $tools, 'is_string' ) ) ); } /** * Render the view inside Overview's content wrapper. * * @return void */ public function render_settings_page(): void { if ( ! current_user_can( 'manage_options' ) ) { return; } $this->render( $this->get_state() ); } /** * Render markup from a get_state() result. Reads nothing else, so every * state can be rendered in tests. * * @param array $state get_state() output. * @return void */ public function render( array $state ): void { ?>

render_status( $state ); $this->render_setup( $state ); $this->render_abilities( $state ); $this->render_prompts( $state ); ?>
__( 'The MCP Adapter is active, so AI assistants can use the abilities that allow it.', 'admin-optimizer' ), self::ADAPTER_INACTIVE => __( 'The MCP Adapter is installed but inactive, so AI assistants can’t use any abilities yet.', 'admin-optimizer' ), self::ADAPTER_NOT_INSTALLED => __( 'The MCP Adapter is not installed, so AI assistants can’t use any abilities yet.', 'admin-optimizer' ), ]; $info = $state['adapter_info'] ?? []; $version_text = null; if ( $is_active && ! empty( $info['version'] ) ) { /* translators: %s: MCP Adapter version number. */ $version_text = sprintf( __( 'Version %s', 'admin-optimizer' ), $info['version'] ); } if ( $is_active && ! empty( $info['bundled'] ) ) { $bundled = '' !== ( $info['bundler'] ?? '' ) /* translators: %s: name of the plugin that bundles the MCP Adapter. */ ? sprintf( __( '(bundled by %s)', 'admin-optimizer' ), $info['bundler'] ) : __( '(bundled by another plugin)', 'admin-optimizer' ); $version_text = null === $version_text ? $bundled : $version_text . ' ' . $bundled; } $adapter_badge = [ self::ADAPTER_ACTIVE => __( 'Active', 'admin-optimizer' ), self::ADAPTER_INACTIVE => __( 'Installed, inactive', 'admin-optimizer' ), self::ADAPTER_NOT_INSTALLED => __( 'Not installed', 'admin-optimizer' ), ]; ?>

  1. render_marker( $count > 0 ); ?>

    0 ) { echo esc_html( sprintf( /* translators: 1: number of abilities on the site, 2: number of them from Admin Optimizer. */ _n( '%1$s ability registered on this site, %2$s from Admin Optimizer.', '%1$s abilities registered on this site, %2$s from Admin Optimizer.', $count, 'admin-optimizer' ), number_format_i18n( $count ), number_format_i18n( $ao_count ) ) ); } else { esc_html_e( 'No abilities registered on this site.', 'admin-optimizer' ); } if ( $tool_count > 0 ) { echo ' ' . esc_html( sprintf( /* translators: %s: number of MCP Adapter tools. */ _n( 'The MCP Adapter adds %s tool for AI assistants.', 'The MCP Adapter adds %s tools for AI assistants.', $tool_count, 'admin-optimizer' ), number_format_i18n( $tool_count ) ) ); } ?>

  2. render_marker( $is_active && ! $server_off ); ?>

  1. render_marker( true ); ?>

  2. render_install_button(); ?>

  3. ' . esc_html__( 'Users', 'admin-optimizer' ) . '', '' . esc_html__( 'Profile', 'admin-optimizer' ) . '', '' . esc_html__( 'Application Passwords', 'admin-optimizer' ) . '' ), [ 'strong' => [] ] ); ?>

    ' . esc_html__( 'Tip:', 'admin-optimizer' ) . '', '' . esc_html__( 'Last used', 'admin-optimizer' ) . '' ), [ 'strong' => [] ] ); ?>

  4. $client ) : ?>
    $client ) : ?>
    >

'search', 'type' => 'term', 's' => 'MCP Adapter', ], self_admin_url( 'plugin-install.php' ) ); ?>

' . esc_html__( 'AI assistant', 'admin-optimizer' ) . ' ' . esc_html__( '(not available yet)', 'admin-optimizer' ) . ''; } // $assistant is built from escaped strings only. if ( $rest && $mcp ) { /* translators: %s: "AI assistant", possibly marked as not available yet. */ echo sprintf( esc_html__( 'REST API and %s', 'admin-optimizer' ), $assistant ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } elseif ( $mcp ) { echo $assistant; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } elseif ( $rest ) { esc_html_e( 'REST API', 'admin-optimizer' ); } else { esc_html_e( 'WordPress only', 'admin-optimizer' ); } } /** * Site-wide abilities report: summary line, filters, table, notes and * empty states, then AO's own Pro strip. Rows carry their filter values * in data- attributes; the script only shows and hides them. * * @param array $state get_state() output. * @return void */ private function render_abilities( array $state ): void { $rows = $state['report']['rows']; $unreadable = (int) $state['report']['unreadable']; $mcp_live = ! empty( $state['mcp_live'] ); $total = count( $rows ); // The adapter's own tools get their own group above the rest. $adapter_tools = []; $other_rows = []; foreach ( $rows as $row ) { if ( ! empty( $row['adapter_tool'] ) ) { $adapter_tools[] = $row; } else { $other_rows[] = $row; } } $categories = []; foreach ( $rows as $row ) { $categories[ $row['category_slug'] ]['label'] = $row['category']; $categories[ $row['category_slug'] ]['count'] = ( $categories[ $row['category_slug'] ]['count'] ?? 0 ) + 1; } uasort( $categories, static function ( array $a, array $b ): int { return strnatcasecmp( $a['label'], $b['label'] ); } ); ?>

render_row( $row, $mcp_live ); } ?> render_row( $row, $mcp_live ); } ?>

' . esc_html( $state['rest_run_url'] ) . '' ); ?>

[ 'is-destructive', __( 'Destructive', 'admin-optimizer' ) ], self::CHANGES_WRITE => [ 'is-readwrite', __( 'Can make changes', 'admin-optimizer' ) ], self::CHANGES_UNDECLARED => [ 'is-undeclared', __( 'Not declared', 'admin-optimizer' ) ], self::CHANGES_READONLY => [ 'is-readonly', __( 'Read-only', 'admin-optimizer' ) ], ]; $badge = $changes_badges[ $row['changes'] ] ?? $changes_badges[ self::CHANGES_UNDECLARED ]; $can_change = in_array( $row['changes'], [ self::CHANGES_DESTRUCTIVE, self::CHANGES_WRITE ], true ); $search = function_exists( 'mb_strtolower' ) ? mb_strtolower( $row['label'] . ' ' . $row['id'] . ' ' . $row['description'] ) : strtolower( $row['label'] . ' ' . $row['id'] . ' ' . $row['description'] ); ?> $segment ) { echo '' . esc_html( $segment . ( $i < $last ? '/' : '' ) ) . '' . ( $i < $last ? '' : '' ); } ?> render_reach( $row['rest'], $row['mcp'], $mcp_live ); ?>