WP_REST_Server::READABLE, 'callback' => array( __CLASS__, 'get_manifest' ), 'permission_callback' => array( __CLASS__, 'check_access' ), ) ); register_rest_route( $ns, '/tools', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( __CLASS__, 'get_tools' ), 'permission_callback' => array( __CLASS__, 'check_access' ), ) ); register_rest_route( $ns, '/call/(?P[a-zA-Z0-9_\-]+)', array( 'methods' => array( WP_REST_Server::CREATABLE, WP_REST_Server::READABLE ), 'callback' => array( __CLASS__, 'call_tool' ), 'permission_callback' => array( __CLASS__, 'check_access' ), 'args' => array( 'tool' => array( 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } } /** * Permission gate for all MCP REST routes. * * Anonymous agent access stays open by default (that is the product); * when the site owner enables "Require API key" in Settings, callers must * present a valid key via the X-WebMCP-Key header or the api_key parameter. * * @param WP_REST_Request $request Incoming REST request. * @return true|WP_Error */ public static function check_access( $request ) { if ( current_user_can( 'manage_options' ) ) { return true; } if ( ! (bool) get_option( 'aeolynx_require_api_key', 0 ) ) { return true; } $provided = ''; foreach ( array( 'X-WebMCP-Key', 'X-AEOLynx-Key' ) as $header_name ) { $header = $request->get_header( $header_name ); if ( is_string( $header ) && '' !== trim( $header ) ) { $provided = trim( $header ); break; } } if ( '' === $provided ) { $auth_header = $request->get_header( 'Authorization' ); if ( is_string( $auth_header ) && preg_match( '/^\s*Bearer\s+(\S+)\s*$/i', $auth_header, $m ) ) { $provided = trim( $m[1] ); } } if ( '' !== $provided && self::verify_api_key( $provided ) ) { return true; } return new WP_Error( 'aeolynx_forbidden', __( 'This gateway requires a valid API key. Send it via the X-WebMCP-Key (or X-AEOLynx-Key / Authorization: Bearer) HTTP header.', 'aeolynx-for-webmcp' ), array( 'status' => 401 ) ); } /** * Return the stored API key records (hashes only — raw keys are never persisted). * * @return array */ public static function get_api_keys() { $keys = get_option( 'aeolynx_api_keys', array() ); return is_array( $keys ) ? $keys : array(); } /** * Hash-compare a provided raw key against the stored key hashes. * * @param string $raw_key Raw key from the request. * @return bool */ public static function verify_api_key( $raw_key ) { $hash = hash( 'sha256', (string) $raw_key ); foreach ( self::get_api_keys() as $record ) { if ( isset( $record['hash'] ) && hash_equals( (string) $record['hash'], $hash ) ) { return true; } } return false; } /** * Generate a new API key, persist only its SHA-256 hash, and return the raw key once. * * @param string $label Admin-friendly label. * @return string|WP_Error Raw key on success. */ public static function generate_api_key( $label = '' ) { $raw = 'wmc_' . wp_generate_password( 40, false, false ); $keys = self::get_api_keys(); if ( count( $keys ) >= 20 ) { return new WP_Error( 'aeolynx_key_limit', __( 'Maximum of 20 API keys reached. Revoke an unused key first.', 'aeolynx-for-webmcp' ) ); } $keys[] = array( 'hash' => hash( 'sha256', $raw ), 'label' => sanitize_text_field( (string) $label ), 'created' => time(), ); if ( ! update_option( 'aeolynx_api_keys', $keys, false ) ) { return new WP_Error( 'aeolynx_key_save_failed', __( 'Could not save the new API key.', 'aeolynx-for-webmcp' ) ); } return $raw; } /** * Revoke one stored key by its hash. * * @param string $hash SHA-256 hash of the key to remove. * @return bool */ public static function revoke_api_key( $hash ) { $hash = (string) $hash; $keys = self::get_api_keys(); $kept = array_values( array_filter( $keys, static function ( $record ) use ( $hash ) { return ! isset( $record['hash'] ) || ! hash_equals( (string) $record['hash'], $hash ); } ) ); $changed = count( $kept ) !== count( $keys ); if ( $changed ) { update_option( 'aeolynx_api_keys', $kept, false ); } return $changed; } /** * Return the full WebMCP manifest via REST. * * @return WP_REST_Response */ public static function get_manifest() { $manifest = AEOLynx_Schema_Builder::build( 'homepage', 0 ); return rest_ensure_response( $manifest ); } /** * Return the registered read tools list via REST. * * @return WP_REST_Response */ public static function get_tools() { $tools = AEOLynx_Schema_Builder::get_core_tools( 0 ); $tools = (array) apply_filters( 'aeolynx_register_tools', $tools, 'homepage', 0 ); return rest_ensure_response( array( 'tools' => array_values( $tools ) ) ); } /** * Per-IP fixed-window rate limit for public agent calls. * * Two independent caps are enforced: a per-minute limit (the "Public rate * limit" setting) and a per-hour burst cap, so a flood that straddles a * window boundary still gets stopped. Counters are atomic increments on * persistent storage — they survive cache-plugin purges, work behind * load balancers, and cannot be overrun by parallel requests. * * @return true|WP_Error */ /** * Resolve client IP safely: defaults to REMOTE_ADDR; only honors X-Forwarded-For / * CF-Connecting-IP when REMOTE_ADDR is explicitly listed in `aeolynx_trusted_proxies`, * and remains filterable via `aeolynx_client_ip` (BUG-010). * * @return string */ public static function get_client_ip() { $remote = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown'; $ip = $remote; /** * List of trusted reverse-proxy IPs whose forwarded headers may be honored. * * @param array $proxies Trusted proxy IP addresses. */ $trusted = (array) apply_filters( 'aeolynx_trusted_proxies', array() ); if ( ! empty( $trusted ) && in_array( $remote, $trusted, true ) ) { $candidates = array(); if ( ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) { $candidates[] = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ); } if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { $xff = explode( ',', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ); if ( ! empty( $xff[0] ) ) { $candidates[] = trim( $xff[0] ); } } foreach ( $candidates as $cand ) { if ( false !== filter_var( $cand, FILTER_VALIDATE_IP ) ) { $ip = $cand; break; } } } return (string) apply_filters( 'aeolynx_client_ip', $ip, $remote ); } private static function check_rate_limit() { if ( current_user_can( 'manage_options' ) ) { return true; } $minute_limit = max( 10, absint( get_option( 'aeolynx_rate_limit', 60 ) ) ); $hourly_limit = max( 50, absint( apply_filters( 'aeolynx_hourly_rate_limit', $minute_limit * 20 ) ) ); $now = time(); $ip = self::get_client_ip(); $identity = md5( $ip ); $minute_ok = self::bump_rate_window( 'aeolynx_rl_m_' . $identity, $minute_limit, MINUTE_IN_SECONDS, $now, 'aeolynx_rate_limited' ); if ( is_wp_error( $minute_ok ) ) { return $minute_ok; } $hourly_ok = self::bump_rate_window( 'aeolynx_rl_h_' . $identity, $hourly_limit, HOUR_IN_SECONDS, $now, 'aeolynx_rate_limited_hourly' ); if ( is_wp_error( $hourly_ok ) ) { return $hourly_ok; } return true; } /** * Atomically bump one fixed-window counter and enforce its cap. * * Counter rows are named "_" so the window * identity lives in the name: the value is a plain integer that a single * INSERT ... ON DUPLICATE KEY UPDATE statement can increment atomically, * and expired windows are simply rows that are no longer addressed. * * @param string $counter_key Stable counter base name. * @param int $limit Maximum hits allowed inside the window. * @param int $window Window length in seconds. * @param int $now Current timestamp. * @param string $error_code WP_Error code for the 429 response. * @return true|WP_Error */ private static function bump_rate_window( $counter_key, $limit, $window, $now, $error_code ) { $window_start = $now - ( $now % $window ); if ( wp_using_ext_object_cache() ) { $count = wp_cache_incr( $counter_key . '_' . $window_start, 1, 'aeolynx_rl' ); if ( false === $count || 1 === (int) $count ) { // Key was absent: seed it and (re)arm its expiry. wp_cache_set( $counter_key . '_' . $window_start, 1, 'aeolynx_rl', $window + 60 ); $count = 1; } } else { $count = self::sql_bump_window_counter( $counter_key . '_' . $window_start, $now ); } if ( (int) $count > (int) $limit ) { $wait = max( 1, (int) ( ( $window_start + $window ) - $now ) ); return new WP_Error( $error_code, sprintf( /* translators: %d: Seconds until the counter resets */ __( 'Rate limit exceeded for Model Context Protocol requests. Retry in about %d seconds.', 'aeolynx-for-webmcp' ), $wait ), array( 'status' => 429, 'retry_after' => $wait, ) ); } return true; } /** * Atomic per-row counter on the options table (no object cache present). * * One INSERT ... ON DUPLICATE KEY UPDATE statement per hit: single-statement * atomic at the SQL level, persisted in the shared DB so it survives cache * purges and counts correctly across load-balanced web nodes. * * @param string $option_name Full counter option name. * @param int $now Current timestamp (used for opportunistic cleanup). * @return int Post-increment count. */ private static function sql_bump_window_counter( $option_name, $now ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single-statement atomic upsert; caching would defeat the counter. $wpdb->query( $wpdb->prepare( "INSERT INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, 1, 'no' ) " . 'ON DUPLICATE KEY UPDATE option_value = option_value + 1', $option_name ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static identifier, value interpolated through prepare above. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-back of the atomic counter written above. $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option_name ) ); $count = ( $row && is_numeric( $row->option_value ) ) ? (int) $row->option_value : 1; // Occasionally sweep counters from expired windows (about 1% of hits). if ( 0 === wp_rand( 0, 99 ) ) { self::sql_sweep_window_counters( $now ); } return $count; } /** * Delete counter rows whose aligned window started before the cutoff. * * Window identity is the trailing "_" of the option name * (the md5 segment contains no underscores), so the sweep is a single * indexed-prefix DELETE. * * @param int $now Current timestamp. * @return void */ public static function sql_sweep_window_counters( $now ) { global $wpdb; $cutoff = (int) $now - 2 * HOUR_IN_SECONDS; $like = $wpdb->esc_like( 'aeolynx_rl_' ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Portable prefix scan avoiding MySQL-only SUBSTRING_INDEX. $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT 250", $like ) ); if ( ! is_array( $names ) || empty( $names ) ) { return; } $expired = array(); foreach ( $names as $name ) { $pos = strrpos( (string) $name, '_' ); if ( false === $pos ) { continue; } $ts = substr( (string) $name, $pos + 1 ); if ( ctype_digit( $ts ) && (int) $ts < $cutoff ) { $expired[] = (string) $name; } } if ( empty( $expired ) ) { return; } $placeholders = implode( ', ', array_fill( 0, count( $expired ), '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Dynamic placeholder list matches $expired exactly. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name IN ( {$placeholders} )", $expired ) ); } /** * Post types the searchSite tool covers: post/page, product when present, * plus every public CPT registered as searchable. Filterable via * `aeolynx_supported_post_types`. * * @return array */ private static function get_searchable_post_types() { $types = array( 'post', 'page' ); if ( post_type_exists( 'product' ) ) { $types[] = 'product'; } $cpt_types = get_post_types( array( 'public' => true, 'exclude_from_search' => false, ), 'names' ); if ( is_array( $cpt_types ) ) { foreach ( $cpt_types as $cpt ) { if ( ! in_array( $cpt, $types, true ) && 'attachment' !== $cpt ) { $types[] = $cpt; } } } return array_values( array_unique( (array) apply_filters( 'aeolynx_supported_post_types', $types ) ) ); } /** * Whether the requested tool is one of the 6 built-in tools. * * @param string $tool Lowercased tool identifier. * @return bool */ private static function is_builtin_tool( $tool ) { return in_array( $tool, array( 'getsiteinfo', 'searchsite', 'getfeaturedcontent', 'getpostcontent', 'getsitetaxonomies', 'getcatalogitems' ), true ); } /** * Allowed-parameter specification for each built-in MCP tool. * * Types: text (sanitize_text_field), key (sanitize_key + allowlist), * title (sanitize_title), url (esc_url_raw), int (clamped absint). * Anything not listed is dropped — unknown parameters never reach handlers. * * @param string $tool Lowercased tool identifier. * @return array}> */ private static function get_tool_spec( $tool ) { $text = array( 'type' => 'text', 'max' => 200, ); switch ( $tool ) { case 'searchsite': return array( 'query' => $text, 'limit' => array( 'type' => 'int', 'min' => 1, 'max' => 10, ), 'post_type' => array( 'type' => 'key', 'allowed' => self::get_searchable_post_types(), ), ); case 'getfeaturedcontent': return array( 'limit' => array( 'type' => 'int', 'min' => 1, 'max' => 10, ), 'category' => array( 'type' => 'title', 'max' => 100, ), ); case 'getpostcontent': return array( 'post_id' => array( 'type' => 'int', 'min' => 1, 'max' => 2147483647, ), 'slug' => array( 'type' => 'title', 'max' => 200, ), 'url' => array( 'type' => 'url', 'max' => 2048, ), ); case 'getsitetaxonomies': return array( 'limit' => array( 'type' => 'int', 'min' => 1, 'max' => 25, ), ); case 'getcatalogitems': return array( 'limit' => array( 'type' => 'int', 'min' => 1, 'max' => 10, ), 'query' => $text, ); default: // getSiteInfo takes no parameters. return array(); } } /** * Reduce incoming tool parameters to the tool's allowlisted, sanitized set. * * Invalid values (wrong scalar type, disallowed enum) are dropped, not * coerced, so handlers fall back to their documented defaults. * * @param string $tool Lowercased tool identifier. * @param array $params Merged request parameters. * @return array */ public static function sanitize_tool_params( $tool, $params ) { $spec = self::get_tool_spec( $tool ); $clean = array(); foreach ( $spec as $name => $rule ) { if ( ! isset( $params[ $name ] ) ) { continue; } $value = $params[ $name ]; switch ( $rule['type'] ) { case 'int': if ( ! is_numeric( $value ) ) { continue 2; } $value = (int) $value; if ( $value < $rule['min'] ) { $value = $rule['min']; } if ( $value > $rule['max'] ) { $value = $rule['max']; } $clean[ $name ] = $value; break; case 'text': if ( ! is_string( $value ) ) { continue 2; } $clean[ $name ] = mb_substr( sanitize_text_field( $value ), 0, $rule['max'] ); break; case 'title': if ( ! is_string( $value ) ) { continue 2; } $clean[ $name ] = mb_substr( sanitize_title( $value ), 0, $rule['max'] ); break; case 'key': $value = sanitize_key( is_string( $value ) ? $value : '' ); if ( '' === $value || ! in_array( $value, $rule['allowed'], true ) ) { continue 2; } $clean[ $name ] = $value; break; case 'url': if ( ! is_string( $value ) ) { continue 2; } $clean[ $name ] = mb_substr( esc_url_raw( $value ), 0, $rule['max'] ); break; } } return $clean; } /** * Whether a merged parameter set exceeds the 4 KB request budget. * * @param array $params Merged request parameters. * @return bool */ public static function payload_too_large( $params ) { return strlen( (string) wp_json_encode( $params ) ) > 4096; } /** * Execute one of the 6 built-in MCP tools (or a developer-registered custom tool). * * Built-in tool parameters are reduced to a per-tool allowlist and sanitized * centrally; the whole merged payload is capped at 4 KB (HTTP 413 above it). * Custom tools resolved through the `aeolynx_call_tool` filter receive * the size-capped (but otherwise raw) parameters — validating those is the * filter callback's responsibility. * * @param WP_REST_Request $request Incoming REST request. * @return WP_REST_Response|WP_Error */ public static function call_tool( $request ) { if ( ! AEOLynx_Frontend::is_enabled() ) { return new WP_Error( 'aeolynx_disabled', __( 'The AEOLynx for WebMCP is currently disabled by the site administrator.', 'aeolynx-for-webmcp' ), array( 'status' => 503 ) ); } $rate_ok = self::check_rate_limit(); if ( is_wp_error( $rate_ok ) ) { $err_data = (array) $rate_ok->get_error_data(); $retry_after = isset( $err_data['retry_after'] ) ? max( 1, (int) $err_data['retry_after'] ) : 60; $resp = new WP_REST_Response( array( 'code' => $rate_ok->get_error_code(), 'message' => $rate_ok->get_error_message(), 'data' => array( 'status' => 429, 'retry_after' => $retry_after, ), ), 429 ); $resp->header( 'Retry-After', (string) $retry_after ); return $resp; } $tool = trim( (string) $request->get_param( 'tool' ) ); $tool_lc = strtolower( $tool ); $json_params = $request->get_json_params(); $params = is_array( $json_params ) ? $json_params : array(); // MCP-spec clients nest tool arguments under "arguments"; the flat form stays supported. if ( isset( $params['arguments'] ) && is_array( $params['arguments'] ) ) { $params = array_merge( $params, $params['arguments'] ); } foreach ( array( 'query', 'limit', 'post_type', 'category', 'post_id', 'slug', 'url' ) as $param_key ) { if ( ! isset( $params[ $param_key ] ) && null !== $request->get_param( $param_key ) ) { $params[ $param_key ] = $request->get_param( $param_key ); } } if ( self::payload_too_large( $params ) ) { return new WP_Error( 'aeolynx_payload_too_large', __( 'The tool call payload exceeds the 4 KB limit.', 'aeolynx-for-webmcp' ), array( 'status' => 413 ) ); } if ( self::is_builtin_tool( $tool_lc ) ) { $params = self::sanitize_tool_params( $tool_lc, $params ); } switch ( $tool_lc ) { case 'getsiteinfo': AEOLynx_Activity_Log::record_event( 'tool_call', 'MCP Tool: getSiteInfo', home_url( '/' ), __( 'Returned site title, language, categories & AEO status', 'aeolynx-for-webmcp' ) ); return self::handle_get_site_info(); case 'searchsite': $q_log = isset( $params['query'] ) ? sanitize_text_field( (string) $params['query'] ) : ''; AEOLynx_Activity_Log::record_event( 'tool_call', 'MCP Tool: searchSite', 'query="' . $q_log . '"', __( 'Executed semantic keyword search across published content', 'aeolynx-for-webmcp' ) ); return self::handle_search_site( $params ); case 'getfeaturedcontent': AEOLynx_Activity_Log::record_event( 'tool_call', 'MCP Tool: getFeaturedContent', 'recent_posts', __( 'Returned latest headlines, summaries & reading times', 'aeolynx-for-webmcp' ) ); return self::handle_get_featured_content( $params ); case 'getpostcontent': $pid_log = isset( $params['post_id'] ) ? absint( $params['post_id'] ) : 0; AEOLynx_Activity_Log::record_event( 'tool_call', 'MCP Tool: getPostContent', 'post_id=' . $pid_log, __( 'Extracted clean Markdown, AI summary & FAQs for post', 'aeolynx-for-webmcp' ) ); return self::handle_get_post_content( $params ); case 'getsitetaxonomies': AEOLynx_Activity_Log::record_event( 'tool_call', 'MCP Tool: getSiteTaxonomies', 'categories & tags', __( 'Returned topical category & tag hierarchy', 'aeolynx-for-webmcp' ) ); return self::handle_get_site_taxonomies( $params ); case 'getcatalogitems': AEOLynx_Activity_Log::record_event( 'tool_call', 'MCP Tool: getCatalogItems', 'catalog / products', __( 'Returned catalog / product items with pricing & availability', 'aeolynx-for-webmcp' ) ); return self::handle_get_catalog_items( $params ); default: $custom_result = apply_filters( 'aeolynx_call_tool', null, $tool, $params, $request ); if ( null !== $custom_result ) { if ( is_wp_error( $custom_result ) ) { return $custom_result; } return rest_ensure_response( $custom_result ); } return new WP_Error( 'unknown_tool', sprintf( /* translators: %s: Tool identifier */ __( 'Tool "%s" is not registered on this gateway.', 'aeolynx-for-webmcp' ), esc_html( $tool ) ), array( 'status' => 404 ) ); } } /** * Tool 1: getSiteInfo * * @return WP_REST_Response */ private static function handle_get_site_info() { $theme = wp_get_theme(); $post_count = wp_count_posts( 'post' ); $page_count = wp_count_posts( 'page' ); $cats = get_categories( array( 'orderby' => 'count', 'order' => 'DESC', 'number' => 8, 'hide_empty' => true, ) ); $categories = array(); if ( is_array( $cats ) ) { foreach ( $cats as $c ) { $categories[] = array( 'name' => $c->name, 'slug' => $c->slug, 'count' => (int) $c->count, 'url' => get_category_link( $c->term_id ), ); } } return rest_ensure_response( array( 'tool' => 'getSiteInfo', 'protocol' => 'model-context-protocol/1.0', 'name' => (string) get_bloginfo( 'name' ), 'description' => (string) get_bloginfo( 'description' ), 'url' => home_url( '/' ), 'language' => get_bloginfo( 'language' ), 'timezone' => wp_timezone_string(), 'active_theme' => $theme instanceof WP_Theme ? (string) $theme->get( 'Name' ) : '', 'counts' => array( 'published_posts' => isset( $post_count->publish ) ? (int) $post_count->publish : 0, 'published_pages' => isset( $page_count->publish ) ? (int) $page_count->publish : 0, ), 'top_categories' => $categories, 'aeo_capabilities' => array( 'schema_graph' => (bool) get_option( 'aeolynx_schema_enabled', 1 ), 'speakable_spec' => (bool) get_option( 'aeolynx_speakable_enabled', 1 ), 'auto_faq' => (bool) get_option( 'aeolynx_auto_faq_enabled', 1 ), 'markdown_stream'=> (bool) get_option( 'aeolynx_markdown_enabled', 1 ), 'llms_txt' => home_url( '/llms.txt' ), 'well_known_mcp' => home_url( '/.well-known/mcp.json' ), ), ) ); } /** * Tool 2: searchSite * * @param array $params Tool arguments. * @return WP_REST_Response|WP_Error */ private static function handle_search_site( $params ) { $query = isset( $params['query'] ) ? sanitize_text_field( (string) $params['query'] ) : ''; $limit = isset( $params['limit'] ) ? min( 10, max( 1, absint( $params['limit'] ) ) ) : 5; $post_type = isset( $params['post_type'] ) ? sanitize_key( (string) $params['post_type'] ) : 'any'; if ( '' === $query ) { return new WP_Error( 'missing_query', __( 'A non-empty "query" parameter is required for searchSite.', 'aeolynx-for-webmcp' ), array( 'status' => 400 ) ); } $allowed_types = self::get_searchable_post_types(); if ( in_array( $post_type, $allowed_types, true ) ) { $allowed_types = array( $post_type ); } $posts = get_posts( array( 's' => $query, 'posts_per_page' => $limit, 'post_type' => $allowed_types, 'post_status' => 'publish', 'has_password' => false, ) ); $posts = array_values( array_filter( $posts, array( 'AEOLynx_Frontend', 'is_public_post' ) ) ); $fallback_used = false; if ( empty( $posts ) ) { $posts = get_posts( array( 'posts_per_page' => $limit, 'post_type' => $allowed_types, 'post_status' => 'publish', 'has_password' => false, ) ); $posts = array_values( array_filter( $posts, array( 'AEOLynx_Frontend', 'is_public_post' ) ) ); $fallback_used = true; } $results = array(); foreach ( $posts as $p ) { $ai_summary = AEOLynx_Activity_Log::get_effective_ai_summary( $p ); $permalink = get_permalink( $p ); $results[] = array( 'id' => (int) $p->ID, 'type' => (string) $p->post_type, 'title' => get_the_title( $p ), 'url' => $permalink, 'markdown_url' => add_query_arg( 'format', 'markdown', $permalink ), 'date' => get_the_date( 'Y-m-d', $p ), 'author' => get_the_author_meta( 'display_name', $p->post_author ), 'ai_summary' => $ai_summary, ); } return rest_ensure_response( array( 'tool' => 'searchSite', 'query' => $query, 'total' => count( $results ), 'fallback_used' => $fallback_used, 'results' => $results, ) ); } /** * Tool 3: getFeaturedContent * * @param array $params Tool arguments. * @return WP_REST_Response */ private static function handle_get_featured_content( $params ) { $limit = isset( $params['limit'] ) ? min( 10, max( 1, absint( $params['limit'] ) ) ) : 5; $category = isset( $params['category'] ) ? sanitize_title( (string) $params['category'] ) : ''; $query_args = array( 'posts_per_page' => $limit, 'post_type' => 'post', 'post_status' => 'publish', 'has_password' => false, ); if ( '' !== $category ) { $query_args['category_name'] = $category; } $posts = array_values( array_filter( get_posts( $query_args ), array( 'AEOLynx_Frontend', 'is_public_post' ) ) ); $list = array(); foreach ( $posts as $p ) { $words = aeolynx_word_count( wp_strip_all_tags( $p->post_content ) ); $read_mins = max( 1, (int) ceil( $words / 200 ) ); $ai_summary = AEOLynx_Activity_Log::get_effective_ai_summary( $p ); $permalink = get_permalink( $p ); $cats = get_the_category( $p->ID ); $cat_names = array(); if ( is_array( $cats ) ) { foreach ( $cats as $c ) { $cat_names[] = $c->name; } } $list[] = array( 'id' => (int) $p->ID, 'title' => get_the_title( $p ), 'url' => $permalink, 'markdown_url' => add_query_arg( 'format', 'markdown', $permalink ), 'date' => get_the_date( 'Y-m-d', $p ), 'modified' => get_the_modified_date( 'Y-m-d', $p ), 'author' => get_the_author_meta( 'display_name', $p->post_author ), 'categories' => $cat_names, 'reading_time_mins' => $read_mins, 'summary' => $ai_summary, ); } return rest_ensure_response( array( 'tool' => 'getFeaturedContent', 'count' => count( $list ), 'featured' => $list, ) ); } /** * Tool 4: getPostContent * * @param array $params Tool arguments. * @return WP_REST_Response|WP_Error */ private static function handle_get_post_content( $params ) { $post_id = isset( $params['post_id'] ) ? absint( $params['post_id'] ) : 0; $slug = isset( $params['slug'] ) ? sanitize_title( (string) $params['slug'] ) : ''; $url = isset( $params['url'] ) ? esc_url_raw( (string) $params['url'] ) : ''; if ( $post_id <= 0 && '' !== $url ) { $post_id = url_to_postid( $url ); } $post = null; if ( $post_id > 0 ) { $post = get_post( $post_id ); } elseif ( '' !== $url ) { // Explicit URL did not resolve to any local post: return 404 (BUG-033). $post = null; } elseif ( '' !== $slug ) { $found = get_posts( array( 'name' => $slug, 'post_type' => self::get_searchable_post_types(), 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => 1, ) ); if ( ! empty( $found[0] ) ) { $post = $found[0]; } } else { $recent = get_posts( array( 'post_type' => array( 'post', 'page' ), 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => 1, ) ); if ( ! empty( $recent[0] ) ) { $post = $recent[0]; } } if ( ! AEOLynx_Frontend::is_public_post( $post ) ) { return new WP_Error( 'post_not_found', __( 'Requested post or page was not found or is not publicly published.', 'aeolynx-for-webmcp' ), array( 'status' => 404 ) ); } $ai_summary = AEOLynx_Activity_Log::get_effective_ai_summary( $post ); $faqs = get_post_meta( $post->ID, '_aeolynx_faq_items', true ); if ( ( ! is_array( $faqs ) || empty( $faqs ) ) && (bool) get_option( 'aeolynx_auto_faq_enabled', 1 ) ) { $faqs = AEOLynx_Activity_Log::extract_auto_faqs_from_html( $post->post_content ); } $clean_md = AEOLynx_Markdown::convert_html_to_markdown( $post->post_content ); $permalink = get_permalink( $post ); return rest_ensure_response( array( 'tool' => 'getPostContent', 'id' => (int) $post->ID, 'type' => (string) $post->post_type, 'title' => get_the_title( $post ), 'url' => $permalink, 'markdown_url' => add_query_arg( 'format', 'markdown', $permalink ), 'author' => get_the_author_meta( 'display_name', $post->post_author ), 'date' => get_the_date( 'c', $post ), 'modified' => get_the_modified_date( 'c', $post ), 'word_count' => aeolynx_word_count( wp_strip_all_tags( $post->post_content ) ), 'ai_summary' => $ai_summary, 'faqs' => is_array( $faqs ) ? array_values( array_filter( $faqs, static function ( $item ) { $a = isset( $item['a'] ) ? (string) $item['a'] : ''; $q = isset( $item['q'] ) ? trim( (string) $item['q'] ) : ''; return '' !== $q && AEOLynx_Schema_Graph::is_publishable_faq_answer( $a ); } ) ) : array(), 'content_md' => $clean_md, 'content_text' => wp_strip_all_tags( $post->post_content ), ) ); } /** * Tool 5: getSiteTaxonomies * * @param array $params Tool arguments. * @return WP_REST_Response */ private static function handle_get_site_taxonomies( $params ) { $limit = isset( $params['limit'] ) ? min( 25, max( 1, absint( $params['limit'] ) ) ) : 10; $cats = get_categories( array( 'orderby' => 'count', 'order' => 'DESC', 'number' => $limit, 'hide_empty' => false, ) ); $cat_list = array(); if ( is_array( $cats ) ) { foreach ( $cats as $c ) { $cat_list[] = array( 'id' => (int) $c->term_id, 'name' => $c->name, 'slug' => $c->slug, 'description' => $c->description, 'count' => (int) $c->count, 'url' => get_category_link( $c->term_id ), ); } } $tags = get_tags( array( 'orderby' => 'count', 'order' => 'DESC', 'number' => $limit, 'hide_empty' => false, ) ); $tag_list = array(); if ( is_array( $tags ) ) { foreach ( $tags as $t ) { $tag_list[] = array( 'id' => (int) $t->term_id, 'name' => $t->name, 'slug' => $t->slug, 'count' => (int) $t->count, 'url' => get_tag_link( $t->term_id ), ); } } return rest_ensure_response( array( 'tool' => 'getSiteTaxonomies', 'categories' => $cat_list, 'tags' => $tag_list, ) ); } /** * Tool 6: getCatalogItems (WooCommerce Products or Site Catalog Items) * * @param array $params Tool arguments. * @return WP_REST_Response */ private static function handle_get_catalog_items( $params ) { $limit = isset( $params['limit'] ) ? min( 10, max( 1, absint( $params['limit'] ) ) ) : 5; $query = isset( $params['query'] ) ? sanitize_text_field( (string) $params['query'] ) : ''; $has_woo = post_type_exists( 'product' ); $post_type = $has_woo ? 'product' : array( 'post', 'page' ); $args = array( 'post_type' => $post_type, 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => $limit, ); if ( '' !== $query ) { $args['s'] = $query; } $items = array_values( array_filter( get_posts( $args ), array( 'AEOLynx_Frontend', 'is_public_post' ) ) ); $list = array(); foreach ( $items as $item ) { $entry = array( 'id' => (int) $item->ID, 'type' => (string) $item->post_type, 'title' => get_the_title( $item ), 'url' => get_permalink( $item ), 'summary' => AEOLynx_Activity_Log::get_effective_ai_summary( $item ), ); if ( 'product' === $item->post_type ) { $entry['sku'] = (string) get_post_meta( $item->ID, '_sku', true ); $entry['price'] = (string) get_post_meta( $item->ID, '_price', true ); $entry['currency'] = function_exists( 'get_woocommerce_currency' ) ? (string) get_woocommerce_currency() : 'USD'; $entry['stock_status'] = (string) get_post_meta( $item->ID, '_stock_status', true ); } $list[] = $entry; } $response = array( 'tool' => 'getCatalogItems', 'woocommerce' => $has_woo, 'catalog_available' => $has_woo, 'count' => count( $list ), 'items' => $list, ); if ( ! $has_woo ) { $response['reason'] = 'woocommerce-not-active'; } return rest_ensure_response( $response ); } } }