Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/surecart/app/config.php
+++ b/surecart/app/config.php
@@ -146,6 +146,8 @@
SureCartRestVariantValuesRestServiceProvider::class,
SureCartRestClicksRestServiceProvider::class,
SureCartRestVisitsRestServiceProvider::class,
+ SureCartRestAgentCatalogRestServiceProvider::class,
+ SureCartRestAIConnectionsRestServiceProvider::class,
SureCartRestReferralItemsRestServiceProvider::class,
SureCartRestPayoutsRestServiceProvider::class,
SureCartRestPayoutGroupsRestServiceProvider::class,
@@ -192,6 +194,8 @@
SureCartIntegrationsYoastYoastServiceProvider::class,
SureCartIntegrationsNpsSurveyNpsSurveyServiceProvider::class,
SureCartAbilitiesAbilitiesServiceProvider::class,
+ SureCartMCPMcpServerServiceProvider::class,
+ SureCartAgentCatalogAgentCatalogServiceProvider::class,
),
/**
--- a/surecart/app/helpers/product-helpers.php
+++ b/surecart/app/helpers/product-helpers.php
@@ -114,13 +114,13 @@
*/
function sc_query_products( $args = [] ) {
return new WP_Query(
- [
+ wp_parse_args(
$args,
[
'post_type' => 'sc_product',
'post_status' => 'publish',
- ],
- ]
+ ]
+ )
);
}
}
--- a/surecart/app/src/Abilities/AbilitiesServiceProvider.php
+++ b/surecart/app/src/Abilities/AbilitiesServiceProvider.php
@@ -50,10 +50,11 @@
$registrar = $container['surecart.abilities.registrar'];
// Pass toggle settings to the registrar so it can filter abilities.
+ $edit_enabled = (bool) get_option( 'surecart_mcp_edit_abilities_enabled', true );
$registrar->set_settings(
array(
- 'edit_enabled' => (bool) get_option( 'surecart_mcp_edit_abilities_enabled', true ),
- 'delete_enabled' => (bool) get_option( 'surecart_mcp_delete_abilities_enabled', true ),
+ 'edit_enabled' => $edit_enabled,
+ 'delete_enabled' => $edit_enabled && (bool) get_option( 'surecart_mcp_delete_abilities_enabled', true ),
)
);
--- a/surecart/app/src/Activation/ActivationService.php
+++ b/surecart/app/src/Activation/ActivationService.php
@@ -1,6 +1,8 @@
<?php
namespace SureCartActivation;
+use SureCartAgentCatalogAgentCatalogService;
+use SureCartMCPAIConnectionsService;
use SureCartIntegrationsNpsSurveyNpsSurveyNotice;
use SureCartModelsApiToken;
use SureCartModelsRegisteredWebhook;
@@ -320,6 +322,10 @@
delete_option( 'surecart_mcp_abilities_enabled' );
delete_option( 'surecart_mcp_edit_abilities_enabled' );
delete_option( 'surecart_mcp_delete_abilities_enabled' );
+ delete_option( AgentCatalogService::ENABLED_OPTION );
+ delete_option( AgentCatalogService::CACHE_VERSION_OPTION );
+ SureCart::agentCatalog()->deleteCache();
+ delete_metadata( 'user', 0, AIConnectionsService::META_KEY, '', true );
delete_option( SetupGuideService::OPTION );
delete_option( SetupGuideService::REPORTED_OPTION );
--- a/surecart/app/src/AgentCatalog/AgentCatalogService.php
+++ b/surecart/app/src/AgentCatalog/AgentCatalogService.php
@@ -0,0 +1,973 @@
+<?php
+
+namespace SureCartAgentCatalog;
+
+use SureCartModelsForm;
+use SureCartModelsPrice;
+use SureCartModelsProduct;
+use SureCartSupportCurrency;
+
+/**
+ * Builds the public, read-only product manifest for external AI shopping agents.
+ *
+ * Reads only the locally synced `sc_product` posts — never the platform API — so an
+ * anonymous request cannot fan out to api.surecart.com, and webhook re-syncs keep it fresh.
+ * Field names follow the OpenAI ACP product feed / Google UCP catalog vocabulary so a later
+ * push exporter is a mapping, not a remodel.
+ *
+ * Items are an explicit allow-list, never a serialized model, so private catalog fields
+ * (stock counts, SKUs, downloads — see SureCartSupportPublicCatalogData) cannot leak through here.
+ */
+class AgentCatalogService {
+ /**
+ * Manifest schema version. Bump on any breaking change to the output shape.
+ *
+ * @var string
+ */
+ const SCHEMA_VERSION = '1.0';
+
+ /**
+ * The option that turns the public catalog on or off (on by default).
+ *
+ * @var string
+ */
+ const ENABLED_OPTION = 'surecart_agent_catalog_enabled';
+
+ /**
+ * Default and maximum products per page, and the size of each cached chunk.
+ *
+ * @var int
+ */
+ const DEFAULT_PER_PAGE = 100;
+
+ /**
+ * How long a cached chunk is kept server-side, matching the endpoint's Cache-Control max-age.
+ *
+ * @var int
+ */
+ const CACHE_TTL = 300;
+
+ /**
+ * Option holding the cache version; bumping it orphans every cached page at once.
+ *
+ * @var string
+ */
+ const CACHE_VERSION_OPTION = 'surecart_agent_catalog_cache_version';
+
+ /**
+ * Prefix of every cache row and rebuild lock.
+ *
+ * @var string
+ */
+ const CACHE_PREFIX = 'sc_agent_catalog_';
+
+ /**
+ * How long a chunk's row is kept, so an outdated one can still be served while another request rebuilds it.
+ *
+ * @var int
+ */
+ const STALE_TTL = DAY_IN_SECONDS;
+
+ /**
+ * Seconds after which a rebuild lock is treated as abandoned (the builder died).
+ *
+ * @var int
+ */
+ const LOCK_TIMEOUT = 30;
+
+ /**
+ * Product metadata set to 'true' to hide a product. Synced to post meta, so the query filters it.
+ *
+ * @var string
+ */
+ const HIDDEN_META_KEY = 'agent_catalog_hidden';
+
+ /**
+ * Memoized live checkout page URL; null until resolved.
+ *
+ * @var string|null
+ */
+ protected $live_checkout_url = null;
+
+ /**
+ * Whether the cache was already invalidated this request.
+ *
+ * @var bool
+ */
+ protected $flushed = false;
+
+ /**
+ * Register WordPress hooks.
+ *
+ * @return void
+ */
+ public function bootstrap() {
+ add_action( 'wp_head', array( $this, 'addDiscoveryLink' ) );
+
+ // save_post_sc_product also catches status, password and trash changes made in wp-admin.
+ $checkout_option = SureCart::pages()->getOptionName( 'checkout', 'page' );
+ foreach ( array( 'surecart/product/sync/created', 'surecart/product/sync/updated', 'surecart/product_deleted', 'save_post_sc_product', 'surecart/account_updated', "add_option_{$checkout_option}", "update_option_{$checkout_option}" ) as $hook ) {
+ add_action( $hook, array( $this, 'flushCache' ) );
+ }
+ add_action( 'save_post_page', array( $this, 'flushCacheForCheckoutPage' ) );
+ add_action( 'save_post_sc_form', array( $this, 'flushCacheForCheckoutForm' ) );
+ }
+
+ /**
+ * Invalidate when the checkout form is saved; other forms never reach the manifest.
+ *
+ * @param int $post_id The saved form id.
+ *
+ * @return void
+ */
+ public function flushCacheForCheckoutForm( $post_id ) {
+ $form = $this->checkoutForm();
+ if ( $form && (int) $post_id === (int) $form->ID ) {
+ $this->flushCache();
+ }
+ }
+
+ /**
+ * Invalidate every cached manifest page; repeated calls write once until a chunk is rebuilt.
+ *
+ * @return void
+ */
+ public function flushCache() {
+ $this->live_checkout_url = null;
+
+ if ( $this->flushed ) {
+ return;
+ }
+ $this->flushed = true;
+
+ update_option( self::CACHE_VERSION_OPTION, (string) microtime( true ), false );
+ }
+
+ /**
+ * Invalidate when the checkout page itself is edited (e.g. its form is swapped).
+ *
+ * @param int $post_id The saved page id.
+ *
+ * @return void
+ */
+ public function flushCacheForCheckoutPage( $post_id ) {
+ if ( (int) $post_id === SureCart::pages()->getId( 'checkout' ) ) {
+ $this->flushCache();
+ }
+ }
+
+ /**
+ * Is the public manifest enabled for this store?
+ *
+ * @return bool
+ */
+ public function isEnabled(): bool {
+ return (bool) get_option( self::ENABLED_OPTION, true );
+ }
+
+ /**
+ * Advertise the manifest to agents that read page HTML.
+ *
+ * @return void
+ */
+ public function addDiscoveryLink() {
+ if ( ! $this->isEnabled() ) {
+ return;
+ }
+ printf(
+ '<link rel="alternate" type="application/json" title="%s" href="%s" />' . "n",
+ esc_attr__( 'Product catalog for AI agents', 'surecart' ),
+ esc_url( $this->url() )
+ );
+ }
+
+ /**
+ * Get one page of the manifest.
+ *
+ * Pages are sliced from cached fixed-size chunks of the catalog, so any page/per_page an
+ * anonymous caller picks is served from cache, and the number of cache rows is bounded by
+ * the catalog size — not by the inputs.
+ *
+ * @param int $page 1-based page number.
+ * @param int $per_page Products per page, 1 to DEFAULT_PER_PAGE.
+ *
+ * @return array
+ */
+ public function page( int $page = 1, int $per_page = self::DEFAULT_PER_PAGE ): array {
+ $per_page = max( 1, min( self::DEFAULT_PER_PAGE, $per_page ) );
+ $window = $this->window( $page, $per_page );
+ $total = $window['total'];
+
+ $total_pages = (int) ceil( $total / $per_page );
+
+ return array(
+ 'schema_version' => self::SCHEMA_VERSION,
+ 'generated_at' => gmdate( 'c' ),
+ 'store' => $this->store(),
+ 'products' => $window['products'],
+ 'pagination' => array(
+ 'page' => $page,
+ 'per_page' => $per_page,
+ 'total' => $total,
+ 'total_pages' => $total_pages,
+ 'next' => $page < $total_pages ? add_query_arg(
+ array(
+ 'page' => $page + 1,
+ 'per_page' => $per_page,
+ ),
+ $this->url()
+ ) : null,
+ ),
+ );
+ }
+
+ /**
+ * One fixed-size chunk of formatted products. An outdated row is served while one request rebuilds it.
+ *
+ * @param int $index 0-based chunk index.
+ *
+ * @return array{total: int, items: array} Items keep null for posts that aren't quotable.
+ */
+ protected function chunk( int $index ): array {
+ // plugin version in the key: an update never serves the old output shape.
+ $key = self::CACHE_PREFIX . SureCart::plugin()->version() . '_' . $index;
+ $version = (string) get_option( self::CACHE_VERSION_OPTION, '' );
+ $copy = get_transient( $key );
+ $copy = is_array( $copy ) ? $copy : null;
+
+ if ( $copy && $version === $copy['version'] && $copy['expires'] > time() ) {
+ return $copy['chunk'];
+ }
+
+ $lock = self::CACHE_PREFIX . 'lock_' . $index;
+ if ( $copy && ! $this->acquireLock( $lock ) ) {
+ return $copy['chunk'];
+ }
+
+ try {
+ $chunk = $this->buildChunk( $index );
+ } finally {
+ if ( $copy ) {
+ $this->releaseLock( $lock );
+ }
+ }
+
+ // a rebuild with identical output (e.g. Test -> Live -> Test) keeps its Last-Modified.
+ $hash = md5( wp_json_encode( array( $chunk, $this->store() ) ) );
+ $unchanged = $copy && ( $copy['hash'] ?? '' ) === $hash;
+ $chunk['changed_at'] = $unchanged ? $copy['chunk']['changed_at'] : time();
+
+ // stored even when empty, so a store with nothing listed doesn't query on every hit.
+ set_transient(
+ $key,
+ array(
+ 'version' => $version,
+ 'expires' => time() + self::CACHE_TTL,
+ 'hash' => $hash,
+ 'chunk' => $chunk,
+ ),
+ self::STALE_TTL
+ );
+ // re-arm flushCache().
+ $this->flushed = false;
+
+ return $chunk;
+ }
+
+ /**
+ * Query and format one chunk of products.
+ *
+ * @param int $index 0-based chunk index.
+ *
+ * @return array{total: int, items: array}
+ */
+ protected function buildChunk( int $index ): array {
+ $query = new WP_Query(
+ array_merge(
+ $this->listedQueryArgs(),
+ array(
+ 'posts_per_page' => self::DEFAULT_PER_PAGE,
+ 'offset' => $index * self::DEFAULT_PER_PAGE,
+ // stable order so pages don't shift while an agent walks them.
+ 'orderby' => 'ID',
+ 'order' => 'ASC',
+ )
+ )
+ );
+
+ return array(
+ 'total' => (int) $query->found_posts,
+ 'items' => array_map( array( $this, 'product' ), $query->posts ),
+ );
+ }
+
+ /**
+ * Take a short-lived rebuild lock. INSERT IGNORE, like WP_Upgrader::create_lock(): add_option() upserts.
+ *
+ * @param string $name Lock option name.
+ *
+ * @return bool Whether this request holds the lock.
+ */
+ protected function acquireLock( string $name ): bool {
+ global $wpdb;
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ if ( $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES ( %s, %s, 'no' )", $name, time() ) ) ) {
+ return true;
+ }
+
+ // get_option() may hold a cached miss.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $locked_at = (int) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM `$wpdb->options` WHERE option_name = %s", $name ) );
+
+ if ( $locked_at < time() - self::LOCK_TIMEOUT ) {
+ $this->releaseLock( $name );
+ }
+
+ return false;
+ }
+
+ /**
+ * Delete every cache row and lock, for uninstall.
+ *
+ * @return void
+ */
+ public function deleteCache() {
+ global $wpdb;
+
+ foreach ( array( '_transient_', '_transient_timeout_', '' ) as $type ) {
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $wpdb->query( $wpdb->prepare( "DELETE FROM `$wpdb->options` WHERE option_name LIKE %s", $wpdb->esc_like( $type . self::CACHE_PREFIX ) . '%' ) );
+ }
+ }
+
+ /**
+ * Drop a rebuild lock.
+ *
+ * @param string $name Lock option name.
+ *
+ * @return void
+ */
+ protected function releaseLock( string $name ) {
+ global $wpdb;
+ $wpdb->delete( $wpdb->options, array( 'option_name' => $name ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ }
+
+ /**
+ * Query args for the products the catalog may name: published, not password-protected, not hidden.
+ *
+ * @param array $meta_query Extra meta clauses, ANDed with the hidden check.
+ *
+ * @return array
+ */
+ protected function listedQueryArgs( array $meta_query = array() ): array {
+ return array(
+ 'post_type' => 'sc_product',
+ 'post_status' => 'publish',
+ 'has_password' => false,
+ 'meta_query' => array_merge(
+ array(
+ 'relation' => 'AND',
+ $this->visibleMetaQuery(),
+ ),
+ $meta_query
+ ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
+ 'update_post_term_cache' => false,
+ );
+ }
+
+ /**
+ * Which of these product ids the catalog may name.
+ *
+ * @param string[] $ids Product ids.
+ *
+ * @return string[]
+ */
+ protected function listedProductIds( array $ids ): array {
+ if ( empty( $ids ) ) {
+ return array();
+ }
+
+ $posts = get_posts(
+ array_merge(
+ $this->listedQueryArgs(
+ array(
+ array(
+ 'key' => 'sc_id',
+ 'value' => $ids,
+ 'compare' => 'IN',
+ ),
+ )
+ ),
+ array(
+ 'posts_per_page' => -1,
+ 'no_found_rows' => true,
+ )
+ )
+ );
+
+ return array_map(
+ function ( $post ) {
+ return (string) get_post_meta( $post->ID, 'sc_id', true );
+ },
+ $posts
+ );
+ }
+
+ /**
+ * Products the merchant has not hidden.
+ *
+ * @return array
+ */
+ protected function visibleMetaQuery(): array {
+ return array(
+ 'relation' => 'OR',
+ array(
+ 'key' => self::HIDDEN_META_KEY,
+ 'compare' => 'NOT EXISTS',
+ ),
+ array(
+ 'key' => self::HIDDEN_META_KEY,
+ 'value' => 'true',
+ 'compare' => '!=',
+ ),
+ );
+ }
+
+ /**
+ * How many published products the merchant has hidden. Admin only, never in the manifest.
+ *
+ * @return int
+ */
+ public function hiddenCount(): int {
+ $query = new WP_Query(
+ array(
+ 'post_type' => 'sc_product',
+ 'post_status' => 'publish',
+ 'has_password' => false,
+ 'meta_key' => self::HIDDEN_META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
+ 'meta_value' => 'true', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
+ 'fields' => 'ids',
+ 'posts_per_page' => 1,
+ 'update_post_meta_cache' => false,
+ 'update_post_term_cache' => false,
+ )
+ );
+
+ return (int) $query->found_posts;
+ }
+
+ /**
+ * The public manifest URL.
+ *
+ * @return string
+ */
+ public function url(): string {
+ return rest_url( 'surecart/v1/agent-catalog' );
+ }
+
+ /**
+ * Store-level (seller) information.
+ *
+ * @return array
+ */
+ protected function store(): array {
+ $account = SureCart::account();
+ $portal = $account->customer_portal_protocol ?? null;
+ $privacy = ! empty( $portal->privacy_url ) ? esc_url_raw( $portal->privacy_url ) : get_privacy_policy_url();
+
+ return array(
+ 'name' => get_bloginfo( 'name' ),
+ 'url' => home_url( '/' ),
+ 'currency' => strtoupper( (string) ( $account->currency ?? '' ) ),
+ 'terms_url' => ! empty( $portal->terms_url ) ? esc_url_raw( $portal->terms_url ) : null,
+ 'privacy_policy_url' => $privacy ? $privacy : null,
+ );
+ }
+
+ /**
+ * Format one synced product post for agents.
+ *
+ * @param WP_Post $post The synced product post.
+ *
+ * @return array|null Null when the product cannot be quoted (no model or no active price).
+ */
+ public function product( WP_Post $post ) {
+ $product = SureCart::productPost()->getModel( $post->ID );
+ if ( ! $product instanceof Product ) {
+ return null;
+ }
+
+ $prices = array_values(
+ array_filter(
+ (array) $product->active_prices,
+ function ( $price ) {
+ return $price instanceof Price && ! empty( $price->currency );
+ }
+ )
+ );
+ if ( empty( $prices ) ) {
+ return null;
+ }
+
+ // a bundle with variable components needs the buyer's component choices, which a link can't carry.
+ $can_link = ! $product->has_variable_components;
+ $variants = $this->variants( $product, $prices, $can_link );
+
+ $in_stock = null === $variants ? (bool) $product->in_stock : in_array( 'in_stock', array_column( $variants, 'availability' ), true );
+ $in_stock = $in_stock && $this->bundleComponentsAvailable( $product );
+
+ // a variant product needs a variant choice, so only its variants carry links.
+ $linkable = $can_link && null === $variants && $in_stock;
+ $offers = array_map(
+ function ( $price ) use ( $linkable ) {
+ return $this->offer( $price, $linkable );
+ },
+ $prices
+ );
+
+ $item = array(
+ 'id' => $product->id,
+ 'title' => $product->name,
+ 'description' => trim( wp_strip_all_tags( (string) $product->description ) ),
+ 'url' => get_permalink( $post ),
+ 'checkout_url' => ( $in_stock ? $this->instantCheckoutUrl( $product ) : null ) ?? $offers[0]['checkout_url'],
+ 'image_url' => $this->imageUrl( $product ),
+ 'availability' => $in_stock ? 'in_stock' : 'out_of_stock',
+ 'price' => array(
+ 'amount' => $offers[0]['amount'],
+ 'currency' => $offers[0]['currency'],
+ 'display' => $offers[0]['display'],
+ ),
+ 'offers' => $offers,
+ 'has_variants' => null !== $variants,
+ 'variants' => $variants ?? array(),
+ 'is_bundle' => ! empty( $product->bundle ),
+ 'bundle_items' => $this->bundleItems( $product ),
+ 'shippable' => (bool) $product->shipping_enabled,
+ 'license' => $product->licensing_enabled ? array(
+ 'type' => 'license_key',
+ 'activation_limit' => $product->license_activation_limit ? (int) $product->license_activation_limit : null,
+ ) : null,
+ 'updated_at' => $product->updated_at ? gmdate( 'c', (int) $product->updated_at ) : null,
+ );
+
+ /**
+ * Filter a product as exposed to external AI agents. Return null to leave it out.
+ *
+ * @param array $item The manifest item.
+ * @param Product $product The product model.
+ */
+ $item = apply_filters( 'surecart/agent_catalog/product', $item, $product );
+
+ return is_array( $item ) ? $item : null;
+ }
+
+ /**
+ * Format a price as an offer.
+ *
+ * @param Price $price The price.
+ * @param bool $linkable Whether a price alone can be bought (no variant choice, in stock).
+ *
+ * @return array
+ */
+ protected function offer( Price $price, bool $linkable ): array {
+ $billing = 'one_time';
+ if ( ! empty( $price->recurring_interval ) ) {
+ $billing = (int) $price->recurring_period_count > 1 ? 'installments' : 'subscription';
+ }
+
+ return array_merge(
+ array(
+ 'id' => $price->id,
+ 'name' => $price->name ? $price->name : null,
+ ),
+ $this->money( $this->baseAmount( $price ), $price->currency ),
+ array(
+ 'billing' => $billing,
+ 'interval' => $price->recurring_interval ? $price->recurring_interval : null,
+ 'interval_count' => $price->recurring_interval ? (int) $price->recurring_interval_count : null,
+ 'payments' => 'installments' === $billing ? (int) $price->recurring_period_count : null,
+ 'pay_what_you_want' => (bool) $price->ad_hoc,
+ 'checkout_url' => $linkable ? $this->checkoutPageUrl( $price ) : null,
+ )
+ );
+ }
+
+ /**
+ * Variants with their own availability and per-price checkout links.
+ *
+ * @param Product $product The product.
+ * @param Price[] $prices The quotable prices.
+ * @param bool $can_link Whether the product can be bought by link at all.
+ *
+ * @return array|null Null when the product has no variants.
+ */
+ protected function variants( Product $product, array $prices, bool $can_link ) {
+ if ( empty( $product->variants->data ) ) {
+ return null;
+ }
+
+ // option_1..3 map to the product's variant options in position order.
+ $options = $this->byPosition( $product->variant_options->data ?? array() );
+
+ return array_map(
+ function ( $variant ) use ( $product, $prices, $options, $can_link ) {
+ $values = array_filter( array( $variant->option_1, $variant->option_2, $variant->option_3 ) );
+
+ $in_stock = $this->variantInStock( $variant, $product );
+
+ return array(
+ 'id' => $variant->id,
+ 'title' => implode( ' / ', $values ),
+ 'options' => array_values(
+ array_map(
+ function ( $value, $slot ) use ( $options ) {
+ return array(
+ 'name' => $options[ $slot ]->name ?? null,
+ 'value' => $value,
+ );
+ },
+ $values,
+ array_keys( $values )
+ )
+ ),
+ 'availability' => $in_stock ? 'in_stock' : 'out_of_stock',
+ 'offers' => array_map(
+ function ( $price ) use ( $variant, $prices, $in_stock, $can_link ) {
+ // the product page shows a variant's own amount only when there is a single price.
+ $amount = 1 === count( $prices ) && ! empty( $variant->amount ) ? (int) $variant->amount : $this->baseAmount( $price );
+
+ return array_merge(
+ array( 'id' => $price->id ),
+ $this->money( $amount, $price->currency ),
+ array( 'checkout_url' => $can_link && $in_stock ? $this->checkoutPageUrl( $price, $variant->id ) : null )
+ );
+ },
+ $prices
+ ),
+ );
+ },
+ $product->variants->data
+ );
+ }
+
+ /**
+ * What a bundle contains and the choices the buyer makes. Component variants belong to other products, so they are not the bundle's `variants`.
+ *
+ * @param Product $product The product.
+ *
+ * @return array Empty for products that are not bundles.
+ */
+ protected function bundleItems( Product $product ): array {
+ if ( empty( $product->bundle ) ) {
+ return array();
+ }
+
+ $components = array();
+ foreach ( $this->byPosition( $product->bundle_items->data ?? array() ) as $item ) {
+ $component = $product->resolveBundleComponent( $item );
+ if ( empty( $component->id ) ) {
+ $component = is_object( $item->component_product ?? null ) ? $item->component_product : null;
+ }
+ if ( ! empty( $component->id ) ) {
+ $components[] = array( $item, $component );
+ }
+ }
+
+ // a component left out of the catalog (hidden, draft, archived) is not named through its bundle either.
+ $listed = $this->listedProductIds(
+ array_map(
+ function ( $pair ) {
+ return $pair[1]->id;
+ },
+ $components
+ )
+ );
+
+ $items = array();
+ foreach ( $components as list( $item, $component ) ) {
+ if ( ! in_array( $component->id, $listed, true ) ) {
+ continue;
+ }
+
+ $items[] = array(
+ 'product_id' => $component->id,
+ 'title' => $component->name ?? null,
+ 'quantity' => max( 1, (int) ( $item->quantity ?? 1 ) ),
+ 'options' => array_map(
+ function ( $option ) {
+ return array(
+ 'name' => $option->name ?? null,
+ 'values' => array_values( (array) ( $option->values ?? array() ) ),
+ );
+ },
+ $this->byPosition( $component->variant_options->data ?? array() )
+ ),
+ );
+ }
+
+ return $items;
+ }
+
+ /**
+ * Whether a variant can be bought.
+ *
+ * @param object $variant The variant.
+ * @param Product $product Its product.
+ *
+ * @return bool
+ */
+ protected function variantInStock( $variant, Product $product ): bool {
+ // an unset variant stock flag falls back to the product's. Not `??`: Model::__isset skips accessors.
+ $unlimited = $variant->has_unlimited_stock;
+ if ( null === $unlimited ) {
+ $unlimited = $product->has_unlimited_stock;
+ }
+
+ return $unlimited || (int) $variant->available_stock > 0;
+ }
+
+ /**
+ * Whether every bundle component can be bought, as the product page requires. True for non-bundles.
+ *
+ * @param Product $product The product.
+ *
+ * @return bool
+ */
+ protected function bundleComponentsAvailable( Product $product ): bool {
+ if ( empty( $product->bundle ) ) {
+ return true;
+ }
+
+ foreach ( $product->bundle_items->data ?? array() as $item ) {
+ $component = $product->resolveBundleComponent( $item );
+ if ( ! $component instanceof Product ) {
+ continue;
+ }
+
+ // "Unavailable for purchase": a false "out of stock" costs a sale, a false "in stock" a failed checkout.
+ if ( ! empty( $component->archived ) ) {
+ return false;
+ }
+
+ $variants = $component->variants->data ?? array();
+ $in_stock = empty( $variants )
+ ? (bool) $component->in_stock
+ : ! empty(
+ array_filter(
+ $variants,
+ function ( $variant ) use ( $component ) {
+ return $this->variantInStock( $variant, $component );
+ }
+ )
+ );
+
+ if ( ! $in_stock ) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Sort records by their `position`, the order the merchant set.
+ *
+ * @param array $records Records with an optional `position`.
+ *
+ * @return array
+ */
+ protected function byPosition( $records ): array {
+ $records = array_values( (array) $records );
+ usort(
+ $records,
+ function ( $a, $b ) {
+ return (int) ( $a->position ?? 0 ) <=> (int) ( $b->position ?? 0 );
+ }
+ );
+
+ return $records;
+ }
+
+ /**
+ * The amount to quote for a price, in minor units.
+ *
+ * @param Price $price The price.
+ *
+ * @return int
+ */
+ protected function baseAmount( Price $price ): int {
+ return $price->ad_hoc ? (int) $price->ad_hoc_min_amount : (int) $price->amount;
+ }
+
+ /**
+ * An amount as the agent-facing `amount`, `currency` and `display` fields.
+ *
+ * @param int $amount Amount in minor units.
+ * @param string $currency Currency code.
+ *
+ * @return array
+ */
+ protected function money( int $amount, string $currency ): array {
+ return array(
+ 'amount' => Currency::maybeConvertAmount( $amount, $currency ),
+ 'currency' => strtoupper( $currency ),
+ 'display' => Currency::format( $amount, $currency ),
+ );
+ }
+
+ /**
+ * Direct-to-checkout link for one price (and variant) — the same URL the Buy Button block builds.
+ *
+ * @param Price $price The price.
+ * @param string|null $variant_id The chosen variant, for variant products.
+ *
+ * @return string|null Null when a price can't be bought by link, or the checkout page is missing or not live.
+ */
+ protected function checkoutPageUrl( Price $price, $variant_id = null ) {
+ $checkout = $this->liveCheckoutPageUrl();
+
+ // a pay-what-you-want price needs the buyer's amount.
+ if ( empty( $checkout ) || $price->ad_hoc ) {
+ return null;
+ }
+
+ return add_query_arg(
+ array(
+ 'line_items' => array(
+ array_filter(
+ array(
+ 'price_id' => $price->id,
+ 'variant_id' => $variant_id,
+ 'quantity' => 1,
+ )
+ ),
+ ),
+ // keep it out of the shopper's persisted cart.
+ 'no_cart' => true,
+ ),
+ $checkout
+ );
+ }
+
+ /**
+ * The checkout page URL, only when its form takes live payments.
+ *
+ * Resolved once per instance: every offer on the page shares it.
+ *
+ * @return string Empty when there is no live checkout page.
+ */
+ protected function liveCheckoutPageUrl(): string {
+ if ( null !== $this->live_checkout_url ) {
+ return $this->live_checkout_url;
+ }
+
+ // never send an agent's buyer to a test-mode checkout.
+ $this->live_checkout_url = 'live' === $this->checkoutMode() ? (string) get_permalink( SureCart::pages()->get( 'checkout' ) ) : '';
+
+ return $this->live_checkout_url;
+ }
+
+ /**
+ * The checkout form on the store's checkout page.
+ *
+ * @return WP_Post|null Null when there is no checkout page or it has no form.
+ */
+ public function checkoutForm() {
+ $page = SureCart::pages()->get( 'checkout' );
+ $form = $page ? SureCart::post()->getFormPost( $page ) : null;
+
+ return ! empty( $form->ID ) ? $form : null;
+ }
+
+ /**
+ * The payment mode of the checkout page, which decides whether offers get checkout links.
+ *
+ * @return string 'live', 'test', or '' when there is no checkout form.
+ */
+ public function checkoutMode(): string {
+ $form = $this->checkoutForm();
+
+ return $form ? (string) Form::getMode( $form->ID ) : '';
+ }
+
+ /**
+ * When a manifest page's content last changed: the newest chunk it reads from.
+ *
+ * @param int $page 1-based page number.
+ * @param int $per_page Products per page.
+ *
+ * @return int Unix timestamp.
+ */
+ public function lastModified( int $page, int $per_page ): int {
+ return $this->window( $page, max( 1, min( self::DEFAULT_PER_PAGE, $per_page ) ) )['changed_at'];
+ }
+
+ /**
+ * The products on one page, sliced from the cached chunks it spans.
+ *
+ * @param int $page 1-based page number.
+ * @param int $per_page Products per page, 1 to DEFAULT_PER_PAGE.
+ *
+ * @return array{total: int, products: array, changed_at: int}
+ */
+ protected function window( int $page, int $per_page ): array {
+ $offset = ( max( 1, $page ) - 1 ) * $per_page;
+ $first = intdiv( $offset, self::DEFAULT_PER_PAGE );
+ $last = intdiv( $offset + $per_page - 1, self::DEFAULT_PER_PAGE );
+
+ // chunk 0 carries the total, so it is always read.
+ $head = $this->chunk( 0 );
+ $changed_at = $head['changed_at'];
+ $slots = array();
+ for ( $index = $first; $offset < $head['total'] && $index <= $last; $index++ ) {
+ $chunk = 0 === $index ? $head : $this->chunk( $index );
+ $slots = array_merge( $slots, $chunk['items'] );
+ $changed_at = max( $changed_at, $chunk['changed_at'] );
+ }
+
+ return array(
+ 'total' => $head['total'],
+ // slots keep nulls for skipped posts so offsets match the query.
+ 'products' => array_values( array_filter( array_slice( $slots, $offset - $first * self::DEFAULT_PER_PAGE, $per_page ) ) ),
+ 'changed_at' => $changed_at,
+ );
+ }
+
+ /**
+ * The product's Instant Checkout page, only when published and taking live payments.
+ *
+ * @param Product $product The product.
+ *
+ * @return string|null
+ */
+ protected function instantCheckoutUrl( Product $product ) {
+ $buy_link = $product->buyLink();
+
+ // never send an agent's buyer to a test-mode checkout.
+ if ( ! $buy_link->isEnabled() || 'test' === $buy_link->getMode() ) {
+ return null;
+ }
+
+ return $buy_link->url();
+ }
+
+ /**
+ * The primary product image URL.
+ *
+ * @param Product $product The product.
+ *
+ * @return string|null
+ */
+ protected function imageUrl( Product $product ) {
+ $image = $product->featured_image;
+ if ( empty( $image ) || ! method_exists( $image, 'attributes' ) ) {
+ return null;
+ }
+
+ $src = $image->attributes( 'large' )->src ?? '';
+
+ return $src ? esc_url_raw( $src ) : null;
+ }
+}
--- a/surecart/app/src/AgentCatalog/AgentCatalogServiceProvider.php
+++ b/surecart/app/src/AgentCatalog/AgentCatalogServiceProvider.php
@@ -0,0 +1,35 @@
+<?php
+
+namespace SureCartAgentCatalog;
+
+use SureCartCoreServiceProvidersServiceProviderInterface;
+
+/**
+ * Provides the public product catalog for AI agents as `SureCart::agentCatalog()`.
+ */
+class AgentCatalogServiceProvider implements ServiceProviderInterface {
+ /**
+ * Register all dependencies in the IoC container.
+ *
+ * @param PimpleContainer $container Service container.
+ * @return void
+ */
+ public function register( $container ) {
+ $container['surecart.agent_catalog'] = function () {
+ return new AgentCatalogService();
+ };
+
+ $app = $container[ SURECART_APPLICATION_KEY ];
+ $app->alias( 'agentCatalog', 'surecart.agent_catalog' );
+ }
+
+ /**
+ * Bootstrap any services if needed.
+ *
+ * @param PimpleContainer $container Service container.
+ * @return void
+ */
+ public function bootstrap( $container ) {
+ $container['surecart.agent_catalog']->bootstrap();
+ }
+}
--- a/surecart/app/src/Controllers/Admin/Settings/MCPSettings.php
+++ b/surecart/app/src/Controllers/Admin/Settings/MCPSettings.php
@@ -3,7 +3,7 @@
namespace SureCartControllersAdminSettings;
/**
- * Data for the client-side MCP settings tab (localized via the main Settings controller).
+ * Data for the client-side AI Assistants settings tab (localized via the main Settings controller).
*
* The MCP Adapter is installed from WordPress.org through core's `/wp/v2/plugins` REST endpoint,
* so it gets core updates and core's capability checks; there is no custom installer here.
@@ -24,6 +24,13 @@
const MCP_ADAPTER_URL = 'https://wordpress.org/plugins/mcp-adapter/';
/**
+ * Agent-Ready Catalog docs, the scanner's "Learn more" target.
+ *
+ * @var string
+ */
+ const AGENT_CATALOG_DOCS_URL = 'https://surecart.com/docs/agent-ready-catalog/';
+
+ /**
* Get the data required by the client-side MCP settings tab.
*
* Called from the main Settings controller to localize `scMCPData` on
@@ -40,6 +47,9 @@
$is_installed = isset( $all_plugins[ self::MCP_ADAPTER_SLUG ] );
$is_active = is_plugin_active( self::MCP_ADAPTER_SLUG );
+ $catalog = SureCart::agentCatalog();
+ $checkout_form = $catalog->checkoutForm();
+
return [
'mcp_adapter_installed' => $is_installed,
'mcp_adapter_active' => $is_active,
@@ -51,6 +61,13 @@
'wp_version' => get_bloginfo( 'version' ),
'abilities_api_available' => function_exists( 'wp_register_ability_category' ),
'current_username' => wp_get_current_user()->user_login,
+ 'agent_catalog_url' => $catalog->url(),
+ 'agent_catalog_docs_url' => self::AGENT_CATALOG_DOCS_URL,
+ 'agent_catalog_hidden' => $catalog->hiddenCount(),
+ 'agent_catalog_checkout' => [
+ 'mode' => $catalog->checkoutMode(),
+ 'edit_url' => $checkout_form ? get_edit_post_link( $checkout_form->ID, 'raw' ) : admin_url( 'admin.php?page=sc-restore&restore=checkout' ),
+ ],
];
}
}
--- a/surecart/app/src/Controllers/Rest/AIConnectionsController.php
+++ b/surecart/app/src/Controllers/Rest/AIConnectionsController.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace SureCartControllersRest;
+
+/**
+ * Lists the current user's connected AI assistants.
+ */
+class AIConnectionsController extends RestController {
+ /**
+ * List connections, with the server time so the client can compare without clock skew.
+ *
+ * @param WP_REST_Request $request The REST request.
+ *
+ * @return WP_REST_Response
+ */
+ public function index( WP_REST_Request $request ) {
+ $response = rest_ensure_response(
+ [
+ 'now' => time(),
+ 'connections' => SureCart::aiConnections()->connections( get_current_user_id() ),
+ ]
+ );
+
+ // polled while the setup wizard waits for the AI, so never cache it.
+ $response->header( 'Cache-Control', 'no-store' );
+
+ return $response;
+ }
+}
--- a/surecart/app/src/Controllers/Rest/AgentCatalogController.php
+++ b/surecart/app/src/Controllers/Rest/AgentCatalogController.php
@@ -0,0 +1,76 @@
+<?php
+
+namespace SureCartControllersRest;
+
+/**
+ * Serves the public product manifest to external AI agents.
+ */
+class AgentCatalogController extends RestController {
+ /**
+ * How long agents and CDNs may cache a manifest page, in seconds.
+ *
+ * @var int
+ */
+ const MAX_AGE = SureCartAgentCatalogAgentCatalogService::CACHE_TTL;
+
+ /**
+ * Get a page of the manifest, or 304 when the agent's copy is still current.
+ *
+ * @param WP_REST_Request $request The REST request.
+ *
+ * @return WP_REST_Response
+ */
+ public function index( WP_REST_Request $request ) {
+ $catalog = SureCart::agentCatalog();
+ $page = $catalog->page( (int) $request->get_param( 'page' ), (int) $request->get_param( 'per_page' ) );
+
+ // generated_at changes every response, so it is left out of the hash.
+ $etag = 'W/"' . md5( wp_json_encode( array_diff_key( $page, array( 'generated_at' => true ) ) ) ) . '"';
+ $last_modified = $catalog->lastModified( (int) $request->get_param( 'page' ), (int) $request->get_param( 'per_page' ) );
+
+ $response = $this->isNotModified( $request, $etag, $last_modified )
+ ? new WP_REST_Response( null, 304 )
+ : rest_ensure_response( $page );
+
+ // overrides CacheService's no-cache Expires; page caches stay off this route.
+ $response->header( 'Cache-Control', 'public, max-age=' . self::MAX_AGE );
+ $response->header( 'Expires', gmdate( 'D, d M Y H:i:s', time() + self::MAX_AGE ) . ' GMT' );
+ $response->header( 'ETag', $etag );
+ $response->header( 'Last-Modified', gmdate( 'D, d M Y H:i:s', $last_modified ) . ' GMT' );
+
+ return $response;
+ }
+
+ /**
+ * Does the request's validator still match? If-None-Match wins over If-Modified-Since (RFC 9110 13.2.2).
+ *
+ * @param WP_REST_Request $request The REST request.
+ * @param string $etag The current ETag.
+ * @param int $last_modified The current Last-Modified timestamp.
+ *
+ * @return bool
+ */
+ protected function isNotModified( WP_REST_Request $request, string $etag, int $last_modified ): bool {
+ $if_none_match = $request->get_header( 'If-None-Match' );
+ if ( null !== $if_none_match ) {
+ $tags = array_map( array( $this, 'opaqueTag' ), explode( ',', $if_none_match ) );
+
+ return in_array( '*', $tags, true ) || in_array( $this->opaqueTag( $etag ), $tags, true );
+ }
+
+ $since = strtotime( (string) $request->get_header( 'If-Modified-Since' ) );
+
+ return $since && $last_modified <= $since;
+ }
+
+ /**
+ * An entity tag for weak comparison: no W/ prefix, and no -gzip/-br suffix that Apache's mod_deflate/mod_brotli append.
+ *
+ * @param string $tag Entity tag as sent.
+ *
+ * @return string
+ */
+ protected function opaqueTag( string $tag ): string {
+ return preg_replace( array( '#^W/#', '#-(gzip|br)"$#' ), array( '', '"' ), trim( $tag ) );
+ }
+}
--- a/surecart/app/src/MCP/AIConnectionsService.php
+++ b/surecart/app/src/MCP/AIConnectionsService.php
@@ -0,0 +1,183 @@
+<?php
+
+namespace SureCartMCP;
+
+/**
+ * Knows which application passwords belong to connected AI assistants.
+ *
+ * Every AI client (MCP clients and ChatGPT's Abilities REST action) signs in with an
+ * application password, so the first authenticated request to an AI route is the
+ * "connected" signal and the first tool call is the "answered a question" signal.
+ * Listing and revoking reuse core's application passwords; only the AI-specific
+ * timestamps are stored here, in user meta keyed by application password uuid.
+ */
+class AIConnectionsService {
+ /**
+ * User meta holding `{ uuid: { connected_at, last_used_at, first_question_at } }`.
+ *
+ * @var string
+ */
+ const META_KEY = 'surecart_ai_connections';
+
+ /**
+ * Minimum seconds between `last_used_at` writes, so a chatty session isn't a write per request.
+ *
+ * @var int
+ */
+ const TOUCH_INTERVAL = 60;
+
+ /**
+ * Register WordPress hooks.
+ *
+ * @return void
+ */
+ public function bootstrap() {
+ add_filter( 'rest_request_before_callbacks', array( $this, 'track' ), 10, 3 );
+ add_action( 'wp_delete_application_password', array( $this, 'forget' ), 10, 2 );
+ }
+
+ /**
+ * Record AI use of an application password. Passes the response through untouched.
+ *
+ * @param mixed $response Response to replace the requested version with.
+ * @param array $handler Route handler.
+ * @param WP_REST_Request $request The request.
+ *
+ * @return mixed
+ */
+ public function track( $response, $handler, $request ) {
+ if ( is_wp_error( $response ) || ! function_exists( 'rest_get_authenticated_app_password' ) ) {
+ return $response;
+ }
+
+ $uuid = rest_get_authenticated_app_password();
+ $kind = $uuid ? $this->requestKind( $request ) : null;
+ if ( $kind ) {
+ $this->record( get_current_user_id(), $uuid, 'question' === $kind );
+ }
+
+ return $response;
+ }
+
+ /**
+ * Is this request an AI connecting, or an AI running a tool?
+ *
+ * @param WP_REST_Request $request The request.
+ *
+ * @return string|null 'question', 'connect', or null when it isn't an AI route.
+ */
+ protected function requestKind( WP_REST_Request $request ) {
+ $route = $request->get_route();
+
+ // MCP adapter servers (JSON-RPC: a tool call is the AI answering something).
+ if ( 0 === strpos( $route, '/mcp/' ) ) {
+ $body = $request->get_json_params();
+ return 'tools/call' === ( $body['method'] ?? '' ) ? 'question' : 'connect';
+ }
+
+ // Core Abilities REST API, used by the ChatGPT custom GPT action.
+ if ( 0 === strpos( $route, '/wp-abilities/' ) ) {
+ return '/run' === substr( $route, -4 ) ? 'question' : 'connect';
+ }
+
+ return null;
+ }
+
+ /**
+ * Store the timestamps for one application password.
+ *
+ * @param int $user_id The user the password belongs to.
+ * @param string $uuid Application password uuid.
+ * @param bool $is_question Whether this request ran a tool.
+ *
+ * @return void
+ */
+ public function record( int $user_id, string $uuid, bool $is_question ) {
+ $all = $this->stored( $user_id );
+ $now = time();
+ $entry = $all[ $uuid ] ?? array(
+ 'connected_at' => $now,
+ 'last_used_at' => 0,
+ 'first_question_at' => null,
+ );
+
+ $touch = $now - (int) $entry['last_used_at'] >= self::TOUCH_INTERVAL;
+ $question = $is_question && empty( $entry['first_question_at'] );
+ if ( ! $touch && ! $question && isset( $all[ $uuid ] ) ) {
+ return;
+ }
+
+ $entry['last_used_at'] = $now;
+ if ( $question ) {
+ $entry['first_question_at'] = $now;
+ }
+
+ $all[ $uuid ] = $entry;
+ update_user_meta( $user_id, self::META_KEY, $all );
+ }
+
+ /**
+ * Drop the timestamps when core deletes the application password.
+ *
+ * @param int $user_id The user id.
+ * @param array $item The deleted application password.
+ *
+ * @return void
+ */
+ public function forget( $user_id, $item ) {
+ $all = $this->stored( (int) $user_id );
+ if ( isset( $item['uuid'], $all[ $item['uuid'] ] ) ) {
+ unset( $all[ $item['uuid'] ] );
+ update_user_meta( (int) $user_id, self::META_KEY, $all );
+ }
+ }
+
+ /**
+ * The user's AI connections, most recently used first.
+ *
+ * Only application passwords that still exist and have been used by an AI are listed.
+ *
+ * @param int $user_id The user id.
+ *
+ * @return array<int, array{uuid: string, name: string, connected_at: int, last_used_at: int, first_question_at: int|null}>
+ */
+ public function connections( int $user_id ): array {
+ $stored = $this->stored( $user_id );
+ $list = array();
+
+ foreach ( WP_Application_Passwords::get_user_application_passwords( $user_id ) as $password ) {
+ if ( empty( $stored[ $password['uuid'] ] ) ) {
+ continue;
+ }
+ $entry = $stored[ $password['uuid'] ];
+ $list[] = array(
+ 'uuid' => $password['uuid'],
+ 'name' => $password['name'],
+ 'connected_at' => (int) $entry['connected_at'],
+ 'last_used_at' => (int) $entry['last_used_at'],
+ 'first_question_at' => $entry['first_question_at'] ? (int) $entry['first_question_at'] : null,
+ );
+ }
+
+ usort(
+ $list,
+ function ( $a, $b ) {
+ return $b['last_used_at'] <=> $a['last_used_at'];
+ }
+ );
+
+ return $list;
+ }
+
+ /**
+ * The raw stored timestamps.
+ *
+ * @param int $user_id The user id.
+ *
+ * @return array
+ */
+ protected function stored( int $user_id ): array {
+ $all = get_user_meta( $user_id, self::META_KEY, true );
+ return is_array( $all ) ? $all : array();
+ }
+}
--- a/surecart/app/src/MCP/McpServerServiceProvider.php
+++ b/surecart/app/src/MCP/McpServerServiceProvider.php
@@ -0,0 +1,41 @@
+<?php
+
+namespace SureCartMCP;
+
+use SureCartCoreServiceProvidersServiceProviderInterface;
+
+/**
+ * Service provider for MCP (Model Context Protocol) integration.
+ *
+ * Handles AJAX handlers for MCP adapter plugin install/activate.
+ * The MCP adapter plugin's default server automatically exposes
+ * all abilities registered via wp_register_ability().
+ */
+class McpServerServiceProvider implements ServiceProviderInterface {
+
+ /**
+ * Register all dependencies in the IoC container.
+ *
+ * @param PimpleContainer $container Service container.
+ * @return void
+ */
+ public function register( $container ) {
+ $container['surecart.ai_connections'] = function () {
+ return new AIConnectionsService();
+ };
+
+ $app = $container[ SURECART_APPLICATION_KEY ];
+ $app->alias( 'aiConnections', 'surecart.ai_connections' );
+ }
+
+ /**
+ * Bootstrap the service.
+ *
+ * @param PimpleContainer $container Service container.
+ * @return void
+ */
+ public function bootstrap( $container ) {
+ // AI requests are REST requests, so this can't be admin-only.
+ $container['surecart.ai_connections']->bootstrap();
+ }
+}
--- a/surecart/app/src/Rest/AIConnectionsRestServiceProvider.php
+++ b/surecart/app/src/Rest/AIConnectionsRestServiceProvider.php
@@ -0,0 +1,58 @@
+<?php
+
+namespace SureCartRest;
+
+use SureCartControllersRestAIConnectionsController;
+
+/**
+ * The current user's connected AI assistants, for the AI Assistants settings page.
+ *
+ * Read-only: disconnecting revokes the application password through core's
+ * `/wp/v2/users/me/application-passwords/{uuid}` route.
+ */
+class AIConnectionsRestServiceProvider extends RestServiceProvider implements RestServiceInterface {
+ /**
+ * Endpoint.
+ *
+ * @var string
+ */
+ protected $endpoint = 'ai_connections';
+
+ /**
+ * No model CRUD routes; the single read route is registered in registerRoutes().
+ *
+ * @var array
+ */
+ protected $methods = [];
+
+ /**
+ * Register REST Routes
+ *
+ * @return void
+ */
+ public function registerRoutes() {
+ register_rest_route(
+ "$this->name/v$this->version",
+ "$this->endpoint",
+ [
+ [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => $this->callback( AIConnectionsController::class, 'index' ),
+ 'permission_callback' => [ $this, 'get_items_permissions_check' ],
+ ],
+ 'schema' => [ $this, 'get_item_schema' ],
+ ]
+ );
+ }
+
+ /**
+ * Same capability as the settings page that shows them.
+ *
+ * @param WP_REST_Request $request Full details about the request.
+ *
+ * @return bool
+ */
+ public function get_items_permissions_check( $request ) {
+ return current_user_can( 'manage_sc_shop_settings' );
+ }
+}
--- a/surecart/app/src/Rest/AgentCatalogRestServiceProvider.php
+++ b/surecart/app/src/Rest/AgentCatalogRestServiceProvider.php
@@ -0,0 +1,68 @@
+<?php
+
+namespace SureCartRest;
+
+use SureCartAgentCatalogAgentCatalogService;
+use SureCartControllersRestAgentCatalogController;
+
+/**
+ * Public, read-only product manifest for external AI shopping agents.
+ *
+ * While the merchant has it off the route is not registered, so the store is invisible
+ * to agents looking for it. The discovery link lives in the AgentCatalogService.
+ */
+class AgentCatalogRestServiceProvider extends RestServiceProvider implements RestServiceInterface {
+ /**
+ * Endpoint.
+ *
+ * @var string
+ */
+ protected $endpoint = 'agent-catalog';
+
+ /**
+ * No model CRUD routes; the single read route is registered in registerRoutes().
+ *
+ * @var array
+ */
+ protected $methods = [];
+
+ /**
+ * Register REST Routes
+ *
+ * @return void
+ */
+ public function registerRoutes() {
+ if ( ! SureCart::agentCatalog()->isEnabled() ) {
+ return;
+ }
+
+ register_rest_route(
+ "$this->name/v$this->version",
+ "$this->endpoint",
+ [
+ [
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => $this->callback( AgentCatalogController::class, 'index' ),
+ 'permission_callback' => '__return_true',
+ 'args' => [
+ 'page' => [
+ 'description' => esc_html__( 'Page of the catalog to return.', 'surecart' ),
+ 'type' => 'integer',
+ 'default' => 1,
+ 'minimum' => 1,
+ ],
+ 'per_page' => [
+ 'description' => esc_html__( 'Products per page.', 'surecart' ),
+ 'type' => 'integer',
+ // one request covers most stores; image lookups scale per item, so the default is also the cap.
+ 'default' => AgentCatalogService::DEFAULT_PER_PAGE,
+ 'minimum' => 1,
+ 'maximum' => AgentCatalogService::DEFAULT_PER_PAGE,
+ ],
+ ],
+ ],
+ 'schema' => [ $this, 'get_item_schema' ],
+ ]
+ );
+ }
+}
--- a/surecart/app/src/Rest/TaxRegistrationRestServiceProvider.php
+++ b/surecart/app/src/Rest/TaxRegistrationRestServiceProvider.php
@@ -76,6 +76,22 @@
'type' => [ 'number', 'null' ],
'context' => [ 'view', 'edit', 'embed' ],
],
+ 'tax_components' => [
+ 'description' => esc_html__( 'The separate taxes that make up the manual rate, each shown as its own line. Empty or null for a single tax line.', 'surecart' ),
+ 'type' => [ 'array', 'null' ],
+ 'context' => [ 'view', 'edit', 'embed' ],
+ 'items' => [
+ 'type' => 'object',
+ 'properties' => [
+ 'label' => [
+ 'type' => 'string',
+ ],
+ 'rate' => [
+ 'type' => 'number',
+ ],
+ ],
+ ],
+ ],
],
];
--- a/surecart/app/src/Settings/SettingService.php
+++ b/surecart/app/src/Settings/SettingService.php
@@ -595,6 +595,18 @@
);
$this->register(
'surecart',
+ 'agent_catalog_enabled',
+ [
+ 'type' => 'boolean',
+ 'show_in_rest' => true,
+ 'sanitize_callback' => 'boolval',
+ 'default' => true,
+ // read on every REST boot and front-end head.
+ 'autoload' => true,
+ ]
+ );
+ $this->register(
+ 'surecart',
'enhanced_admin_views',
[
'type' => 'boolean',
--- a/surecart/app/src/Support/Errors/Translations/attributes.php
+++ b/surecart/app/src/Support/Errors/Translations/attributes.php
@@ -39,4 +39,5 @@
'shipments.to_contact.phone' => __( 'Recipient phone', 'surecart' ),
'to_contact.email' => __( 'Recipient email', 'surecart' ),
'to_contact.phone' => __( 'Recipient phone', 'surecart' ),
+ 'manual_rate' => __( 'Tax rate', 'surecart' ),
];
--- a/surecart/app/src/Support/Errors/Translations/codes.php
+++ b/surecart/app/src/Support/Errors/Translations/codes.php
@@ -152,4 +152,11 @@
'shipment.weight.not_a_number' => __( 'The package weight must be a number.', 'surecart' ),
'shipment.g_weight.blank' => __( 'Please provide the package weight.', 'surecart' ),
'shipment.g_weight.not_a_number' => __( 'The package weight must be a number.', 'surecart' ),
+ 'tax_registration.tax_components.too_few' => __( 'Please add at least 2 tax components.', 'surecart' ),
+ 'tax_registration.tax_components.too_many' => __( 'You can add at most 5 tax components.', 'surecart' ),
+ 'tax_registration.tax_components.blank_label' => __( 'Each tax component needs a label.', 'surecart' ),
+ 'tax_registration.tax_components.label_too_long' => __( 'Tax component labels must be 50 characters or fewer.', 'surecart' ),
+ 'tax_registration.tax_components.duplicate_label' => __( 'Each tax component must have a different label.', 'surecart' ),
+ 'tax_registration.tax_components.invalid_rate' => __( 'Each tax component rate must be greater than 0.', 'surecart' ),
+ 'tax_registration.tax_components.rates_mismatch' => __( 'The tax component rates must add up to the tax rate.', 'surecart' ),
);
--- a/surecart/app/src/WordPress/Admin/PluginCache/AdminPluginCacheService.php
+++ b/surecart/app/src/WordPress/Admin/PluginCache/AdminPluginCacheService.php
@@ -40,15 +40,17 @@
// 'breeze/breeze.php', // we added support for this in the plugin
// 'perfmatters/perfmatters.php', // we added support for this in the plugin
// 'hummingbird-performance/wp-hummingbird.php', // we added support for this in the plugin
- 'swift-performance-lite/performance.php',
- 'wp-optimize/wp-optimize.php',
- 'nitropack/main.php',
- 'wp-asset-clean-up/wpacu.php',
- 'flying-pages/flying-pages.php',
- 'fast-velocity-minify/fvm.php',
- 'wp-performance-score-booster/wp-performance-score-booster.php',
- 'clearfy/clearfy.php',
- 'psn-pagespeed-ninja/pagespeedninja.php',
+ // 'wp-optimize/wp-optimize.php', // we added support for this in the plugin
+ // 'nitropack/main.php', // we added support for this in the plugin
+ // 'wp-asset-clean-up/wpacu.php', // we added support for this in the plugin
+ // 'flying-pages/flying-pages.php', // we added support for this in the plugin
+ // 'fast-velocity-minify/fvm.php', // we added support for this in the plugin
+
+ // Not planned for first party support list.
+ 'swift-performance-lite/performance.php', // It's under WP review now.
+ 'clearfy/clearfy.php', // lower maintained plugin: don't add first party support, last updated 3 months ago.
+ 'wp-performance-score-booster/wp-performance-score-booster.php', // lower maintained plugin: don't add first party support, last updated 2 months ago.
+ 'psn-pagespeed-ninja/pagespeedninja.php', // lower maintained plugin: don't add first party support, last updated 2 years ago.
]
);
}
--- a/surecart/app/src/WordPress/Cache/AssetCleanUpCacheService.php
+++ b/surecart/app/src/WordPress/Cache/AssetCleanUpCacheService.php
@@ -0,0 +1,76 @@
+<?php
+
+namespace SureCartWordPressCache;
+
+/**
+ * Asset CleanUp (Page Speed Booster) Cache Service.
+ *
+ * Asset CleanUp has no page cache. Its "Combine loaded JS" moves core scripts like
+ * wp-i18n/wp-api-fetch into a combined BODY file (deferred when "defer" is on), so the
+ * Interactivity API modules that read them run first ("wp is not defined"). It never
+ * combines `type="module"` scripts, so only classic core scripts need protecting.
+ *
+ * Asset CleanUp reuses each page's combined-file list for up to a day without
+ * re-checking its settings, so pages combined before this ran pick it up once that expires.
+ */
+class AssetCleanUpCacheService extends CacheService {
+ /**
+ * Hook Asset CleanUp's settings and per-page opt-out filters.
+ *
+ * Does not call parent::registerHooks() — Asset CleanUp does no page caching.
+ *
+ * @return void
+ */
+ protected function registerHooks(): void {
+ add_filter( 'wpacu_settings', [ $this, 'excludeScriptsFromCombine' ] );
+ add_filter( 'wpacu_prevent_any_frontend_optimization', [ $this, 'maybeSkipOptimization' ] );
+ }
+
+ /**
+ * Check if the Asset CleanUp plugin (Lite or Pro) is active.
+ *
+ * @return bool
+ */
+ protected function isCachePluginActive(): bool {
+ return defined( 'WPACU_PLUGIN_VERSION' );
+ }
+
+ /**
+ * Keep critical core scripts out of Asset CleanUp's combined JS files.
+ *
+ * Excluded files are left exactly where WordPress printed them. The filter returns the
+ * settings for the current request only; it's skipped in wp-admin so the settings form
+ * never saves SureCart's patterns into the user's own list.
+ *
+ * @param mixed $settings Asset CleanUp settings.
+ * @return mixed
+ */
+ public function excludeScriptsFromCombine( $settings ) {
+ if ( is_admin() || ! is_array( $settings ) ) {
+ return $settings;
+ }
+
+ // Rules are newline-separated; plain ones are substring-matched against each script's src.
+ $exceptions = isset( $settings['combine_loaded_js_exceptions'] ) ? trim( (string) $settings['combine_loaded_js_exceptions'] ) : '';
+ $settings['combine_loaded_js_exceptions'] = trim( $exceptions . "n" . implode( "n", $this->getJsDeferExcludes() ) );
+
+ return $settings;
+ }
+
+ /**
+ * Skip all of Asset CleanUp's front-end optimization on dynamic SureCart pages.
+ *
+ * Asset CleanUp also asks before the main query, where page checks can't work yet,
+ * so those calls are left alone — it only caches a "don't skip" answer from 'wp' on.
+ *
+ * @param bool $prevent Whether to skip optimization on this page.
+ * @return bool
+ */
+ public function maybeSkipOptimization( $prevent ) {
+ if ( $prevent || ! did_action( 'wp' ) ) {
+ return $prevent;
+ }
+
+ return $this->shouldExcludeFromCache();
+ }
+}
--- a/surecart/app/src/WordPress/Cache/CacheService.php
+++ b/surecart/app/src/WordPress/Cache/CacheService.php
@@ -258,6 +258,45 @@
}
/**
+ * Relative paths of the published dynamic pages from getDynamicPageKeys().
+ *
+ * For optimizers that take a static list of URLs to skip; each one wraps
+ * these in its own pattern syntax.
+ *
+ * @return string[]
+ */
+ protected function getDynamicPagePaths(): array {
+ $paths = [];
+
+ foreach ( $this->getDynamicPageKeys() as $page ) {
+ $path = $this->getPagePath( (int) SureCart::pages()->getId( $page ) );
+ if ( $path ) {
+ $paths[] = $path;
+ }
+ }
+
+ return $paths;
+ }
+
+ /**
+ * Base path of pretty buy links (/buy/{product-slug}/), without a trailing slash.
+ *
+ * Only exists with a permalink structure — plain-permalink and legacy ?sc-buy
+ * links are query-based, which page caches already skip.
+ *
+ * @return string Empty string when there is no pretty buy base.
+ */
+ protected function getBuyPageBasePath(): string {
+ if ( ! get_option( 'permalink_structure' ) ) {
+ return '';
+ }
+
+ $buy_base = trim( (string) SureCart::settings()->permalinks()->getBase( 'buy_page' ), '/' );
+
+ return '' !== $buy_base ? '/' . $buy_base : '';
+ }
+
+ /**
* Determine which dynamic SureCart page (if any) the current request matches.
*
* Iterates getDynamicPageKeys() so isCustomerDashboardPage()/isCheckoutPage()
--- a/surecart/app/src/WordPress/Cache/CacheServiceProvider.php
+++ b/surecart/app/src/WordPress/Cache/CacheServiceProvider.php
@@ -63,6 +63,21 @@
$container['surecart.hummingbird_cache'] = function () {
return new HummingbirdCacheService();
};
+ $container['surecart.wpoptimize_cache'] = function () {
+ return new WpOptimizeCacheService();
+ };
+ $container['surecart.nitropack_cache'] = function () {
+ return new NitroPackCacheService();
+ };
+ $container['surecart.fastvelocityminify_cache'] = function () {
+ return new FastVelocityMinifyCacheService();
+ };
+ $container['surecart.flyingpages_cache'] = function () {
+