diff --git a/admin/section/class-convertkit-admin-section-base.php b/admin/section/class-convertkit-admin-section-base.php
index 650b0321d..79d3e38c0 100644
--- a/admin/section/class-convertkit-admin-section-base.php
+++ b/admin/section/class-convertkit-admin-section-base.php
@@ -47,7 +47,7 @@ abstract class ConvertKit_Admin_Section_Base {
*
* @since 1.9.6
*
- * @var false|ConvertKit_Settings|ConvertKit_ContactForm7_Settings|ConvertKit_Wishlist_Settings|ConvertKit_Settings_Restrict_Content|ConvertKit_Settings_Broadcasts|ConvertKit_Forminator_Settings
+ * @var false|ConvertKit_Settings|ConvertKit_ContactForm7_Settings|ConvertKit_Wishlist_Settings|ConvertKit_Settings_Restrict_Content|ConvertKit_Settings_Broadcasts|ConvertKit_Forminator_Settings|ConvertKit_Settings_MCP
*/
public $settings;
diff --git a/admin/section/class-convertkit-admin-section-mcp.php b/admin/section/class-convertkit-admin-section-mcp.php
new file mode 100644
index 000000000..8cb7f2be8
--- /dev/null
+++ b/admin/section/class-convertkit-admin-section-mcp.php
@@ -0,0 +1,176 @@
+ Kit > MCP.
+ *
+ * @package ConvertKit
+ * @author ConvertKit
+ */
+class ConvertKit_Admin_Section_MCP extends ConvertKit_Admin_Section_Base {
+
+ /**
+ * Constructor.
+ *
+ * @since 3.4.0
+ */
+ public function __construct() {
+
+ // Define the class that reads/writes settings.
+ $this->settings = new ConvertKit_Settings_MCP();
+
+ // Define the settings key.
+ $this->settings_key = $this->settings::SETTINGS_NAME;
+
+ // Define the programmatic name, Title and Tab Text.
+ $this->name = 'mcp';
+ $this->title = __( 'MCP', 'convertkit' );
+ $this->tab_text = __( 'MCP', 'convertkit' );
+
+ // Identify that this is beta functionality.
+ $this->is_beta = true;
+
+ // Define settings sections.
+ $this->settings_sections = array(
+ 'general' => array(
+ 'title' => $this->title,
+ 'callback' => array( $this, 'print_section_info' ),
+ 'wrap' => true,
+ ),
+ );
+
+ // Register and maybe output notices for this settings screen, and the Intercom messenger.
+ if ( $this->on_settings_screen( $this->name ) ) {
+ add_action( 'convertkit_settings_base_render_before', array( $this, 'maybe_output_notices' ) );
+ }
+
+ // Enqueue scripts and CSS.
+ add_action( 'convertkit_admin_settings_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
+
+ parent::__construct();
+
+ }
+
+ /**
+ * Enqueues scripts for the Settings > MCP screen.
+ *
+ * @since 3.4.0
+ *
+ * @param string $section Settings section / tab (general|tools|restrict-content|broadcasts|mcp).
+ */
+ public function enqueue_scripts( $section ) {
+
+ // Bail if we're not on the MCP section.
+ if ( $section !== $this->name ) {
+ return;
+ }
+
+ // Enqueue JS.
+ wp_enqueue_script( 'convertkit-admin-settings-conditional-display', CONVERTKIT_PLUGIN_URL . 'resources/backend/js/settings-conditional-display.js', array( 'jquery' ), CONVERTKIT_PLUGIN_VERSION, true );
+
+ }
+
+ /**
+ * Registers settings fields for this section.
+ *
+ * @since 3.4.0
+ */
+ public function register_fields() {
+
+ // Enable.
+ add_settings_field(
+ 'enabled',
+ __( 'Enable MCP Server', 'convertkit' ),
+ array( $this, 'enabled_callback' ),
+ $this->settings_key,
+ $this->name,
+ array(
+ 'name' => 'enabled',
+ 'label_for' => 'enabled',
+ 'label' => __( 'When enabled, allows AI clients to connect to the Kit Plugin using MCP.', 'convertkit' ),
+ 'description' => sprintf(
+ '%s %s',
+ __( 'Go to your AI tool to add a custom connector by pasting this URL to connect to this plugin:', 'convertkit' ),
+ get_site_url() . '/wp-json/kit/mcp/v1'
+ ),
+ )
+ );
+
+ }
+
+ /**
+ * Prints help info for this section
+ *
+ * @since 3.4.0
+ */
+ public function print_section_info() {
+
+ ?>
+
+
+ output_checkbox_field(
+ $args['name'],
+ 'on',
+ $this->settings->enabled(),
+ $args['label'],
+ $args['description'],
+ array( 'convertkit-conditional-display' )
+ );
+
+ }
+
+}
+
+// Bootstrap.
+add_filter(
+ 'convertkit_admin_settings_register_sections',
+ function ( $sections ) {
+
+ // Don't register the MCP section if the Abilities API is not available (WordPress < 6.9).
+ if ( ! function_exists( 'wp_register_ability' ) ) {
+ return $sections;
+ }
+
+ // Don't register the MCP section if PHP 7.4+ is not installed.
+ if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
+ return $sections;
+ }
+
+ $sections['mcp'] = new ConvertKit_Admin_Section_MCP();
+ return $sections;
+
+ }
+);
diff --git a/includes/blocks/class-convertkit-block-broadcasts.php b/includes/blocks/class-convertkit-block-broadcasts.php
index d41ba18fb..60db77639 100644
--- a/includes/blocks/class-convertkit-block-broadcasts.php
+++ b/includes/blocks/class-convertkit-block-broadcasts.php
@@ -27,6 +27,9 @@ public function __construct() {
// Register this as a Gutenberg block in the ConvertKit Plugin.
add_filter( 'convertkit_blocks', array( $this, 'register' ) );
+ // Register this block's MCP abilities.
+ add_filter( 'convertkit_abilities', array( $this, 'register_abilities' ) );
+
// Enqueue scripts and styles for this Gutenberg Block in the editor and frontend views.
add_action( 'convertkit_gutenberg_enqueue_scripts_editor_and_frontend', array( $this, 'enqueue_scripts' ) );
add_action( 'convertkit_gutenberg_enqueue_styles_editor_and_frontend', array( $this, 'enqueue_styles' ) );
@@ -171,6 +174,19 @@ public function get_title() {
}
+ /**
+ * Returns this block's plural title.
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ public function get_title_plural() {
+
+ return __( 'Kit Broadcasts', 'convertkit' );
+
+ }
+
/**
* Returns this block's icon.
*
diff --git a/includes/blocks/class-convertkit-block-form-trigger.php b/includes/blocks/class-convertkit-block-form-trigger.php
index 4bec4aa50..4acbdd3f4 100644
--- a/includes/blocks/class-convertkit-block-form-trigger.php
+++ b/includes/blocks/class-convertkit-block-form-trigger.php
@@ -27,6 +27,9 @@ public function __construct() {
// Register this as a Gutenberg block in the ConvertKit Plugin.
add_filter( 'convertkit_blocks', array( $this, 'register' ) );
+ // Register this block's MCP abilities.
+ add_filter( 'convertkit_abilities', array( $this, 'register_abilities' ) );
+
// Enqueue scripts and styles for this Gutenberg Block in the editor and frontend views.
add_action( 'convertkit_gutenberg_enqueue_styles_editor_and_frontend', array( $this, 'enqueue_styles' ) );
@@ -73,6 +76,19 @@ public function get_title() {
}
+ /**
+ * Returns this block's plural title.
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ public function get_title_plural() {
+
+ return __( 'Kit Form Triggers', 'convertkit' );
+
+ }
+
/**
* Returns this block's icon.
*
diff --git a/includes/blocks/class-convertkit-block-form.php b/includes/blocks/class-convertkit-block-form.php
index f5e121ba8..7a7db6e73 100644
--- a/includes/blocks/class-convertkit-block-form.php
+++ b/includes/blocks/class-convertkit-block-form.php
@@ -27,6 +27,9 @@ public function __construct() {
// Register this as a Gutenberg block in the ConvertKit Plugin.
add_filter( 'convertkit_blocks', array( $this, 'register' ) );
+ // Register this block's MCP abilities.
+ add_filter( 'convertkit_abilities', array( $this, 'register_abilities' ) );
+
// Enqueue scripts for this Gutenberg Block in the editor view.
add_action( 'convertkit_gutenberg_enqueue_scripts', array( $this, 'enqueue_scripts_editor' ) );
@@ -101,6 +104,19 @@ public function get_title() {
}
+ /**
+ * Returns this block's plural title.
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ public function get_title_plural() {
+
+ return __( 'Kit Forms', 'convertkit' );
+
+ }
+
/**
* Returns this block's icon.
*
diff --git a/includes/blocks/class-convertkit-block-product.php b/includes/blocks/class-convertkit-block-product.php
index bea8b12a5..aaf522f81 100644
--- a/includes/blocks/class-convertkit-block-product.php
+++ b/includes/blocks/class-convertkit-block-product.php
@@ -27,6 +27,9 @@ public function __construct() {
// Register this as a Gutenberg block in the ConvertKit Plugin.
add_filter( 'convertkit_blocks', array( $this, 'register' ) );
+ // Register this block's MCP abilities.
+ add_filter( 'convertkit_abilities', array( $this, 'register_abilities' ) );
+
// Enqueue scripts and styles for this Gutenberg Block in the editor and frontend views.
add_action( 'convertkit_gutenberg_enqueue_scripts_editor_and_frontend', array( $this, 'enqueue_scripts' ) );
add_action( 'convertkit_gutenberg_enqueue_styles_editor_and_frontend', array( $this, 'enqueue_styles' ) );
@@ -95,6 +98,19 @@ public function get_title() {
}
+ /**
+ * Returns this block's plural title.
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ public function get_title_plural() {
+
+ return __( 'Kit Products', 'convertkit' );
+
+ }
+
/**
* Returns this block's icon.
*
diff --git a/includes/blocks/class-convertkit-block.php b/includes/blocks/class-convertkit-block.php
index c308a1bd0..35d78d32f 100644
--- a/includes/blocks/class-convertkit-block.php
+++ b/includes/blocks/class-convertkit-block.php
@@ -68,10 +68,10 @@ public function register_abilities( $abilities ) {
return array_merge(
$abilities,
array(
- new ConvertKit_MCP_Ability_Content_List( $this ),
- new ConvertKit_MCP_Ability_Content_Insert( $this ),
- new ConvertKit_MCP_Ability_Content_Update( $this ),
- new ConvertKit_MCP_Ability_Content_Delete( $this ),
+ 'kit/' . $this->get_name() . '-list' => new ConvertKit_MCP_Ability_Content_List( $this ),
+ 'kit/' . $this->get_name() . '-insert' => new ConvertKit_MCP_Ability_Content_Insert( $this ),
+ 'kit/' . $this->get_name() . '-update' => new ConvertKit_MCP_Ability_Content_Update( $this ),
+ 'kit/' . $this->get_name() . '-delete' => new ConvertKit_MCP_Ability_Content_Delete( $this ),
)
);
@@ -105,6 +105,19 @@ public function get_title() {
}
+ /**
+ * Returns this block's plural title.
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ public function get_title_plural() {
+
+ return '';
+
+ }
+
/**
* Returns this block's icon.
*
diff --git a/includes/blocks/helpers/class-convertkit-block-post-helper.php b/includes/blocks/helpers/class-convertkit-block-post-helper.php
index 5472cb319..7d25b57b8 100644
--- a/includes/blocks/helpers/class-convertkit-block-post-helper.php
+++ b/includes/blocks/helpers/class-convertkit-block-post-helper.php
@@ -41,13 +41,12 @@ public static function find( $post_id, $block_name ) {
$occurrence_index = 0;
- foreach ( $blocks as $index => $block ) {
+ foreach ( $blocks as $block ) {
if ( ! isset( $block['blockName'] ) || $block['blockName'] !== $block_name ) {
continue;
}
$found[] = array(
- 'index' => (int) $index,
'occurrence_index' => (int) $occurrence_index,
'attrs' => $block['attrs'],
);
@@ -73,6 +72,18 @@ public static function find( $post_id, $block_name ) {
*/
public static function insert( $post_id, $block_name, $attrs, $position = 'append', $index = 0 ) {
+ // If the index is negative, bail.
+ if ( $position === 'index' && (int) $index < 0 ) {
+ return new WP_Error(
+ 'convertkit_block_post_helper_invalid_index',
+ sprintf(
+ /* translators: %d: index */
+ __( 'The supplied index (%d) must be zero or a positive integer.', 'convertkit' ),
+ (int) $index
+ )
+ );
+ }
+
// Get Post.
$post = get_post( $post_id );
if ( ! $post ) {
@@ -115,6 +126,15 @@ public static function insert( $post_id, $block_name, $attrs, $position = 'appen
// Splice in the new block.
array_splice( $blocks, $insert_at, 0, array( $new_block ) );
+ // Determine the occurrence index of the newly inserted block, by
+ // counting how many blocks of the same name precede it.
+ $occurrence_index = 0;
+ for ( $i = 0; $i < $insert_at; $i++ ) {
+ if ( isset( $blocks[ $i ]['blockName'] ) && $blocks[ $i ]['blockName'] === $block_name ) {
+ ++$occurrence_index;
+ }
+ }
+
// Update Post.
$result = wp_update_post(
array(
@@ -129,10 +149,10 @@ public static function insert( $post_id, $block_name, $attrs, $position = 'appen
return $result;
}
- // Return the index the block was inserted at.
+ // Return the occurrence index of the newly inserted block.
return array(
- 'post_id' => $post_id,
- 'index' => $insert_at,
+ 'post_id' => $post_id,
+ 'occurrence_index' => $occurrence_index,
);
}
@@ -162,13 +182,10 @@ public static function update( $post_id, $block_name, $occurrence_index, $attrs
// Parse blocks.
$blocks = parse_blocks( $post->post_content );
- $update_at = 0;
$block_index = 0;
$matched = false;
foreach ( $blocks as $key => $block ) {
- ++$update_at;
-
// Skip if the block name does not match.
if ( ! isset( $block['blockName'] ) || $block['blockName'] !== $block_name ) {
continue;
@@ -207,10 +224,10 @@ public static function update( $post_id, $block_name, $occurrence_index, $attrs
return $result;
}
- // Return the index the block was updated at.
+ // Return the occurrence index of the block that was updated.
return array(
- 'post_id' => $post_id,
- 'index' => ( $update_at - 1 ),
+ 'post_id' => $post_id,
+ 'occurrence_index' => (int) $occurrence_index,
);
}
@@ -239,19 +256,16 @@ public static function delete( $post_id, $block_name, $occurrence_index ) {
// Parse blocks.
$blocks = parse_blocks( $post->post_content );
- $delete_at = 0;
$block_index = 0;
$matched = false;
foreach ( $blocks as $key => $block ) {
- ++$delete_at;
-
// Skip if the block name does not match.
if ( ! isset( $block['blockName'] ) || $block['blockName'] !== $block_name ) {
continue;
}
- // Update the block if the occurrence index matches.
+ // Delete the block if the occurrence index matches.
if ( $block_index === (int) $occurrence_index ) {
unset( $blocks[ $key ] );
$blocks = array_values( $blocks );
@@ -285,10 +299,10 @@ public static function delete( $post_id, $block_name, $occurrence_index ) {
return $result;
}
- // Return the index the block was deleted from.
+ // Return the occurrence index of the block that was deleted.
return array(
- 'post_id' => $post_id,
- 'index' => ( $delete_at - 1 ),
+ 'post_id' => $post_id,
+ 'occurrence_index' => (int) $occurrence_index,
);
}
diff --git a/includes/blocks/helpers/class-convertkit-content-post-helper.php b/includes/blocks/helpers/class-convertkit-content-post-helper.php
index 4925eaf73..762ea5edd 100644
--- a/includes/blocks/helpers/class-convertkit-content-post-helper.php
+++ b/includes/blocks/helpers/class-convertkit-content-post-helper.php
@@ -53,6 +53,12 @@ public static function find( $post_id, $element_name ) {
$post_id,
'convertkit/' . $element_name
);
+
+ case 'shortcode':
+ return ConvertKit_Shortcode_Post_Helper::find(
+ $post_id,
+ 'convertkit_' . $element_name
+ );
}
return self::unsupported_mechanism_error( $mechanism );
@@ -80,7 +86,6 @@ public static function insert( $post_id, $element_name, $attrs, $position = 'app
}
// Insert the element into the post, depending on the mechanism.
- // A switch is used as shortcodes and other mechanisms will be supported in the future.
switch ( $mechanism ) {
case 'block':
return ConvertKit_Block_Post_Helper::insert(
@@ -90,6 +95,15 @@ public static function insert( $post_id, $element_name, $attrs, $position = 'app
$position,
$index
);
+
+ case 'shortcode':
+ return ConvertKit_Shortcode_Post_Helper::insert(
+ $post_id,
+ 'convertkit_' . $element_name,
+ $attrs,
+ $position,
+ $index
+ );
}
return self::unsupported_mechanism_error( $mechanism );
@@ -117,7 +131,6 @@ public static function update( $post_id, $element_name, $occurrence_index, $attr
}
// Updates the existing occurrence of the element in the post, depending on the mechanism.
- // A switch is used as shortcodes and other mechanisms will be supported in the future.
switch ( $mechanism ) {
case 'block':
return ConvertKit_Block_Post_Helper::update(
@@ -126,6 +139,14 @@ public static function update( $post_id, $element_name, $occurrence_index, $attr
$occurrence_index,
$attrs
);
+
+ case 'shortcode':
+ return ConvertKit_Shortcode_Post_Helper::update(
+ $post_id,
+ 'convertkit_' . $element_name,
+ $occurrence_index,
+ $attrs
+ );
}
return self::unsupported_mechanism_error( $mechanism );
@@ -160,6 +181,13 @@ public static function delete( $post_id, $element_name, $occurrence_index ) {
'convertkit/' . $element_name,
$occurrence_index
);
+
+ case 'shortcode':
+ return ConvertKit_Shortcode_Post_Helper::delete(
+ $post_id,
+ 'convertkit_' . $element_name,
+ $occurrence_index
+ );
}
return self::unsupported_mechanism_error( $mechanism );
diff --git a/includes/blocks/helpers/class-convertkit-shortcode-post-helper.php b/includes/blocks/helpers/class-convertkit-shortcode-post-helper.php
new file mode 100644
index 000000000..f13fddce9
--- /dev/null
+++ b/includes/blocks/helpers/class-convertkit-shortcode-post-helper.php
@@ -0,0 +1,557 @@
+post_content, $shortcode_tag );
+ $found = array();
+
+ foreach ( $matches as $occurrence_index => $match ) {
+ $found[] = array(
+ // Zero-based index of this occurrence among occurrences of
+ // this shortcode in the post.
+ 'occurrence_index' => (int) $occurrence_index,
+ 'attrs' => self::parse_attrs( $match ),
+ );
+ }
+
+ // If no shortcodes found, return false.
+ if ( empty( $found ) ) {
+ return false;
+ }
+
+ return $found;
+
+ }
+
+ /**
+ * Inserts a new shortcode into the Post's content at the specified
+ * position.
+ *
+ * @since 3.4.0
+ *
+ * @param int $post_id Post ID.
+ * @param string $shortcode_tag Programmatic Shortcode Tag.
+ * @param array $attrs Shortcode Attributes.
+ * @param string $position One of 'prepend', 'append', 'index'.
+ * @param int $index Zero-based top-level element index; only used when $position is 'index'.
+ * @return WP_Error|array
+ */
+ public static function insert( $post_id, $shortcode_tag, $attrs, $position = 'append', $index = 0 ) {
+
+ // If the index is negative, bail.
+ if ( $position === 'index' && (int) $index < 0 ) {
+ return new WP_Error(
+ 'convertkit_shortcode_post_helper_invalid_index',
+ sprintf(
+ /* translators: %d: index */
+ __( 'The supplied index (%d) must be zero or a positive integer.', 'convertkit' ),
+ (int) $index
+ )
+ );
+ }
+
+ // Get Post.
+ $post = get_post( $post_id );
+ if ( ! $post ) {
+ return new WP_Error(
+ 'convertkit_shortcode_post_helper_insert_post_not_found',
+ /* translators: %d: post ID */
+ sprintf( __( 'No post exists with ID %d.', 'convertkit' ), $post_id )
+ );
+ }
+
+ // Build the shortcode string to insert.
+ $shortcode = self::build_shortcode( $shortcode_tag, $attrs );
+ $content = $post->post_content;
+
+ // Determine the byte offset of the start of each top-level element.
+ $starts = self::get_element_starts( $content );
+
+ // Resolve $position into a concrete byte offset within the content.
+ switch ( $position ) {
+ case 'prepend':
+ $insert_at = 0;
+ break;
+
+ case 'index':
+ // Insert before the Nth top-level element. If no elements
+ // exist, or the index is equal to / beyond count(), append
+ // after all existing content — mirroring how array_splice()
+ // treats an index equal to the array length.
+ if ( empty( $starts ) || (int) $index >= count( $starts ) ) {
+ $insert_at = strlen( $content );
+ } else {
+ $insert_at = $starts[ (int) $index ];
+ }
+ break;
+
+ case 'append':
+ default:
+ $insert_at = strlen( $content );
+ break;
+ }
+
+ // Determine the occurrence index the new shortcode will have, by
+ // counting how many existing occurrences of the same shortcode start
+ // before the insertion offset.
+ $occurrence_index = 0;
+ foreach ( self::match_shortcodes( $content, $shortcode_tag ) as $match ) {
+ if ( $match['offset'] < $insert_at ) {
+ ++$occurrence_index;
+ }
+ }
+
+ // Splice the shortcode into the content at the resolved offset,
+ // wrapped in blank lines so it sits as its own top-level element.
+ // All other content is left byte-for-byte unchanged.
+ $snippet = self::pad_snippet( $shortcode, $content, $insert_at );
+ $content = substr_replace( $content, $snippet, $insert_at, 0 );
+
+ // Update Post.
+ $result = wp_update_post(
+ array(
+ 'ID' => $post_id,
+ 'post_content' => $content,
+ ),
+ true
+ );
+
+ // Bail if the update failed.
+ if ( is_wp_error( $result ) ) {
+ return $result;
+ }
+
+ // Return the occurrence index of the newly inserted shortcode.
+ return array(
+ 'post_id' => $post_id,
+ 'occurrence_index' => $occurrence_index,
+ );
+
+ }
+
+ /**
+ * Updates the attributes of an existing shortcode in the Post's content.
+ *
+ * @since 3.4.0
+ *
+ * @param int $post_id Post ID.
+ * @param string $shortcode_tag Programmatic Shortcode Tag.
+ * @param int $occurrence_index Zero-based occurrence index to update.
+ * @param array $attrs Shortcode Attributes.
+ * @return WP_Error|array
+ */
+ public static function update( $post_id, $shortcode_tag, $occurrence_index, $attrs ) {
+
+ // Get Post.
+ $post = get_post( $post_id );
+ if ( ! $post ) {
+ return new WP_Error(
+ 'convertkit_shortcode_post_helper_update_post_not_found',
+ /* translators: %d: post ID */
+ sprintf( __( 'No post exists with ID %d.', 'convertkit' ), $post_id )
+ );
+ }
+
+ // Match all occurrences of the shortcode.
+ $matches = self::match_shortcodes( $post->post_content, $shortcode_tag );
+
+ // Bail if the requested occurrence does not exist.
+ if ( ! isset( $matches[ (int) $occurrence_index ] ) ) {
+ return new WP_Error(
+ 'convertkit_shortcode_post_helper_occurrence_not_found',
+ sprintf(
+ /* translators: 1: shortcode tag, 2: occurrence index, 3: post ID */
+ __( 'No occurrence #%2$d of shortcode %1$s found in post %3$d.', 'convertkit' ),
+ $shortcode_tag,
+ (int) $occurrence_index,
+ $post_id
+ )
+ );
+ }
+
+ // Build the replacement shortcode, merging new attributes over existing.
+ $match = $matches[ (int) $occurrence_index ];
+ $merged_attrs = array_merge( self::parse_attrs( $match ), (array) $attrs );
+ $replacement = self::build_shortcode( $shortcode_tag, $merged_attrs );
+
+ // Replace the matched shortcode text with the rebuilt shortcode.
+ $content = self::replace_match( $post->post_content, $match, $replacement );
+
+ // Update Post.
+ $result = wp_update_post(
+ array(
+ 'ID' => $post_id,
+ 'post_content' => $content,
+ ),
+ true
+ );
+
+ // Bail if the update failed.
+ if ( is_wp_error( $result ) ) {
+ return $result;
+ }
+
+ // Return the occurrence index that was updated.
+ return array(
+ 'post_id' => $post_id,
+ 'occurrence_index' => (int) $occurrence_index,
+ );
+
+ }
+
+ /**
+ * Deletes a specific shortcode from the Post's content.
+ *
+ * @since 3.4.0
+ *
+ * @param int $post_id Post ID.
+ * @param string $shortcode_tag Programmatic Shortcode Tag.
+ * @param int $occurrence_index Zero-based occurrence index to delete.
+ * @return WP_Error|array
+ */
+ public static function delete( $post_id, $shortcode_tag, $occurrence_index ) {
+
+ // Get Post.
+ $post = get_post( $post_id );
+ if ( ! $post ) {
+ return new WP_Error(
+ 'convertkit_shortcode_post_helper_delete_post_not_found',
+ /* translators: %d: post ID */
+ sprintf( __( 'No post exists with ID %d.', 'convertkit' ), $post_id )
+ );
+ }
+
+ // Match all occurrences of the shortcode.
+ $matches = self::match_shortcodes( $post->post_content, $shortcode_tag );
+
+ // Bail if the requested occurrence does not exist.
+ if ( ! isset( $matches[ (int) $occurrence_index ] ) ) {
+ return new WP_Error(
+ 'convertkit_shortcode_post_helper_occurrence_not_found',
+ sprintf(
+ /* translators: 1: shortcode tag, 2: occurrence index, 3: post ID */
+ __( 'No occurrence #%2$d of shortcode %1$s found in post %3$d.', 'convertkit' ),
+ $shortcode_tag,
+ (int) $occurrence_index,
+ $post_id
+ )
+ );
+ }
+
+ // Remove the matched shortcode text from the content.
+ $content = self::replace_match( $post->post_content, $matches[ (int) $occurrence_index ], '' );
+
+ // Update Post.
+ $result = wp_update_post(
+ array(
+ 'ID' => $post_id,
+ 'post_content' => $content,
+ ),
+ true
+ );
+
+ // Bail if the update failed.
+ if ( is_wp_error( $result ) ) {
+ return $result;
+ }
+
+ // Return the occurrence index that was deleted.
+ return array(
+ 'post_id' => $post_id,
+ 'occurrence_index' => (int) $occurrence_index,
+ );
+
+ }
+
+ /**
+ * Returns all matches of the given shortcode tag within the content, in
+ * document order.
+ *
+ * Each match is an array of:
+ * - 'text' The full matched shortcode string (e.g. `[convertkit_form form="1"]`).
+ * - 'offset' Its byte offset within the content.
+ * - 'atts' The raw attribute string only (e.g. `form="1"`), suitable for
+ * passing directly to shortcode_parse_atts().
+ *
+ * @since 3.4.0
+ *
+ * @param string $content Post content.
+ * @param string $shortcode_tag Programmatic Shortcode Tag.
+ * @return array
+ */
+ private static function match_shortcodes( $content, $shortcode_tag ) {
+
+ // Build a shortcode regex scoped to this single tag.
+ $pattern = get_shortcode_regex( array( $shortcode_tag ) );
+
+ // Bail if there are no matches.
+ if ( ! preg_match_all( '/' . $pattern . '/', $content, $matches, PREG_OFFSET_CAPTURE ) ) {
+ return array();
+ }
+
+ // Build array of shortcode matches.
+ $found = array();
+ foreach ( $matches[0] as $i => $match ) {
+ $found[] = array(
+ 'text' => $match[0],
+ 'offset' => (int) $match[1],
+ 'atts' => isset( $matches[3][ $i ][0] ) ? trim( (string) $matches[3][ $i ][0] ) : '',
+ );
+ }
+
+ return $found;
+
+ }
+
+ /**
+ * Parses the attributes of a single matched shortcode into a key/value
+ * array.
+ *
+ * @since 3.4.0
+ *
+ * @param array $shortcode A match from match_shortcodes().
+ * @return array
+ */
+ private static function parse_attrs( $shortcode ) {
+
+ // Parse the raw attribute string (e.g. `form="1"`). shortcode_parse_atts()
+ // expects only the attributes, without the surrounding brackets or tag name.
+ $attrs = shortcode_parse_atts( $shortcode['atts'] );
+
+ // Discard any positional (non-string keyed) attributes, keeping only
+ // named attributes.
+ foreach ( array_keys( $attrs ) as $key ) {
+ if ( ! is_string( $key ) ) {
+ unset( $attrs[ $key ] );
+ }
+ }
+
+ return $attrs;
+
+ }
+
+ /**
+ * Builds a self-closing shortcode string from a tag and attributes.
+ *
+ * @since 3.4.0
+ *
+ * @param string $shortcode_tag Programmatic Shortcode Tag.
+ * @param array $attrs Shortcode Attributes.
+ * @return string
+ */
+ private static function build_shortcode( $shortcode_tag, $attrs ) {
+
+ $shortcode = '[' . $shortcode_tag;
+
+ foreach ( (array) $attrs as $key => $value ) {
+ // Skip empty attribute names.
+ if ( ! is_string( $key ) || '' === $key ) {
+ continue;
+ }
+
+ $shortcode .= sprintf( ' %s="%s"', $key, esc_attr( (string) $value ) );
+ }
+
+ $shortcode .= ']';
+
+ return $shortcode;
+
+ }
+
+ /**
+ * Replaces a single matched shortcode occurrence with the replacement
+ * string.
+ *
+ * @since 3.4.0
+ *
+ * @param string $content Post content.
+ * @param array $atts A match from match_shortcodes().
+ * @param string $replacement Replacement string (empty string to delete).
+ * @return string
+ */
+ private static function replace_match( $content, $atts, $replacement ) {
+
+ return substr_replace(
+ $content,
+ $replacement,
+ $atts['offset'],
+ strlen( $atts['text'] )
+ );
+
+ }
+
+ /**
+ * Wraps a shortcode snippet in blank-line padding so that, once inserted
+ * at the given offset, it sits as its own top-level element.
+ *
+ * @since 3.4.0
+ *
+ * @param string $shortcode The shortcode string to insert.
+ * @param string $content The content the shortcode is being inserted into.
+ * @param int $offset Byte offset within $content the shortcode will be inserted at.
+ * @return string
+ */
+ private static function pad_snippet( $shortcode, $content, $offset ) {
+
+ // Determine the text immediately before and after the insertion point.
+ $before = substr( $content, 0, $offset );
+ $after = substr( $content, $offset );
+
+ // Add a leading blank line unless the shortcode is at the start of the
+ // content, or already preceded by a blank line.
+ $lead = ( $before === '' || preg_match( '/\R\R\s*$/', $before ) ) ? '' : "\n\n";
+
+ // Add a trailing blank line unless the shortcode is at the end of the
+ // content, or already followed by a blank line.
+ $trail = ( $after === '' || preg_match( '/^\s*\R\R/', $after ) ) ? '' : "\n\n";
+
+ return $lead . $shortcode . $trail;
+
+ }
+
+ /**
+ * Returns the byte offset of the start of each top-level element in the
+ * content, in document order.
+ *
+ * Uses WP_HTML_Tag_Processor (WP 6.2+) for nesting-aware structure, paired
+ * with a regex for the byte offsets the tag processor does not expose.
+ * Falls back to regex alone on older WordPress versions.
+ *
+ * @since 3.4.0
+ *
+ * @param string $content Post content.
+ * @return array
+ */
+ private static function get_element_starts( $content ) {
+
+ if ( trim( (string) $content ) === '' ) {
+ return array();
+ }
+
+ // Candidate offsets, one per regex-matched element-level opener.
+ $pattern = '/<(' . self::ELEMENT_LEVEL_TAGS . ')\b[^>]*>.*?<\/\1>/is';
+ if ( ! preg_match_all( $pattern, $content, $matches, PREG_OFFSET_CAPTURE ) ) {
+ return array();
+ }
+
+ // Fallback for WP < 6.2: regex offsets verbatim, no nesting awareness.
+ if ( ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
+ $starts = array();
+ foreach ( $matches[0] as $match ) {
+ $starts[] = (int) $match[1];
+ }
+ return $starts;
+ }
+
+ // Per-tag queue of regex offsets in document order.
+ $queues = array();
+ foreach ( $matches[1] as $i => $tag_match ) {
+ $queues[ strtoupper( $tag_match[0] ) ][] = (int) $matches[0][ $i ][1];
+ }
+
+ // Walk with depth tracking; record offsets only for depth-zero openers.
+ $processor = new WP_HTML_Tag_Processor( $content );
+ $starts = array();
+ $depth = 0;
+ $element_level_tags = array_flip( explode( '|', strtoupper( self::ELEMENT_LEVEL_TAGS ) ) );
+
+ while ( $processor->next_tag( array( 'tag_closers' => 'visit' ) ) ) {
+ $tag = $processor->get_tag();
+
+ if ( ! isset( $element_level_tags[ $tag ] ) ) {
+ continue;
+ }
+
+ if ( $processor->is_tag_closer() ) {
+ if ( $depth > 0 ) {
+ --$depth;
+ }
+ continue;
+ }
+
+ $offset = array_shift( $queues[ $tag ] );
+
+ if ( $depth === 0 ) {
+ $starts[] = $offset;
+ }
+
+ if ( $tag !== 'HR' ) {
+ ++$depth;
+ }
+ }
+
+ // Treat blank line separated text as paragraphs, matching the logic in wpautop().
+ $opener_prefix = '/^<(?:' . self::ELEMENT_LEVEL_TAGS . ')\b/i';
+ $offset = 0;
+ foreach ( preg_split( '/(\R\R+)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE ) as $i => $chunk ) {
+ // Odd indices are the delimiters captured by PREG_SPLIT_DELIM_CAPTURE.
+ if ( $i % 2 === 1 ) {
+ $offset += strlen( $chunk );
+ continue;
+ }
+
+ $trimmed = trim( $chunk );
+ if ( $trimmed !== '' && ! preg_match( $opener_prefix, $trimmed ) ) {
+ $starts[] = $offset + ( strlen( $chunk ) - strlen( ltrim( $chunk ) ) );
+ }
+
+ $offset += strlen( $chunk );
+ }
+
+ sort( $starts, SORT_NUMERIC );
+
+ return $starts;
+
+ }
+
+}
diff --git a/includes/class-convertkit-settings-mcp.php b/includes/class-convertkit-settings-mcp.php
new file mode 100644
index 000000000..9e58b50f1
--- /dev/null
+++ b/includes/class-convertkit-settings-mcp.php
@@ -0,0 +1,121 @@
+settings = $this->get_defaults();
+ } else {
+ $this->settings = array_merge( $this->get_defaults(), $settings );
+ }
+
+ }
+
+ /**
+ * Returns Plugin settings.
+ *
+ * @since 3.4.0
+ *
+ * @return array
+ */
+ public function get() {
+
+ return $this->settings;
+
+ }
+
+ /**
+ * Returns whether the MCP server is enabled.
+ *
+ * @since 3.4.0
+ *
+ * @return bool
+ */
+ public function enabled() {
+
+ return ( $this->settings['enabled'] === 'on' ? true : false );
+
+ }
+
+ /**
+ * The default settings, used when the ConvertKit MCP Settings haven't been saved
+ * e.g. on a new installation.
+ *
+ * @since 2.1.0
+ *
+ * @return array
+ */
+ public function get_defaults() {
+
+ $defaults = array(
+ 'enabled' => '', // blank|on.
+ );
+
+ /**
+ * The default settings, used when the ConvertKit MCP Settings haven't been saved
+ * e.g. on a new installation.
+ *
+ * @since 3.4.0
+ *
+ * @param array $defaults Default settings.
+ */
+ $defaults = apply_filters( 'convertkit_settings_mcp_get_defaults', $defaults );
+
+ return $defaults;
+
+ }
+
+ /**
+ * Saves the given array of settings to the WordPress options table.
+ *
+ * @since 3.4.0
+ *
+ * @param array $settings Settings.
+ */
+ public function save( $settings ) {
+
+ update_option( self::SETTINGS_NAME, array_merge( $this->get(), $settings ) );
+
+ }
+
+}
diff --git a/includes/class-wp-convertkit.php b/includes/class-wp-convertkit.php
index 63cfa5263..1e358c92f 100644
--- a/includes/class-wp-convertkit.php
+++ b/includes/class-wp-convertkit.php
@@ -64,6 +64,7 @@ public function initialize() {
$this->initialize_cli_cron();
$this->initialize_frontend();
$this->initialize_global();
+ $this->initialize_mcp();
}
@@ -218,6 +219,49 @@ private function initialize_global() {
}
+ /**
+ * Initializes the MCP server if enabled in the Plugin's settings.
+ *
+ * @since 3.4.0
+ */
+ public function initialize_mcp() {
+
+ // Bail if the MCP server is not enabled.
+ $settings = new ConvertKit_Settings_MCP();
+ if ( ! $settings->enabled() ) {
+ return;
+ }
+
+ // Bail if the Abilities API is unavailable (WordPress < 6.9).
+ if ( ! function_exists( 'wp_register_ability' ) ) {
+ return;
+ }
+
+ // Bail if PHP 7.4+ is not installed, as this is required for the MCP Adapter classes.
+ if ( version_compare( PHP_VERSION, '7.4', '<' ) ) {
+ return;
+ }
+
+ // Bail if the WordPress MCP Adapter autoloader is missing.
+ if ( ! file_exists( CONVERTKIT_PLUGIN_PATH . '/vendor/autoload.php' ) ) {
+ return;
+ }
+
+ // Load MCP Adapter.
+ require_once CONVERTKIT_PLUGIN_PATH . '/vendor/autoload.php';
+
+ // Bail if the MCP Adapter class doesn't exist - something went wrong with the autoloader.
+ if ( ! class_exists( 'WP\\MCP\\Core\\McpAdapter' ) ) {
+ return;
+ }
+
+ // Bootstrap the MCP Adapter, per WordPress/mcp-adapter's recommended
+ // integration pattern.
+ // @see https://github.com/WordPress/mcp-adapter#using-mcp-adapter-in-your-plugin.
+ \WP\MCP\Core\McpAdapter::instance();
+
+ }
+
/**
* Runs the Plugin's initialization and update routines, which checks if
* the Plugin has just been updated to a newer version,
diff --git a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-delete.php b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-delete.php
index fc21b383a..c0081e9e9 100644
--- a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-delete.php
+++ b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-delete.php
@@ -51,7 +51,7 @@ public function get_label() {
return sprintf(
/* translators: %s: block title */
- __( 'Delete an existing %s element from a post', 'convertkit' ),
+ __( 'Delete Existing %s from a Post, Page or Custom Post', 'convertkit' ),
$this->block->get_title()
);
@@ -67,10 +67,9 @@ public function get_label() {
public function get_description() {
return sprintf(
- /* translators: 1: block full name e.g. convertkit/form, 2: block title */
- __( 'Removes a single occurrence of the %1$s (%2$s) element from the given post.', 'convertkit' ),
- 'convertkit/' . $this->block->get_name(),
- $this->block->get_title()
+ /* translators: Block Name */
+ __( 'Removes an existing %s from a Post, Page or Custom Post using the supplied zero-based occurrence index.', 'convertkit' ),
+ $this->block->get_title_plural()
);
}
diff --git a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-insert.php b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-insert.php
index 5c14151f7..d705ec571 100644
--- a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-insert.php
+++ b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-insert.php
@@ -42,7 +42,7 @@ public function get_label() {
return sprintf(
/* translators: %s: block title */
- __( 'Insert a %s element into a post', 'convertkit' ),
+ __( 'Insert %s into a Page, Post or Custom Post', 'convertkit' ),
$this->block->get_title()
);
@@ -59,9 +59,8 @@ public function get_description() {
return sprintf(
/* translators: 1: block full name e.g. convertkit/form, 2: block title */
- __( 'Inserts a new %1$s (%2$s) element into the given post\'s content. The element can be appended (default), prepended, or positioned relative to an existing element using a zero-based index.', 'convertkit' ),
- 'convertkit/' . $this->block->get_name(),
- $this->block->get_title()
+ __( 'Inserts a new %s in a Page, Post or Custom Post\'s content. The element can be appended (default), prepended, or inserted relative to an existing element using a zero-based index.', 'convertkit' ),
+ $this->block->get_title_plural()
);
}
diff --git a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-list.php b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-list.php
index d0fcf89d1..8f0685d01 100644
--- a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-list.php
+++ b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-list.php
@@ -60,8 +60,8 @@ public function get_label() {
return sprintf(
/* translators: %s: block title */
- __( 'List %s elements in a post', 'convertkit' ),
- $this->block->get_title()
+ __( 'List %s in a Post, Page or Custom Post', 'convertkit' ),
+ $this->block->get_title_plural()
);
}
@@ -76,10 +76,9 @@ public function get_label() {
public function get_description() {
return sprintf(
- /* translators: 1: block full name e.g. convertkit/form, 2: block title */
- __( 'Lists every occurrence of the %1$s (%2$s) element in the given post, including each occurrence\'s zero-based index and current attribute values.', 'convertkit' ),
- 'convertkit/' . $this->block->get_name(),
- $this->block->get_title()
+ /* translators: Block Name */
+ __( 'Lists every %s in the given Post, Page or Custom Post, including each occurrence\'s zero-based index and current attribute values.', 'convertkit' ),
+ $this->block->get_title_plural()
);
}
@@ -131,14 +130,14 @@ public function get_output_schema() {
'type' => 'array',
'items' => array(
'type' => 'object',
- 'required' => array( 'index', 'attrs' ),
+ 'required' => array( 'occurrence_index', 'attrs' ),
'properties' => array(
- 'index' => array(
+ 'occurrence_index' => array(
'type' => 'integer',
'minimum' => 0,
'description' => __( 'Zero-based occurrence index among this element\'s appearances in the post.', 'convertkit' ),
),
- 'attrs' => array(
+ 'attrs' => array(
'type' => 'object',
'description' => __( 'Element attributes for this occurrence.', 'convertkit' ),
),
diff --git a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-update.php b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-update.php
index d7c73ca47..a614f66c9 100644
--- a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-update.php
+++ b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content-update.php
@@ -51,7 +51,7 @@ public function get_label() {
return sprintf(
/* translators: %s: block title */
- __( 'Update an existing %s element in a post', 'convertkit' ),
+ __( 'Update Existing %s in a Page, Post or Custom Post', 'convertkit' ),
$this->block->get_title()
);
@@ -67,10 +67,9 @@ public function get_label() {
public function get_description() {
return sprintf(
- /* translators: 1: block full name e.g. convertkit/form, 2: block title */
- __( 'Updates the attributes of a single occurrence of the %1$s (%2$s) element in the given post. By default the provided attributes are merged into the existing attributes.', 'convertkit' ),
- 'convertkit/' . $this->block->get_name(),
- $this->block->get_title()
+ /* translators: Block Name */
+ __( 'Updates the attributes of an existing %s in a Page, Post or Custom Post. The provided attributes are merged into the existing attributes.', 'convertkit' ),
+ $this->block->get_title_plural()
);
}
diff --git a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content.php b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content.php
index 8abfcea81..539ef3e36 100644
--- a/includes/mcp/abilities/content/class-convertkit-mcp-ability-content.php
+++ b/includes/mcp/abilities/content/class-convertkit-mcp-ability-content.php
@@ -108,7 +108,7 @@ public function get_output_schema() {
return array(
'type' => 'object',
- 'required' => array( 'post_id', 'occurrence_index', 'index' ),
+ 'required' => array( 'post_id', 'occurrence_index' ),
'properties' => array(
'post_id' => array(
'type' => 'integer',
@@ -116,11 +116,7 @@ public function get_output_schema() {
),
'occurrence_index' => array(
'type' => 'integer',
- 'description' => __( 'The zero-based occurrence index of the block in the post.', 'convertkit' ),
- ),
- 'index' => array(
- 'type' => 'integer',
- 'description' => __( 'The zero-based index of the block in the post.', 'convertkit' ),
+ 'description' => __( 'The zero-based occurrence index of the Kit element in the post.', 'convertkit' ),
),
),
);
@@ -169,6 +165,9 @@ private function get_input_schema_property_type( $field ) {
switch ( $type ) {
case 'resource':
+ case 'text':
+ case 'color':
+ case 'select':
return 'string';
case 'number':
@@ -178,7 +177,8 @@ private function get_input_schema_property_type( $field ) {
return 'boolean';
default:
- return $type;
+ // Unknown field type — fall back to string.
+ return 'string';
}
}
diff --git a/includes/mcp/abilities/resources/class-convertkit-mcp-ability-resource-forms.php b/includes/mcp/abilities/resources/class-convertkit-mcp-ability-resource-forms.php
new file mode 100644
index 000000000..14c91b206
--- /dev/null
+++ b/includes/mcp/abilities/resources/class-convertkit-mcp-ability-resource-forms.php
@@ -0,0 +1,133 @@
+ (int) ( $item['id'] ?? 0 ),
+ 'name' => (string) ( $item['name'] ?? '' ),
+ 'format' => isset( $item['format'] ) && $item['format'] !== '' ? (string) $item['format'] : 'inline',
+ );
+
+ }
+
+ /**
+ * Returns the JSON Schema for a single Form item, including the `format`
+ * field added by map_item().
+ *
+ * @since 3.4.0
+ *
+ * @return array
+ */
+ protected function get_item_schema() {
+
+ return array(
+ 'type' => 'object',
+ 'required' => array( 'id', 'name', 'format' ),
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Numeric ID of the Kit Form.', 'convertkit' ),
+ ),
+ 'name' => array(
+ 'type' => 'string',
+ 'description' => __( 'Human-readable name of the Kit Form.', 'convertkit' ),
+ ),
+ 'format' => array(
+ 'type' => 'string',
+ 'enum' => array( 'inline', 'modal', 'slide in', 'sticky bar' ),
+ 'description' => __( 'Where and how the Form is displayed. Inline forms render in post content; modal / slide in / sticky bar forms are site-wide overlays triggered elsewhere.', 'convertkit' ),
+ ),
+ ),
+ );
+
+ }
+
+}
diff --git a/includes/mcp/abilities/resources/class-convertkit-mcp-ability-resource-landing-pages.php b/includes/mcp/abilities/resources/class-convertkit-mcp-ability-resource-landing-pages.php
new file mode 100644
index 000000000..be0d05def
--- /dev/null
+++ b/includes/mcp/abilities/resources/class-convertkit-mcp-ability-resource-landing-pages.php
@@ -0,0 +1,73 @@
+get_resource() . '-list';
+
+ }
+
+ /**
+ * Returns the resource slug for this ability, used in the ability name
+ * and as a hint for clients (e.g. `forms`, `tags`, `landing-pages`,
+ * `products`).
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ abstract protected function get_resource();
+
+ /**
+ * Returns the fully-qualified class name of the ConvertKit_Resource_*
+ * implementation backing this ability.
+ *
+ * @since 3.4.0
+ *
+ * @return string
+ */
+ abstract protected function get_resource_class();
+
+ /**
+ * Maps a single raw resource item from the resource class' get() method
+ * into the shape exposed in this ability's output.
+ *
+ * The default implementation returns just id and name. Subclasses may
+ * override to expose additional per-item fields (e.g. Forms includes
+ * `format`) — output_schema() should be overridden to match.
+ *
+ * @since 3.4.0
+ *
+ * @param array $item Raw item from the resource class' get() method.
+ * @return array
+ */
+ protected function map_item( $item ) {
+
+ return array(
+ 'id' => (int) ( $item['id'] ?? 0 ),
+ 'name' => (string) ( $item['name'] ?? '' ),
+ );
+
+ }
+
+ /**
+ * Returns the JSON Schema describing a single item in the output `items`
+ * array.
+ *
+ * Subclasses may override to add per-resource fields. Keep in sync with
+ * map_item() — both describe the same shape, one in schema form and one
+ * in PHP.
+ *
+ * @since 3.4.0
+ *
+ * @return array
+ */
+ protected function get_item_schema() {
+
+ return array(
+ 'type' => 'object',
+ 'required' => array( 'id', 'name' ),
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Numeric ID of the resource item.', 'convertkit' ),
+ ),
+ 'name' => array(
+ 'type' => 'string',
+ 'description' => __( 'Human-readable name of the resource item.', 'convertkit' ),
+ ),
+ ),
+ );
+
+ }
+
+ /**
+ * Permission callback for resource-list abilities.
+ *
+ * Listing available Kit resources is permitted for anyone who can edit
+ * posts — the same capability gate that allows placing a Kit element on
+ * a post, where these lists are typically used as a lookup.
+ *
+ * @since 3.4.0
+ *
+ * @param array $input Ability input (unused).
+ * @return bool|WP_Error
+ */
+ public function permission_callback( $input ) {
+
+ if ( ! current_user_can( 'edit_posts' ) ) {
+ return new WP_Error(
+ 'convertkit_mcp_cannot_list_resources',
+ __( 'You do not have permission to list Kit resources.', 'convertkit' )
+ );
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Returns the ability's input JSON Schema.
+ *
+ * Resource-list abilities take no input.
+ *
+ * @since 3.4.0
+ *
+ * @return array
+ */
+ public function get_input_schema() {
+
+ return array(
+ 'type' => 'object',
+ 'properties' => new stdClass(),
+ );
+
+ }
+
+ /**
+ * Returns the ability's output JSON Schema.
+ *
+ * @since 3.4.0
+ *
+ * @return array
+ */
+ public function get_output_schema() {
+
+ return array(
+ 'type' => 'object',
+ 'required' => array( 'count', 'items' ),
+ 'properties' => array(
+ 'count' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ 'description' => __( 'The number of items returned.', 'convertkit' ),
+ ),
+ 'items' => array(
+ 'type' => 'array',
+ 'description' => __( 'The resource items.', 'convertkit' ),
+ 'items' => $this->get_item_schema(),
+ ),
+ ),
+ );
+
+ }
+
+ /**
+ * Executes the ability: instantiate the backing resource class, fetch
+ * its cached items, and return them mapped to this ability's output
+ * shape.
+ *
+ * A "no items" result (e.g. the Plugin has not yet cached this resource
+ * from the Kit API) is returned as a successful empty list rather than
+ * an error, so the model can explain the absence to the user.
+ *
+ * @since 3.4.0
+ *
+ * @param array $input Ability input (unused).
+ * @return array|WP_Error
+ */
+ public function execute_callback( $input ) {
+
+ // Instantiate the backing resource class.
+ $resource_class = $this->get_resource_class();
+ if ( ! class_exists( $resource_class ) ) {
+ return new WP_Error(
+ 'convertkit_mcp_resource_class_missing',
+ sprintf(
+ /* translators: %s: Resource class name */
+ __( 'The resource class "%s" does not exist.', 'convertkit' ),
+ $resource_class
+ )
+ );
+ }
+
+ $resource = new $resource_class();
+
+ // Fetch the items from the resource cache. ConvertKit_Resource::get()
+ // returns false when nothing has been cached; normalise that to an
+ // empty array so the output shape is always consistent.
+ $items = $resource->get();
+ if ( ! is_array( $items ) ) {
+ $items = array();
+ }
+
+ // Map each raw item to the ability's output shape.
+ $mapped = array();
+ foreach ( $items as $item ) {
+ $mapped[] = $this->map_item( $item );
+ }
+
+ return array(
+ 'count' => count( $mapped ),
+ 'items' => $mapped,
+ );
+
+ }
+
+}
diff --git a/includes/mcp/class-convertkit-mcp.php b/includes/mcp/class-convertkit-mcp.php
index 05e3dd3df..33cec9fe2 100644
--- a/includes/mcp/class-convertkit-mcp.php
+++ b/includes/mcp/class-convertkit-mcp.php
@@ -37,7 +37,7 @@ class ConvertKit_MCP {
*
* @var string
*/
- const SERVER_ID = 'kit-mcp';
+ const SERVER_ID = 'kit/mcp';
/**
* The REST namespace used by the MCP server.
@@ -46,7 +46,7 @@ class ConvertKit_MCP {
*
* @var string
*/
- const SERVER_NAMESPACE = 'kit-mcp';
+ const SERVER_NAMESPACE = 'kit/mcp';
/**
* The REST version number used by the MCP server.
@@ -64,22 +64,46 @@ class ConvertKit_MCP {
*/
public function __construct() {
- // Bail if the Abilities API is unavailable (WordPress < 6.9).
- if ( ! function_exists( 'wp_register_ability' ) ) {
- return;
- }
-
// Register the ability category.
add_action( 'wp_abilities_api_categories_init', array( $this, 'register_abilities_category' ) );
// Register abilities.
add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) );
+ // Register resource-list abilities (Forms, Tags, Landing Pages, Products).
+ // These are owned by the Plugin (not by any single block or feature),
+ // so they're added here rather than via a per-class register_abilities().
+ add_filter( 'convertkit_abilities', array( $this, 'register_resource_abilities' ) );
+
// Register the MCP server.
add_action( 'mcp_adapter_init', array( $this, 'register_mcp_server' ) );
}
+ /**
+ * Appends the resource-list abilities (Forms, Tags, Landing Pages,
+ * Products) to the convertkit_abilities filter, so they are registered
+ * with the Abilities API and exposed via the MCP server.
+ *
+ * @since 3.4.0
+ *
+ * @param array $abilities Abilities to register.
+ * @return array
+ */
+ public function register_resource_abilities( $abilities ) {
+
+ return array_merge(
+ $abilities,
+ array(
+ 'kit/forms-list' => new ConvertKit_MCP_Ability_Resource_Forms(),
+ 'kit/tags-list' => new ConvertKit_MCP_Ability_Resource_Tags(),
+ 'kit/landing-pages-list' => new ConvertKit_MCP_Ability_Resource_Landing_Pages(),
+ 'kit/products-list' => new ConvertKit_MCP_Ability_Resource_Products(),
+ )
+ );
+
+ }
+
/**
* Register the 'kit' ability category.
*
@@ -150,7 +174,7 @@ public function register_mcp_server( $adapter ) {
self::SERVER_ID,
self::SERVER_NAMESPACE,
self::SERVER_ROUTE,
- __( 'Kit MCP', 'convertkit' ),
+ __( 'Kit WordPress Plugin MCP', 'convertkit' ),
__( 'Exposes Kit Plugin abilities over the Model Context Protocol.', 'convertkit' ),
'1.0.0',
array( 'WP\\MCP\\Transport\\HttpTransport' ),
diff --git a/tests/EndToEnd.suite.yml b/tests/EndToEnd.suite.yml
index 85037bdcf..0fdb63bbb 100644
--- a/tests/EndToEnd.suite.yml
+++ b/tests/EndToEnd.suite.yml
@@ -41,6 +41,7 @@ modules:
- \Tests\Support\Helper\WPGutenberg
- \Tests\Support\Helper\WPMetabox
- \Tests\Support\Helper\WPNotices
+ - \Tests\Support\Helper\WPRestAPI
- \Tests\Support\Helper\WPQuickEdit
- \Tests\Support\Helper\WPWidget
- \Tests\Support\Helper\Xdebug
diff --git a/tests/EndToEnd/general/plugin-screens/PluginSettingsMCPCest.php b/tests/EndToEnd/general/plugin-screens/PluginSettingsMCPCest.php
new file mode 100644
index 000000000..3d7a009ea
--- /dev/null
+++ b/tests/EndToEnd/general/plugin-screens/PluginSettingsMCPCest.php
@@ -0,0 +1,94 @@
+ Kit > MCP.
+ *
+ * @since 3.4.0
+ */
+class PluginSettingsMCPCest
+{
+ /**
+ * Run common actions before running the test functions in this class.
+ *
+ * @since 3.4.0
+ *
+ * @param EndToEndTester $I Tester.
+ */
+ public function _before(EndToEndTester $I)
+ {
+ // Activate Kit Plugin.
+ $I->activateKitPlugin($I);
+
+ // Setup Plugin.
+ $I->setupKitPlugin($I);
+ }
+
+ /**
+ * Tests that enabling and disabling the MCP server setting works with no errors.
+ *
+ * @since 3.4.0
+ *
+ * @param EndToEndTester $I Tester.
+ */
+ public function testEnableAndDisableMCPServerSetting(EndToEndTester $I)
+ {
+ // Check that the MCP server is not registered.
+ $I->doesNotHaveRoute($I, '/kit-mcp');
+
+ // Go to the Plugin's MCP Screen.
+ $I->loadKitSettingsMCPScreen($I);
+
+ // Enable MCP server.
+ $I->checkOption('#enabled');
+ $I->click('Save Changes');
+
+ // Check that no PHP warnings or notices were output.
+ $I->checkNoWarningsAndNoticesOnScreen($I);
+
+ // Check that the MCP server is enabled.
+ $I->waitForElementVisible('#enabled');
+ $I->seeCheckboxIsChecked('#enabled');
+
+ // Check that the MCP server is registered.
+ $I->hasRoute($I, '/kit/mcp');
+ $I->hasRoute($I, '/kit/mcp/v1');
+
+ // Disable MCP server.
+ $I->uncheckOption('#enabled');
+ $I->click('Save Changes');
+
+ // Check that no PHP warnings or notices were output.
+ $I->checkNoWarningsAndNoticesOnScreen($I);
+
+ // Check that the MCP server is disabled.
+ $I->waitForElementVisible('#enabled');
+ $I->dontSeeCheckboxIsChecked('#enabled');
+
+ // Go to the Plugin's MCP Screen.
+ $I->loadKitSettingsMCPScreen($I);
+ $I->wait(2);
+
+ // Check that the MCP server is not registered.
+ $I->doesNotHaveRoute($I, '/kit/mcp');
+ $I->doesNotHaveRoute($I, '/kit/mcp/v1');
+ }
+
+ /**
+ * Deactivate and reset Plugin(s) after each test, if the test passes.
+ * We don't use _after, as this would provide a screenshot of the Plugin
+ * deactivation and not the true test error.
+ *
+ * @since 3.4.0
+ *
+ * @param EndToEndTester $I Tester.
+ */
+ public function _passed(EndToEndTester $I)
+ {
+ $I->deactivateKitPlugin($I);
+ $I->resetKitPlugin($I);
+ }
+}
diff --git a/tests/Integration/BlockPostHelperTest.php b/tests/Integration/BlockPostHelperTest.php
index ac34dc25a..020c2bc0d 100644
--- a/tests/Integration/BlockPostHelperTest.php
+++ b/tests/Integration/BlockPostHelperTest.php
@@ -99,12 +99,10 @@ public function testFind()
$this->assertCount( 2, $blocks );
// Assert first matching block indicies and attributes are correct.
- $this->assertEquals( $this->formBlockIndices[0], $blocks[0]['index'] );
$this->assertEquals( 0, $blocks[0]['occurrence_index'] );
$this->assertEquals( $_ENV['CONVERTKIT_API_FORM_ID'], $blocks[0]['attrs']['form'] );
// Assert second matching block indicies and attributes are correct.
- $this->assertEquals( $this->formBlockIndices[1], $blocks[1]['index'] );
$this->assertEquals( 1, $blocks[1]['occurrence_index'] );
$this->assertEquals( $_ENV['CONVERTKIT_API_FORM_ID'], $blocks[1]['attrs']['form'] );
}
@@ -146,9 +144,13 @@ public function testInsertPrepend()
position: 'prepend'
);
+ // Confirm result is an array and the post ID is correct.
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( 0, $result['index'] );
+
+ // Confirm content has been updated and the block is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringStartsWith( '', $post->post_content );
}
/**
@@ -166,9 +168,13 @@ public function testInsertAppend()
position: 'append'
);
+ // Confirm result is an array and the post ID is correct.
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( $this->totalBlocks + 1, $result['index'] );
+
+ // Confirm content has been updated and the block is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringEndsWith( '', $post->post_content );
}
/**
@@ -186,9 +192,37 @@ public function testInsertIndex()
index: 1
);
+ // Confirm result is an array and the post ID is correct.
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( 1, $result['index'] );
+
+ // Confirm content has been updated and the block is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringContainsString( "\n
Item #1
\n', $post->post_content );
+ }
+
+ /**
+ * Test that the insert() method inserts a new block at the specified index position.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertIndexZero()
+ {
+ $result = \ConvertKit_Block_Post_Helper::insert(
+ post_id: $this->postID,
+ block_name: 'convertkit/form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'index',
+ index: 0
+ );
+
+ // Confirm result is an array and the post ID is correct.
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ // Confirm content has been updated and the block is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringStartsWith( '', $post->post_content );
}
/**
@@ -207,14 +241,17 @@ public function testInsertIndexOutOfBounds()
index: 100
);
+ // Confirm result is an array and the post ID is correct.
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( $this->totalBlocks + 1, $result['index'] );
+
+ // Confirm content has been updated and the block is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringEndsWith( '', $post->post_content );
}
/**
- * Test that the insert() method inserts a new block at the beginning of the content when
- * the index is negative.
+ * Test that the insert() method returns a WP_Error when the index is negative.
*
* @since 3.4.0
*/
@@ -227,10 +264,7 @@ public function testInsertIndexNegative()
position: 'index',
index: -1
);
-
- $this->assertIsArray( $result );
- $this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( 0, $result['index'] );
+ $this->assertInstanceOf(\WP_Error::class, $result );
}
/**
@@ -266,7 +300,6 @@ public function testUpdate()
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( $this->formBlockIndices[0], $result['index'] );
$result = \ConvertKit_Block_Post_Helper::update(
post_id: $this->postID,
@@ -277,7 +310,6 @@ public function testUpdate()
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( $this->formBlockIndices[1], $result['index'] );
}
/**
@@ -326,7 +358,6 @@ public function testDelete()
);
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( $this->formBlockIndices[1], $result['index'] );
$result = \ConvertKit_Block_Post_Helper::delete(
post_id: $this->postID,
@@ -335,7 +366,6 @@ public function testDelete()
);
$this->assertIsArray( $result );
$this->assertEquals( $this->postID, $result['post_id'] );
- $this->assertEquals( $this->formBlockIndices[0], $result['index'] );
}
/**
diff --git a/tests/Integration/MCPContentBroadcastsTest.php b/tests/Integration/MCPContentBroadcastsTest.php
new file mode 100644
index 000000000..1d2a6a1f7
--- /dev/null
+++ b/tests/Integration/MCPContentBroadcastsTest.php
@@ -0,0 +1,368 @@
+postID = $this->createPostWithBroadcastsBlocks();
+ }
+
+ /**
+ * Performs actions after each test.
+ *
+ * @since 3.4.0
+ */
+ public function tearDown(): void
+ {
+ // Restore the current user.
+ wp_set_current_user(0);
+
+ // Deactivate Plugin.
+ deactivate_plugins('convertkit/wp-convertkit.php');
+
+ parent::tearDown();
+ }
+
+ /**
+ * The ability names registered by the Broadcasts block.
+ *
+ * @since 3.4.0
+ *
+ * @var string[]
+ */
+ private const BROADCASTS_ABILITY_NAMES = array(
+ 'kit/broadcasts-list',
+ 'kit/broadcasts-insert',
+ 'kit/broadcasts-update',
+ 'kit/broadcasts-delete',
+ );
+
+ /**
+ * Test that the Broadcasts block registers all four content abilities via
+ * the convertkit_abilities filter with the expected names.
+ *
+ * @since 3.4.0
+ */
+ public function testAbilitiesRegistered()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // The ability names and classes expected to be registered.
+ $expected = array(
+ 'kit/broadcasts-list' => \ConvertKit_MCP_Ability_Content_List::class,
+ 'kit/broadcasts-insert' => \ConvertKit_MCP_Ability_Content_Insert::class,
+ 'kit/broadcasts-update' => \ConvertKit_MCP_Ability_Content_Update::class,
+ 'kit/broadcasts-delete' => \ConvertKit_MCP_Ability_Content_Delete::class,
+ );
+
+ // Assert that the abilities are registered and are instances of the expected classes.
+ foreach ( $expected as $name => $class ) {
+ $this->assertArrayHasKey($name, $abilities);
+ $this->assertInstanceOf($class, $abilities[ $name ]);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a user who cannot edit the
+ * given post.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutEditPostCapability()
+ {
+ // Become a Subscriber (no edit_post capability).
+ $subscriber_id = static::factory()->user->create([ 'role' => 'subscriber' ]);
+ wp_set_current_user($subscriber_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::BROADCASTS_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a request with no post_id,
+ * with a clear error code.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutPostId()
+ {
+ // Become an Administrator (has every capability, so the only thing
+ // that can fail here is the missing post_id check).
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::BROADCASTS_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() permits an Administrator on a
+ * valid post_id.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackPermitsAdministrator()
+ {
+ // Become an Administrator.
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission granted.
+ foreach ( self::BROADCASTS_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $this->assertTrue($abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]));
+ }
+ }
+
+ /**
+ * Test that kit/broadcasts-list returns every Broadcasts block occurrence
+ * in the post.
+ *
+ * @since 3.4.0
+ */
+ public function testListReturnsAllBroadcastsOccurrencesInPost()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/broadcasts-list']->execute_callback([ 'post_id' => $this->postID ]);
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['count']);
+ $this->assertCount(2, $result['occurrences']);
+
+ // Each occurrence carries an occurrence_index and an attrs object
+ // holding the limit attribute from the seeded post content.
+ foreach ($result['occurrences'] as $i => $occurrence) {
+ $this->assertSame($i, $occurrence['occurrence_index']);
+ $this->assertArrayHasKey('attrs', $occurrence);
+ $this->assertSame(5, (int) $occurrence['attrs']['limit']);
+ }
+ }
+
+ /**
+ * Test that kit/broadcasts-insert appends a new Broadcasts block to the
+ * post, and returns the new occurrence_index.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertAppendsBroadcastsBlock()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/broadcasts-insert']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'attrs' => array(
+ 'limit' => 3,
+ 'display_image' => true,
+ ),
+ 'position' => 'append',
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['occurrence_index']);
+
+ // Confirm the post now contains three Broadcasts blocks.
+ $listed = $abilities['kit/broadcasts-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(3, $listed['count']);
+
+ // Confirm the newly inserted block carries the attrs we passed in.
+ $this->assertSame(3, (int) $listed['occurrences'][2]['attrs']['limit']);
+ $this->assertTrue( (bool) $listed['occurrences'][2]['attrs']['display_image']);
+ }
+
+ /**
+ * Test that kit/broadcasts-update changes the attrs of a specific
+ * occurrence, leaving other occurrences untouched.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateModifiesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Update the second Broadcasts block (occurrence_index 1) to a different limit.
+ $result = $abilities['kit/broadcasts-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 1,
+ 'attrs' => array( 'limit' => 25 ),
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(1, $result['occurrence_index']);
+
+ // Re-list and confirm: occurrence 0 unchanged, occurrence 1 has the new limit.
+ $listed = $abilities['kit/broadcasts-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(
+ 5,
+ (int) $listed['occurrences'][0]['attrs']['limit'],
+ 'kit/broadcasts-update must not modify other occurrences.'
+ );
+ $this->assertSame(
+ 25,
+ (int) $listed['occurrences'][1]['attrs']['limit'],
+ 'kit/broadcasts-update did not apply the new limit to the requested occurrence.'
+ );
+ }
+
+ /**
+ * Test that kit/broadcasts-delete removes a specific occurrence and the
+ * post now contains one fewer Broadcasts block.
+ *
+ * @since 3.4.0
+ */
+ public function testDeleteRemovesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/broadcasts-delete']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 0,
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(0, $result['occurrence_index']);
+
+ // Confirm the post now contains a single Broadcasts block.
+ $listed = $abilities['kit/broadcasts-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(1, $listed['count']);
+ }
+
+ /**
+ * Test that kit/broadcasts-update returns a WP_Error when asked to update
+ * an occurrence that does not exist, rather than silently mutating
+ * something else.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateOnMissingOccurrenceReturnsError()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/broadcasts-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 99,
+ 'attrs' => array( 'limit' => 5 ),
+ )
+ );
+
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+
+ /**
+ * Creates a Post containing two convertkit/broadcasts blocks interleaved
+ * with non-Kit blocks, mirroring the fixture used by BlockPostHelperTest.
+ *
+ * @since 3.4.0
+ *
+ * @return int
+ */
+ private function createPostWithBroadcastsBlocks(): int
+ {
+ return $this->factory->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_title' => 'Broadcasts Abilities Fixture',
+ 'post_content' => '
+
Intro paragraph.
+
+
+
+
+
+
Middle paragraph.
+
+
+
+
+
+
Closing paragraph.
+',
+ )
+ );
+ }
+}
diff --git a/tests/Integration/MCPContentFormTest.php b/tests/Integration/MCPContentFormTest.php
new file mode 100644
index 000000000..1bad4ba47
--- /dev/null
+++ b/tests/Integration/MCPContentFormTest.php
@@ -0,0 +1,366 @@
+postID = $this->createPostWithFormBlocks();
+ }
+
+ /**
+ * Performs actions after each test.
+ *
+ * @since 3.4.0
+ */
+ public function tearDown(): void
+ {
+ // Restore the current user.
+ wp_set_current_user(0);
+
+ // Deactivate Plugin.
+ deactivate_plugins('convertkit/wp-convertkit.php');
+
+ parent::tearDown();
+ }
+
+ /**
+ * The ability names registered by the Form block.
+ *
+ * @since 3.4.0
+ *
+ * @var string[]
+ */
+ private const FORM_ABILITY_NAMES = array(
+ 'kit/form-list',
+ 'kit/form-insert',
+ 'kit/form-update',
+ 'kit/form-delete',
+ );
+
+ /**
+ * Test that the Form block registers all four content abilities via the
+ * convertkit_abilities filter with the expected names.
+ *
+ * @since 3.4.0
+ */
+ public function testAbilitiesRegistered()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // The ability names and classes expected to be registered.
+ $expected = array(
+ 'kit/form-list' => \ConvertKit_MCP_Ability_Content_List::class,
+ 'kit/form-insert' => \ConvertKit_MCP_Ability_Content_Insert::class,
+ 'kit/form-update' => \ConvertKit_MCP_Ability_Content_Update::class,
+ 'kit/form-delete' => \ConvertKit_MCP_Ability_Content_Delete::class,
+ );
+
+ // Assert that the abilities are registered and are instances of the expected classes.
+ foreach ( $expected as $name => $class ) {
+ $this->assertArrayHasKey($name, $abilities);
+ $this->assertInstanceOf($class, $abilities[ $name ]);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a user who cannot edit the
+ * given post.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutEditPostCapability()
+ {
+ // Become a Subscriber (no edit_post capability).
+ $subscriber_id = static::factory()->user->create([ 'role' => 'subscriber' ]);
+ wp_set_current_user($subscriber_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::FORM_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a request with no post_id,
+ * with a clear error code.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutPostId()
+ {
+ // Become an Administrator (has every capability, so the only thing
+ // that can fail here is the missing post_id check).
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::FORM_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() permits an Administrator on a
+ * valid post_id.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackPermitsAdministrator()
+ {
+ // Become an Administrator.
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission granted.
+ foreach ( self::FORM_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $this->assertTrue($abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]));
+ }
+ }
+
+ /**
+ * Test that kit/form-list returns every Form block occurrence in the
+ * post, with shape { post_id, count, occurrences: [{occurrence_index, attrs}] }.
+ *
+ * @since 3.4.0
+ */
+ public function testListReturnsAllFormOccurrencesInPost()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/form-list']->execute_callback([ 'post_id' => $this->postID ]);
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['count']);
+ $this->assertCount(2, $result['occurrences']);
+
+ // Each occurrence carries an occurrence_index and an attrs object
+ // holding the form ID from the seeded post content.
+ foreach ($result['occurrences'] as $i => $occurrence) {
+ $this->assertSame($i, $occurrence['occurrence_index']);
+ $this->assertArrayHasKey('attrs', $occurrence);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_FORM_ID'],
+ (string) $occurrence['attrs']['form']
+ );
+ }
+ }
+
+ /**
+ * Test that kit/form-insert appends a new Form block to the post, and
+ * returns the new occurrence_index.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertAppendsFormBlock()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/form-insert']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'attrs' => array( 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ),
+ 'position' => 'append',
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['occurrence_index']);
+
+ // Confirm the post now contains three Form blocks.
+ $listed = $abilities['kit/form-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(3, $listed['count']);
+ }
+
+ /**
+ * Test that kit/form-update changes the attrs of a specific occurrence,
+ * leaving other occurrences untouched.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateModifiesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Update the second Form block (occurrence_index 1) to a different form ID.
+ $new_form_id = (string) ( (int) $_ENV['CONVERTKIT_API_FORM_ID'] + 1 );
+ $result = $abilities['kit/form-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 1,
+ 'attrs' => array( 'form' => $new_form_id ),
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(1, $result['occurrence_index']);
+
+ // Re-list and confirm: occurrence 0 unchanged, occurrence 1 has the new form ID.
+ $listed = $abilities['kit/form-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_FORM_ID'],
+ (string) $listed['occurrences'][0]['attrs']['form'],
+ 'kit/form-update must not modify other occurrences.'
+ );
+ $this->assertSame(
+ $new_form_id,
+ (string) $listed['occurrences'][1]['attrs']['form'],
+ 'kit/form-update did not apply the new form ID to the requested occurrence.'
+ );
+ }
+
+ /**
+ * Test that kit/form-delete removes a specific occurrence and the post
+ * now contains one fewer Form block.
+ *
+ * @since 3.4.0
+ */
+ public function testDeleteRemovesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/form-delete']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 0,
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(0, $result['occurrence_index']);
+
+ // Confirm the post now contains a single Form block.
+ $listed = $abilities['kit/form-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(1, $listed['count']);
+ }
+
+ /**
+ * Test that kit/form-update returns a WP_Error when asked to update an
+ * occurrence that does not exist, rather than silently mutating
+ * something else.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateOnMissingOccurrenceReturnsError()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/form-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 99,
+ 'attrs' => array( 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ),
+ )
+ );
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+
+ /**
+ * Creates a Post containing two convertkit/form blocks interleaved with
+ * non-Kit blocks, mirroring the fixture used by BlockPostHelperTest.
+ *
+ * @since 3.4.0
+ *
+ * @return int
+ */
+ private function createPostWithFormBlocks(): int
+ {
+ return $this->factory->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_title' => 'Form Abilities Fixture',
+ 'post_content' => '
+
Intro paragraph.
+
+
+
+
+
+
Middle paragraph.
+
+
+
+
+
+
Closing paragraph.
+',
+ )
+ );
+ }
+}
diff --git a/tests/Integration/MCPContentFormTriggerTest.php b/tests/Integration/MCPContentFormTriggerTest.php
new file mode 100644
index 000000000..afceca369
--- /dev/null
+++ b/tests/Integration/MCPContentFormTriggerTest.php
@@ -0,0 +1,366 @@
+postID = $this->createPostWithFormTriggerBlocks();
+ }
+
+ /**
+ * Performs actions after each test.
+ *
+ * @since 3.4.0
+ */
+ public function tearDown(): void
+ {
+ // Restore the current user.
+ wp_set_current_user(0);
+
+ // Deactivate Plugin.
+ deactivate_plugins('convertkit/wp-convertkit.php');
+
+ parent::tearDown();
+ }
+
+ /**
+ * The ability names registered by the Form Trigger block.
+ *
+ * @since 3.4.0
+ *
+ * @var string[]
+ */
+ private const FORM_TRIGGER_ABILITY_NAMES = array(
+ 'kit/formtrigger-list',
+ 'kit/formtrigger-insert',
+ 'kit/formtrigger-update',
+ 'kit/formtrigger-delete',
+ );
+
+ /**
+ * Test that the Form Trigger block registers all four content abilities via the
+ * convertkit_abilities filter with the expected names.
+ *
+ * @since 3.4.0
+ */
+ public function testAbilitiesRegistered()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // The ability names and classes expected to be registered.
+ $expected = array(
+ 'kit/formtrigger-list' => \ConvertKit_MCP_Ability_Content_List::class,
+ 'kit/formtrigger-insert' => \ConvertKit_MCP_Ability_Content_Insert::class,
+ 'kit/formtrigger-update' => \ConvertKit_MCP_Ability_Content_Update::class,
+ 'kit/formtrigger-delete' => \ConvertKit_MCP_Ability_Content_Delete::class,
+ );
+
+ // Assert that the abilities are registered and are instances of the expected classes.
+ foreach ( $expected as $name => $class ) {
+ $this->assertArrayHasKey($name, $abilities);
+ $this->assertInstanceOf($class, $abilities[ $name ]);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a user who cannot edit the
+ * given post.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutEditPostCapability()
+ {
+ // Become a Subscriber (no edit_post capability).
+ $subscriber_id = static::factory()->user->create([ 'role' => 'subscriber' ]);
+ wp_set_current_user($subscriber_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::FORM_TRIGGER_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a request with no post_id,
+ * with a clear error code.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutPostId()
+ {
+ // Become an Administrator (has every capability, so the only thing
+ // that can fail here is the missing post_id check).
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::FORM_TRIGGER_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() permits an Administrator on a
+ * valid post_id.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackPermitsAdministrator()
+ {
+ // Become an Administrator.
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission granted.
+ foreach ( self::FORM_TRIGGER_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $this->assertTrue($abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]));
+ }
+ }
+
+ /**
+ * Test that kit/formtrigger-list returns every Form Trigger block occurrence in the
+ * post, with shape { post_id, count, occurrences: [{occurrence_index, attrs}] }.
+ *
+ * @since 3.4.0
+ */
+ public function testListReturnsAllFormTriggerOccurrencesInPost()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/formtrigger-list']->execute_callback([ 'post_id' => $this->postID ]);
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['count']);
+ $this->assertCount(2, $result['occurrences']);
+
+ // Each occurrence carries an occurrence_index and an attrs object
+ // holding the form ID from the seeded post content.
+ foreach ($result['occurrences'] as $i => $occurrence) {
+ $this->assertSame($i, $occurrence['occurrence_index']);
+ $this->assertArrayHasKey('attrs', $occurrence);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_FORM_FORMAT_MODAL_ID'],
+ (string) $occurrence['attrs']['form']
+ );
+ }
+ }
+
+ /**
+ * Test that kit/formtrigger-insert appends a new Form Trigger block to the post, and
+ * returns the new occurrence_index.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertAppendsFormTriggerBlock()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/formtrigger-insert']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'attrs' => array( 'form' => $_ENV['CONVERTKIT_API_FORM_FORMAT_MODAL_ID'] ),
+ 'position' => 'append',
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['occurrence_index']);
+
+ // Confirm the post now contains three Form Trigger blocks.
+ $listed = $abilities['kit/formtrigger-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(3, $listed['count']);
+ }
+
+ /**
+ * Test that kit/formtrigger-update changes the attrs of a specific occurrence,
+ * leaving other occurrences untouched.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateModifiesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Update the second Form Trigger block (occurrence_index 1) to a different form ID.
+ $new_form_id = (string) ( (int) $_ENV['CONVERTKIT_API_FORM_FORMAT_MODAL_ID'] + 1 );
+ $result = $abilities['kit/formtrigger-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 1,
+ 'attrs' => array( 'form' => $new_form_id ),
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(1, $result['occurrence_index']);
+
+ // Re-list and confirm: occurrence 0 unchanged, occurrence 1 has the new form ID.
+ $listed = $abilities['kit/formtrigger-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_FORM_FORMAT_MODAL_ID'],
+ (string) $listed['occurrences'][0]['attrs']['form'],
+ 'kit/formtrigger-update must not modify other occurrences.'
+ );
+ $this->assertSame(
+ $new_form_id,
+ (string) $listed['occurrences'][1]['attrs']['form'],
+ 'kit/formtrigger-update did not apply the new form ID to the requested occurrence.'
+ );
+ }
+
+ /**
+ * Test that kit/formtrigger-delete removes a specific occurrence and the post
+ * now contains one fewer Form Trigger block.
+ *
+ * @since 3.4.0
+ */
+ public function testDeleteRemovesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/formtrigger-delete']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 0,
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(0, $result['occurrence_index']);
+
+ // Confirm the post now contains a single Form Trigger block.
+ $listed = $abilities['kit/formtrigger-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(1, $listed['count']);
+ }
+
+ /**
+ * Test that kit/formtrigger-update returns a WP_Error when asked to update an
+ * occurrence that does not exist, rather than silently mutating
+ * something else.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateOnMissingOccurrenceReturnsError()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/formtrigger-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 99,
+ 'attrs' => array( 'form' => $_ENV['CONVERTKIT_API_FORM_FORMAT_MODAL_ID'] ),
+ )
+ );
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+
+ /**
+ * Creates a Post containing two convertkit/formtrigger blocks interleaved with
+ * non-Kit blocks, mirroring the fixture used by BlockPostHelperTest.
+ *
+ * @since 3.4.0
+ *
+ * @return int
+ */
+ private function createPostWithFormTriggerBlocks(): int
+ {
+ return $this->factory->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_title' => 'Form Trigger Abilities Fixture',
+ 'post_content' => '
+
Intro paragraph.
+
+
+
+
+
+
Middle paragraph.
+
+
+
+
+
+
Closing paragraph.
+',
+ )
+ );
+ }
+}
diff --git a/tests/Integration/MCPContentProductTest.php b/tests/Integration/MCPContentProductTest.php
new file mode 100644
index 000000000..50a6504ba
--- /dev/null
+++ b/tests/Integration/MCPContentProductTest.php
@@ -0,0 +1,394 @@
+postID = $this->createPostWithProductBlocks();
+ }
+
+ /**
+ * Performs actions after each test.
+ *
+ * @since 3.4.0
+ */
+ public function tearDown(): void
+ {
+ // Restore the current user.
+ wp_set_current_user(0);
+
+ // Deactivate Plugin.
+ deactivate_plugins('convertkit/wp-convertkit.php');
+
+ parent::tearDown();
+ }
+
+ /**
+ * The ability names registered by the Product block.
+ *
+ * @since 3.4.0
+ *
+ * @var string[]
+ */
+ private const PRODUCT_ABILITY_NAMES = array(
+ 'kit/product-list',
+ 'kit/product-insert',
+ 'kit/product-update',
+ 'kit/product-delete',
+ );
+
+ /**
+ * Test that the Product block registers all four content abilities via
+ * the convertkit_abilities filter with the expected names.
+ *
+ * @since 3.4.0
+ */
+ public function testAbilitiesRegistered()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // The ability names and classes expected to be registered.
+ $expected = array(
+ 'kit/product-list' => \ConvertKit_MCP_Ability_Content_List::class,
+ 'kit/product-insert' => \ConvertKit_MCP_Ability_Content_Insert::class,
+ 'kit/product-update' => \ConvertKit_MCP_Ability_Content_Update::class,
+ 'kit/product-delete' => \ConvertKit_MCP_Ability_Content_Delete::class,
+ );
+
+ // Assert that the abilities are registered and are instances of the expected classes.
+ foreach ( $expected as $name => $class ) {
+ $this->assertArrayHasKey($name, $abilities);
+ $this->assertInstanceOf($class, $abilities[ $name ]);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a user who cannot edit the
+ * given post.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutEditPostCapability()
+ {
+ // Become a Subscriber (no edit_post capability).
+ $subscriber_id = static::factory()->user->create([ 'role' => 'subscriber' ]);
+ wp_set_current_user($subscriber_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::PRODUCT_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a request with no post_id,
+ * with a clear error code.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutPostId()
+ {
+ // Become an Administrator (has every capability, so the only thing
+ // that can fail here is the missing post_id check).
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( self::PRODUCT_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() permits an Administrator on a
+ * valid post_id.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackPermitsAdministrator()
+ {
+ // Become an Administrator.
+ $admin_id = static::factory()->user->create([ 'role' => 'administrator' ]);
+ wp_set_current_user($admin_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission granted.
+ foreach ( self::PRODUCT_ABILITY_NAMES as $name ) {
+ // Execute the ability.
+ $this->assertTrue($abilities[ $name ]->permission_callback([ 'post_id' => $this->postID ]));
+ }
+ }
+
+ /**
+ * Test that kit/product-list returns every Product block occurrence in
+ * the post.
+ *
+ * @since 3.4.0
+ */
+ public function testListReturnsAllProductOccurrencesInPost()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/product-list']->execute_callback([ 'post_id' => $this->postID ]);
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ $this->assertSame(2, $result['count']);
+ $this->assertCount(2, $result['occurrences']);
+
+ // Each occurrence carries an occurrence_index and an attrs object
+ // holding the product ID from the seeded post content.
+ foreach ($result['occurrences'] as $i => $occurrence) {
+ $this->assertSame($i, $occurrence['occurrence_index']);
+ $this->assertArrayHasKey('attrs', $occurrence);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_PRODUCT_ID'],
+ (string) $occurrence['attrs']['product']
+ );
+ }
+ }
+
+ /**
+ * Test that kit/product-insert appends a new Product block to the post,
+ * and returns the new occurrence_index. Exercises all four primary
+ * Product attributes so each round-trips through the block helper.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertAppendsProductBlock()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/product-insert']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'attrs' => array(
+ 'product' => $_ENV['CONVERTKIT_API_PRODUCT_ID'],
+ 'text' => 'Buy this product',
+ 'discount_code' => $_ENV['CONVERTKIT_API_PRODUCT_DISCOUNT_CODE'],
+ 'checkout' => true,
+ ),
+ 'position' => 'append',
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame($this->postID, $result['post_id']);
+ // Two Product blocks existed in setUp(); the newly inserted one is the third.
+ $this->assertSame(2, $result['occurrence_index']);
+
+ // Confirm the post now contains three Product blocks.
+ $listed = $abilities['kit/product-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(3, $listed['count']);
+
+ // Confirm the newly inserted block carries the attrs we passed in.
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_PRODUCT_ID'],
+ (string) $listed['occurrences'][2]['attrs']['product']
+ );
+ $this->assertSame('Buy this product', $listed['occurrences'][2]['attrs']['text']);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_PRODUCT_DISCOUNT_CODE'],
+ (string) $listed['occurrences'][2]['attrs']['discount_code']
+ );
+ $this->assertTrue( (bool) $listed['occurrences'][2]['attrs']['checkout']);
+ }
+
+ /**
+ * Test that kit/product-update changes the attrs of a specific
+ * occurrence, leaving other occurrences untouched.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateModifiesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Update the second Product block (occurrence_index 1) to a different
+ // product ID and text.
+ $new_product_id = (string) ( (int) $_ENV['CONVERTKIT_API_PRODUCT_ID'] + 1 );
+ $result = $abilities['kit/product-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 1,
+ 'attrs' => array(
+ 'product' => $new_product_id,
+ 'text' => 'Updated CTA',
+ ),
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(1, $result['occurrence_index']);
+
+ // Re-list and confirm: occurrence 0 unchanged, occurrence 1 has the
+ // new product ID and text.
+ $listed = $abilities['kit/product-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(
+ (string) $_ENV['CONVERTKIT_API_PRODUCT_ID'],
+ (string) $listed['occurrences'][0]['attrs']['product'],
+ 'kit/product-update must not modify other occurrences.'
+ );
+ $this->assertSame(
+ $new_product_id,
+ (string) $listed['occurrences'][1]['attrs']['product'],
+ 'kit/product-update did not apply the new product ID to the requested occurrence.'
+ );
+ $this->assertSame(
+ 'Updated CTA',
+ $listed['occurrences'][1]['attrs']['text'],
+ 'kit/product-update did not apply the new text to the requested occurrence.'
+ );
+ }
+
+ /**
+ * Test that kit/product-delete removes a specific occurrence and the
+ * post now contains one fewer Product block.
+ *
+ * @since 3.4.0
+ */
+ public function testDeleteRemovesSingleOccurrence()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/product-delete']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 0,
+ )
+ );
+
+ $this->assertIsArray($result);
+ $this->assertSame(0, $result['occurrence_index']);
+
+ // Confirm the post now contains a single Product block.
+ $listed = $abilities['kit/product-list']->execute_callback([ 'post_id' => $this->postID ]);
+ $this->assertSame(1, $listed['count']);
+ }
+
+ /**
+ * Test that kit/product-update returns a WP_Error when asked to update
+ * an occurrence that does not exist, rather than silently mutating
+ * something else.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateOnMissingOccurrenceReturnsError()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/product-update']->execute_callback(
+ array(
+ 'post_id' => $this->postID,
+ 'occurrence_index' => 99,
+ 'attrs' => array( 'product' => $_ENV['CONVERTKIT_API_PRODUCT_ID'] ),
+ )
+ );
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+
+ /**
+ * Creates a Post containing two convertkit/product blocks interleaved
+ * with non-Kit blocks, mirroring the fixture used by BlockPostHelperTest.
+ *
+ * @since 3.4.0
+ *
+ * @return int
+ */
+ private function createPostWithProductBlocks(): int
+ {
+ return $this->factory->post->create(
+ array(
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_title' => 'Product Abilities Fixture',
+ 'post_content' => '
+
Intro paragraph.
+
+
+
+
+
+
Middle paragraph.
+
+
+
+
+
+
Closing paragraph.
+',
+ )
+ );
+ }
+}
diff --git a/tests/Integration/MCPResourceTest.php b/tests/Integration/MCPResourceTest.php
new file mode 100644
index 000000000..e90cf8fd0
--- /dev/null
+++ b/tests/Integration/MCPResourceTest.php
@@ -0,0 +1,307 @@
+settings = new \ConvertKit_Settings();
+ update_option(
+ $this->settings::SETTINGS_NAME,
+ [
+ 'access_token' => $_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN'],
+ 'refresh_token' => $_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN'],
+ ]
+ );
+ }
+
+ /**
+ * Performs actions after each test.
+ *
+ * @since 3.4.0
+ */
+ public function tearDown(): void
+ {
+ // Delete credentials and any cached resources so each test starts clean.
+ delete_option($this->settings::SETTINGS_NAME);
+
+ foreach ( self::RESOURCE_CLASSES as $resource_class ) {
+ $resource = new $resource_class();
+ delete_option($resource->settings_name);
+ delete_option($resource->settings_name . '_last_queried');
+ }
+
+ // Restore the current user.
+ wp_set_current_user(0);
+
+ // Deactivate Plugin.
+ deactivate_plugins('convertkit/wp-convertkit.php');
+
+ parent::tearDown();
+ }
+
+ /**
+ * Map of resource-list ability names to the ConvertKit_Resource_* class
+ * backing them. Used by tests that need to seed / clear the resource
+ * cache alongside the ability under test.
+ *
+ * @since 3.4.0
+ *
+ * @var array
+ */
+ private const RESOURCE_CLASSES = array(
+ 'kit/forms-list' => \ConvertKit_Resource_Forms::class,
+ 'kit/tags-list' => \ConvertKit_Resource_Tags::class,
+ 'kit/landing-pages-list' => \ConvertKit_Resource_Landing_Pages::class,
+ 'kit/products-list' => \ConvertKit_Resource_Products::class,
+ );
+
+ /**
+ * Test that the four resource-list abilities are registered with the
+ * `convertkit_abilities` filter, so they are picked up by the Abilities
+ * API and exposed by the MCP server.
+ *
+ * @since 3.4.0
+ */
+ public function testAbilitiesRegistered()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // The ability names and classes expected to be registered.
+ $expected = array(
+ 'kit/forms-list' => \ConvertKit_MCP_Ability_Resource_Forms::class,
+ 'kit/tags-list' => \ConvertKit_MCP_Ability_Resource_Tags::class,
+ 'kit/landing-pages-list' => \ConvertKit_MCP_Ability_Resource_Landing_Pages::class,
+ 'kit/products-list' => \ConvertKit_MCP_Ability_Resource_Products::class,
+ );
+
+ // Assert that the abilities are registered and are instances of the expected classes.
+ foreach ( $expected as $name => $class ) {
+ $this->assertArrayHasKey($name, $abilities);
+ $this->assertInstanceOf($class, $abilities[ $name ]);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() rejects a user without the
+ * edit_posts capability.
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackDeniesWithoutEditPostsCapability()
+ {
+ // Become a Subscriber (no edit_posts capability).
+ $subscriber_id = static::factory()->user->create([ 'role' => 'subscriber' ]);
+ wp_set_current_user($subscriber_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission denied.
+ foreach ( array_keys( self::RESOURCE_CLASSES ) as $name ) {
+ // Execute the ability.
+ $result = $abilities[ $name ]->permission_callback([]);
+
+ // Assert that the result is a WP_Error.
+ $this->assertInstanceOf(\WP_Error::class, $result);
+ }
+ }
+
+ /**
+ * Test that the permission_callback() permits a user with the edit_posts
+ * capability (e.g. an Editor or Administrator).
+ *
+ * @since 3.4.0
+ */
+ public function testPermissionCallbackPermitsWithEditPostsCapability()
+ {
+ // Become an Editor (has edit_posts capability).
+ $editor_id = static::factory()->user->create([ 'role' => 'editor' ]);
+ wp_set_current_user($editor_id);
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Assert that the abilities are permission granted.
+ foreach ( array_keys( self::RESOURCE_CLASSES ) as $name ) {
+ // Execute the ability.
+ $this->assertTrue($abilities[ $name ]->permission_callback([]));
+ }
+ }
+
+ /**
+ * Test that the execute_callback() returns an empty (but successful) list
+ * when the resource cache is empty, rather than an error.
+ *
+ * @since 3.4.0
+ */
+ public function testReturnsEmptyListWhenNoResourcesAreCached()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ foreach ( self::RESOURCE_CLASSES as $name => $resource_class ) {
+ // Ensure the cache is empty for this resource.
+ delete_option( ( new $resource_class() )->settings_name );
+
+ // Execute the ability.
+ $result = $abilities[ $name ]->execute_callback([]);
+
+ $this->assertIsArray($result);
+ $this->assertArrayHasKey('count', $result);
+ $this->assertArrayHasKey('items', $result);
+ $this->assertSame(0, $result['count']);
+ $this->assertSame([], $result['items']);
+ }
+ }
+
+ /**
+ * Test that execute_callback() returns the cached items, shaped as
+ * { count, items: [{ id, name, ... }] }, when the resource cache is
+ * populated.
+ *
+ * @since 3.4.0
+ */
+ public function testReturnsCachedItems()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the abilities.
+ foreach ( self::RESOURCE_CLASSES as $name => $resource_class ) {
+ // Populate the resource cache from the Kit API.
+ ( new $resource_class() )->init();
+
+ // Execute the ability.
+ $result = $abilities[ $name ]->execute_callback([]);
+
+ $this->assertIsArray($result);
+ $this->assertArrayHasKey('count', $result);
+ $this->assertArrayHasKey('items', $result);
+ $this->assertGreaterThan(0, $result['count']);
+ $this->assertCount($result['count'], $result['items']);
+
+ // Each item must have id and name.
+ foreach ($result['items'] as $item) {
+ $this->assertArrayHasKey('id', $item);
+ $this->assertArrayHasKey('name', $item);
+ $this->assertIsInt($item['id']);
+ $this->assertIsString($item['name']);
+ }
+ }
+ }
+
+ /**
+ * Test that the Forms ability includes the `format` field on each item,
+ * and that legacy forms (which omit `format` in the raw resource cache)
+ * fall back to 'inline'.
+ *
+ * @since 3.4.0
+ */
+ public function testFormsItemsIncludeFormat()
+ {
+ // Populate the resource cache from the Kit API.
+ ( new \ConvertKit_Resource_Forms() )->init();
+
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the ability.
+ $result = $abilities['kit/forms-list']->execute_callback([]);
+
+ // Assert that the result is an array.
+ $this->assertGreaterThan(0, $result['count']);
+
+ // Assert that the result has items.
+ $allowedFormats = [ 'inline', 'modal', 'slide in', 'sticky bar' ];
+ foreach ($result['items'] as $item) {
+ $this->assertArrayHasKey('format', $item);
+ $this->assertContains($item['format'], $allowedFormats);
+ }
+ }
+
+ /**
+ * Test that the output schema returned by each ability advertises the
+ * same keys (id, name, plus format for forms) that execute_callback()
+ * actually returns. Guards against drift between map_item() and
+ * get_item_schema().
+ *
+ * @since 3.4.0
+ */
+ public function testOutputSchemaMatchesExecuteShape()
+ {
+ // Resolve the abilities array via the same helper the MCP server uses.
+ $abilities = convertkit_get_abilities();
+
+ // Execute the abilities.
+ foreach ( self::RESOURCE_CLASSES as $name => $resource_class ) {
+ // Populate the resource cache from the Kit API.
+ ( new $resource_class() )->init();
+
+ // Execute the ability.
+ $result = $abilities[ $name ]->execute_callback([]);
+
+ if ($result['count'] === 0) {
+ // No items to compare against; skip this ability.
+ continue;
+ }
+
+ // Assert that the output schema is an object.
+ $schema = $abilities[ $name ]->get_output_schema();
+ $this->assertSame('object', $schema['type']);
+ $this->assertSame([ 'count', 'items' ], $schema['required']);
+
+ // Assert that the item schema keys match the result item keys.
+ $itemSchemaKeys = array_keys($schema['properties']['items']['items']['properties']);
+ $itemKeys = array_keys($result['items'][0]);
+
+ sort($itemSchemaKeys);
+ sort($itemKeys);
+
+ $this->assertSame($itemSchemaKeys, $itemKeys);
+ }
+ }
+}
diff --git a/tests/Integration/MCPTest.php b/tests/Integration/MCPTest.php
deleted file mode 100644
index 3f79ea1c5..000000000
--- a/tests/Integration/MCPTest.php
+++ /dev/null
@@ -1,109 +0,0 @@
-dispatch( $request );
-
- // Assert response is unsuccessful.
- $this->assertSame( 401, $response->get_status() );
- }
-
- /**
- * Test that the Kit MCP server is registered with the MCP Adapter and
- * exposes its discovery endpoint at /wp-json/kit-mcp/v1.
- *
- * @since 3.4.0
- */
- public function testKitMCPServerCreated()
- {
- // Create and become administrator.
- $this->actAsAdministrator();
-
- // Make request.
- $request = new \WP_REST_Request('POST', '/kit-mcp/v1');
- $request->set_header('Content-Type', 'application/json');
- $request->set_body(
- wp_json_encode(
- [
- 'jsonrpc' => '2.0',
- 'id' => 1,
- 'method' => 'initialize',
- 'params' => [
- 'protocolVersion' => '2024-11-05',
- 'capabilities' => new \stdClass(),
- 'clientInfo' => [
- 'name' => 'test',
- 'version' => '1.0',
- ],
- ],
- ]
- )
- );
- $response = rest_get_server()->dispatch($request);
-
- // Assert the discovery endpoint is registered and responds successfully.
- $this->assertSame(200, $response->get_status());
-
- // Assert the response identifies itself as the Kit MCP server.
- $data = $response->get_data();
- $this->assertSame('Kit MCP', $data['result']->serverInfo['name'] ?? null);
- }
-
- /**
- * Act as an administrator user.
- *
- * @since 3.4.0
- */
- private function actAsAdministrator()
- {
- $administrator_id = static::factory()->user->create( [ 'role' => 'administrator' ] );
- wp_set_current_user( $administrator_id );
- }
-}
diff --git a/tests/Integration/ShortcodePostHelperTest.php b/tests/Integration/ShortcodePostHelperTest.php
new file mode 100644
index 000000000..0188d10ea
--- /dev/null
+++ b/tests/Integration/ShortcodePostHelperTest.php
@@ -0,0 +1,446 @@
+postID = $this->createPost();
+ }
+
+ /**
+ * Performs actions after each test.
+ *
+ * @since 3.4.0
+ */
+ public function tearDown(): void
+ {
+ // Deactivate Plugin.
+ deactivate_plugins('convertkit/wp-convertkit.php');
+
+ parent::tearDown();
+ }
+
+ /**
+ * Test that the find() method returns the correct shortcode indicies and attributes.
+ *
+ * @since 3.4.0
+ */
+ public function testFind()
+ {
+ // Find the shortcode.
+ $shortcodes = \ConvertKit_Shortcode_Post_Helper::find( $this->postID, 'convertkit_form' );
+
+ $this->assertIsArray( $shortcodes );
+ $this->assertCount( 2, $shortcodes );
+
+ // Assert first matching shortcode indicies and attributes are correct.
+ $this->assertEquals( 0, $shortcodes[0]['occurrence_index'] );
+ $this->assertEquals( $_ENV['CONVERTKIT_API_FORM_ID'], $shortcodes[0]['attrs']['form'] );
+
+ // Assert second matching shortcode indicies and attributes are correct.
+ $this->assertEquals( 1, $shortcodes[1]['occurrence_index'] );
+ $this->assertEquals( $_ENV['CONVERTKIT_API_FORM_ID'], $shortcodes[1]['attrs']['form'] );
+ }
+
+ /**
+ * Test that the find() method returns false when no shortcodes match the given shortcode tag.
+ *
+ * @since 3.4.0
+ */
+ public function testFindWhenNoShortcodesMatch()
+ {
+ $this->assertFalse(\ConvertKit_Shortcode_Post_Helper::find( $this->postID, 'fake_shortcode' ));
+ }
+
+ /**
+ * Test that the find() method returns a WP_Error when the post does not exist.
+ *
+ * @since 3.4.0
+ */
+ public function testFindWhenPostDoesNotExist()
+ {
+ $this->assertInstanceOf(\WP_Error::class, \ConvertKit_Shortcode_Post_Helper::find( 999999, 'convertkit_form' ));
+ }
+
+ /**
+ * Test that the insert() method inserts a new shortcode at the beginning of the content
+ * when the position is set to prepend.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertPrepend()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'prepend'
+ );
+
+ // Confirm result is an array and the post ID is correct.
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ // Confirm content has been updated and the shortcode is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringStartsWith( '[convertkit_form form="' . $_ENV['CONVERTKIT_API_FORM_ID'] . '"]', $post->post_content );
+ }
+
+ /**
+ * Test that the insert() method inserts a new shortcode at the end of the content
+ * when the position is set to append.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertAppend()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'append'
+ );
+
+ // Confirm result is an array and the post ID is correct.
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ // Confirm content has been updated and the shortcode is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringEndsWith( '[convertkit_form form="' . $_ENV['CONVERTKIT_API_FORM_ID'] . '"]', $post->post_content );
+ }
+
+ /**
+ * Test that the insert() method inserts a new shortcode at the specified index position.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertIndex()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'index',
+ index: 1
+ );
+
+ // Confirm result is an array and the post ID is correct.
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ // Confirm content has been updated and the shortcode is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringContainsString( "Item #1\n\n[convertkit_form form=\"" . $_ENV['CONVERTKIT_API_FORM_ID'] . '"]', $post->post_content );
+ }
+
+ /**
+ * Test that the insert() method inserts a new shortcode at end of the content when
+ * the index is out of bounds.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertIndexOutOfBounds()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'index',
+ index: 100
+ );
+
+ // Confirm result is an array and the post ID is correct.
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ // Confirm content has been updated and the shortcode is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringEndsWith( '[convertkit_form form="' . $_ENV['CONVERTKIT_API_FORM_ID'] . '"]', $post->post_content );
+ }
+
+ /**
+ * Test that the insert() method inserts a new shortcode at the specified index position.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertIndexZero()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'index',
+ index: 0
+ );
+
+ // Confirm result is an array and the post ID is correct.
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ // Confirm content has been updated and the shortcode is inserted at the correct position.
+ $post = get_post($this->postID);
+ $this->assertStringStartsWith( '[convertkit_form form="' . $_ENV['CONVERTKIT_API_FORM_ID'] . '"]', $post->post_content );
+ }
+
+ /**
+ * Test that the insert() method returns a WP_Error when the index is negative.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertIndexNegative()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'index',
+ index: -1
+ );
+ $this->assertInstanceOf(\WP_Error::class, $result );
+ }
+
+ /**
+ * Test that the insert() method returns a WP_Error when the post does not exist.
+ *
+ * @since 3.4.0
+ */
+ public function testInsertWhenPostDoesNotExist()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::insert(
+ post_id: 999999,
+ shortcode_tag: 'convertkit_form',
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ],
+ position: 'index',
+ index: 0
+ );
+ $this->assertInstanceOf(\WP_Error::class, $result );
+ }
+
+ /**
+ * Test that the update() method updates the attributes of an existing shortcode.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdate()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::update(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 0,
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ]
+ );
+
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ $result = \ConvertKit_Shortcode_Post_Helper::update(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 1,
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ]
+ );
+
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+ }
+
+ /**
+ * Test that the update() method returns a WP_Error when the occurrence index is out of bounds.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateWhenOccurrenceIndexIsOutOfBounds()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::update(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 999,
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ]
+ );
+ $this->assertInstanceOf(\WP_Error::class, $result );
+ }
+
+ /**
+ * Test that the update() method returns a WP_Error when the post does not exist.
+ *
+ * @since 3.4.0
+ */
+ public function testUpdateWhenPostDoesNotExist()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::update(
+ post_id: 999999,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 0,
+ attrs: [ 'form' => $_ENV['CONVERTKIT_API_FORM_ID'] ]
+ );
+ $this->assertInstanceOf(\WP_Error::class, $result );
+ }
+
+ /**
+ * Test that the delete() method deletes an existing shortcode.
+ *
+ * @since 3.4.0
+ */
+ public function testDelete()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::delete(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 1
+ );
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+
+ $result = \ConvertKit_Shortcode_Post_Helper::delete(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 0
+ );
+ $this->assertIsArray( $result );
+ $this->assertEquals( $this->postID, $result['post_id'] );
+ }
+
+ /**
+ * Test that the delete() method returns a WP_Error when the occurrence index is out of bounds.
+ *
+ * @since 3.4.0
+ */
+ public function testDeleteWhenOccurrenceIndexIsOutOfBounds()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::delete(
+ post_id: $this->postID,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 999
+ );
+ $this->assertInstanceOf(\WP_Error::class, $result );
+ }
+
+ /**
+ * Test that the delete() method returns a WP_Error when the post does not exist.
+ *
+ * @since 3.4.0
+ */
+ public function testDeleteWhenPostDoesNotExist()
+ {
+ $result = \ConvertKit_Shortcode_Post_Helper::delete(
+ post_id: 999999,
+ shortcode_tag: 'convertkit_form',
+ occurrence_index: 0
+ );
+ $this->assertInstanceOf(\WP_Error::class, $result );
+ }
+
+ /**
+ * Mocks a post for testing.
+ *
+ * @since 3.4.0
+ * @return int
+ */
+ private function createPost()
+ {
+ // Create a Post with the given shortcode.
+ return $this->factory->post->create(
+ [
+ 'post_type' => 'page',
+ 'post_status' => 'publish',
+ 'post_title' => 'Shortcode Post',
+ 'post_content' => 'Item #1
+
+
Item #1
+
+Item #2: Adhaésionés altéram improbis mi pariendarum sit stulti triarium
+
+
+
+