<?php
defined('ABSPATH') or die(); 
function aiomatic_mcp_panel()
{
    $settings = get_option('aiomatic_mcp_settings', []);
    $bearer_token = isset($settings['bearer_token']) ? $settings['bearer_token'] : '';
    $aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);
    $sse_url = esc_url_raw( rest_url('aiomatic-mcp/v1/sse') );
    $messages_url = esc_url_raw( rest_url('aiomatic-mcp/v1/messages') );
    $tools_url = esc_url_raw( rest_url('aiomatic-mcp/v1/aiomatic-tools') );
    ?>
<div class="wp-header-end"></div>
<div class="aiomatic-admin-shell">
   <div class="aiomatic-admin-hero">
      <div class="aiomatic-admin-identity">
         <div class="aiomatic-admin-logo">
            <img class="client-logo" src="<?php echo esc_url(plugins_url( '/../images/ai.png', __FILE__ )); ?>" alt="Aimogen" />
         </div>
         <div class="aiomatic-admin-title">
            <div class="aiomatic-admin-title-sub">
               <?php esc_html_e( 'AI Momentum Generator', 'aiomatic-automatic-ai-content-writer' ); ?>
            </div>
            <div class="aiomatic-admin-title-main">
               <?php esc_html_e( 'Aimogen - AI Writer, Editor, ChatBot & Toolkit', 'aiomatic-automatic-ai-content-writer' ); ?>
               <span class="aiomatic-version-pill">
                  <span class="aiomatic-version-pill-dot"></span>
                  <?php esc_html_e( 'Version', 'aiomatic-automatic-ai-content-writer' ); ?> <?php echo esc_html(aimogenpro_get_version());?>
               </span>
            </div>
         </div>
      </div>
      <div class="aiomatic-admin-meta">
         <div class="aiomatic-admin-meta-row">
            <span><?php esc_html_e( 'AI Live inside your dashboard', 'aiomatic-automatic-ai-content-writer' ); ?></span>
         </div>
         <a class="aiomatic-white" href="https://wpbay.com/product/aimogen-pro/" target="_blank">
            <div class="aiomatic-admin-badge">
               <span class="aiomatic-admin-badge-dot"></span><?php esc_html_e( 'Ready when your ideas are', 'aiomatic-automatic-ai-content-writer' ); ?>
            </div>
         </a>
      </div>
   </div>
<div class="aiomatic-admin-layout">
    <aside class="aiomatic-admin-sidebar">
         <div class="aiomatic-admin-sidebar-inner">
            <div class="aiomatic-sidebar-heading">
               <?php esc_html_e( 'MCP Servers', 'aiomatic-automatic-ai-content-writer' ); ?>
            </div>
            <div class="aiomatic-sidebar-nav">
               <nav class="nav-tab-wrapper">
                  <a href="#tab-0" class="aiomatic-nav-tab">
                     <span class="aiomatic-sidebar-icon">▶︎</span>
                     <span class="aiomatic-sidebar-label"><?php echo esc_html__("Tutorial", 'aiomatic-automatic-ai-content-writer');?></span>
                  </a>
                  <a href="#tab-1" class="aiomatic-nav-tab">
                     <span class="aiomatic-sidebar-icon">⩰</span>
                     <span class="aiomatic-sidebar-label"><?php echo esc_html__("Create Your MCP Server", 'aiomatic-automatic-ai-content-writer');?></span>
                  </a>
                  <a href="#tab-2" class="aiomatic-nav-tab">
                     <span class="aiomatic-sidebar-icon">⩯</span>
                     <span class="aiomatic-sidebar-label"><?php echo esc_html__("Connect To A MCP Server", 'aiomatic-automatic-ai-content-writer');?></span>
                  </a>
               </nav>
            </div>
            <div class="aiomatic-sidebar-footer">
               <strong><?php esc_html_e( 'Need a quick start?', 'aiomatic-automatic-ai-content-writer' ); ?></strong>
               <span><?php esc_html_e( '1. Set up your own MCP server, exposing specific tools and allow AI models to connect to them.', 'aimogen' ); ?></span>
               <span><?php esc_html_e( '2. Connect your AI models to external MCP servers and use custom tools provided by them.', 'aimogen' ); ?></span>
               <span>
                  <?php esc_html_e( 'Watch tutorials on', 'aiomatic-automatic-ai-content-writer' ); ?>
                  <a href="https://www.youtube.com/channel/UCVLIksvzyk-D_oEdHab2Lgg" target="_blank" rel="noopener noreferrer">CodeRevolutionTV</a>
               </span>
            </div>
         </div>
      </aside>
<section class="aiomatic-admin-main">
    <div class="gs_popuptype_holder">

        <div id="tab-0" class="tab-content" style="display:block">
            <br/><h3><?php echo esc_html__('MCP Server Tutorial', 'aiomatic-automatic-ai-content-writer'); ?></h3>
<div>
    <p>
        <?php echo esc_html__('The Model Context Protocol (MCP) support built into Aimogen allows your WordPress site to become more than just a publishing platform. 
        Once enabled, your site acts as an MCP server using Server Sent Events (SSE). 
        This means tools like Claude Desktop can connect through a local relay script, and services like OpenAI Deep Research can discover and call the functions you expose here.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p>
        <?php echo esc_html__('Enabling the MCP extension plugin unlocks a control panel where you can decide which tool packs are exposed. 
        The Core WordPress pack is recommended because it registers useful functions that let AI models interact with posts, pages, media, taxonomies, and other essentials. 
        You can also turn on plugin oriented helpers, theme oriented helpers, or even WooCommerce helpers if you run a shop. 
        There is an option to generate a dynamic REST layer that creates CRUD style endpoints for content, giving models a way to create or update posts directly.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p>
        <?php echo esc_html__('Once you check the setting to enable the SSE server, an endpoint will be available and protected by the Bearer Token you configure. 
        Any client connecting to this endpoint must provide the correct token. 
        There is also a Debug Mode which is only intended for local testing, it lets you see raw function registrations and requests.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p>
        <?php echo esc_html__('When the extension is active and SSE is enabled you will see your live endpoints listed below. 
        These are the exact URLs that an MCP client or relay script will consume. 
        For example, Claude Desktop requires a relay script pointing to the SSE endpoint, while Deep Research clients may call the Messages endpoint to exchange structured data.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p>
        <?php echo esc_html__('If you scroll further down in the MCP panel you will also see the Messages endpoint and the list of registered tools. 
        The refresh button will query your server and print the current function set in JSON format, which makes it easy to verify what is exposed.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p>
        <?php echo esc_html__('For users running multiple MCP servers, the Connect tab lets you register and manage external servers. 
        Each server entry has a name, description, URL, authentication token, and a flag for global enablement. 
        Aimogen will then merge those into the active context for supported AI models, allowing you to extend functionality across different environments.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p>
        <?php echo esc_html__('In short, Aimogen\'s MCP support turns your WordPress site into a living API hub that AI tools can call. 
        By enabling SSE, protecting it with a token, and choosing the right tool packs, you gain fine control over how AI assistants interact with your content, plugins, themes, and store. 
        The extension plugin is required for this functionality and once active, everything can be configured directly here in the WordPress admin panel.', 'aiomatic-automatic-ai-content-writer'); ?>
    </p>
    <p><?php echo wp_kses(
    sprintf(
        __(
            'Check %s for more details on usage of the MCP server feature of Aimogen.',
            'aiomatic-automatic-ai-content-writer'
        ),
        '<a href="https://coderevolution.ro/knowledge-base/faq/how-to-connect-claude-to-wordpress-with-aiomatic-mcp/" target="_blank">this tutorial</a>'
    ),
    array(
        'a' => array(
            'href'   => array(),
            'target' => array(),
        ),
    )
);?></p>
</div>

            <?php if (!isset($aiomatic_Main_Settings['hide_videos']) || trim($aiomatic_Main_Settings['hide_videos']) != 'on') { ?>
                <h3><?php echo esc_html__('Tutorial Video', 'aiomatic-automatic-ai-content-writer'); ?></h3>
                <p class="cr_center">
                    <div class="embedtool">
                        <iframe src="https://www.youtube.com/embed/niILXouTah4" frameborder="0" allowfullscreen></iframe>
                    </div>
                </p>
            <?php } ?>
        </div>

        <div id="tab-1" class="tab-content" style="display:none">
            <br/>
            <h3><?php echo esc_html__('Create Your Own MCP Server', 'aiomatic-automatic-ai-content-writer'); ?></h3>
            <p><?php echo esc_html__('Create a MCP server on your website and allow AI models to directly connect to it and use tools published by it. Like this, external AI models can control your site, query information from it and insert or update data on it.', 'aiomatic-automatic-ai-content-writer'); ?></p>
            <p><?php echo esc_html__('If your server is behind Cloudflare, go to Cloudflare settings for your site -> Security -> Security Rules -> click Create Rule -> Custom Rules -> add a name of your choice -> in Field select URI -> in Value add: ', 'aiomatic-automatic-ai-content-writer') 
            . '<strong>/wp-json/aiomatic-mcp/v1/*</strong>' . esc_html__(' -> in Choose action select Skip -> select all checkboxes in WAF components to skip -> click More components to skip and also select all new checkboxes which appeared -> click Deploy', 'aiomatic-automatic-ai-content-writer'); ?></p>
<hr/>
<?php
if ( ! function_exists( 'is_plugin_active' ) ) {
        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
    }

    if ( is_plugin_active( 'aiomatic-extension-mcp-server/aiomatic-extension-mcp-server.php' ) ) 
    {
?>
            <form method="post" action="options.php">
                <?php settings_fields('aiomatic_mcp'); ?>
                <?php $opt = wp_parse_args($settings, [
                    'enable_sse' => '', 'bearer_token' => '', 'enable_debug' => '',
                    'tuned_core' => 'on', 'tuned_plugins' => '', 'tuned_themes' => '',
                    'dynamic_rest' => '', 'tuned_woocommerce' => '', 'session_memory' => '', 'embeddings_sse' => '', 'advanced_sse' => ''
                ]); ?>

                <table class="form-table">
                    <tr>
                        <th scope="row"><?php echo esc_html__('Enable SSE server', 'aiomatic-automatic-ai-content-writer'); ?></th>
                        <td><input type="hidden" name="aiomatic_mcp_settings[enable_sse]" value="" /><label><input type="checkbox" name="aiomatic_mcp_settings[enable_sse]" <?php checked($opt['enable_sse'], 'on'); ?> /> <?php echo esc_html__('Enables the MCP SSE endpoint', 'aiomatic-automatic-ai-content-writer'); ?></label></td>
                    </tr>
                    <tr class="mcp_sse">
                        <th scope="row"><?php echo esc_html__('Bearer Token', 'aiomatic-automatic-ai-content-writer'); ?></th>
                        <td><input type="text" name="aiomatic_mcp_settings[bearer_token]" value="<?php echo esc_attr($opt['bearer_token']); ?>" class="regular-text" /><p class="description"><?php echo esc_html__('MCP will be usable by using this Bearer Token. If you intend to use this in Claude Desktop, don\'t use any upper case letters in the token.', 'aiomatic-automatic-ai-content-writer'); ?></p></td>
                    </tr>
                    <tr class="mcp_sse">
                        <th scope="row"><?php echo esc_html__('Enable Debug Mode', 'aiomatic-automatic-ai-content-writer'); ?></th>
                        <td><input type="hidden" name="aiomatic_mcp_settings[enable_debug]" value="" /><label><input type="checkbox" name="aiomatic_mcp_settings[enable_debug]" <?php checked($opt['enable_debug'], 'on'); ?> /> <?php echo esc_html__('Enables debug mode - only use for local testing', 'aiomatic-automatic-ai-content-writer'); ?></label></td>
                    </tr>
                    <tr class="mcp_sse"><th colspan="2"><h3><?php echo esc_html__('Enabled Tool Packs', 'aiomatic-automatic-ai-content-writer'); ?></h3></th></tr>
                    <tr class="mcp_sse"><th scope="row"><?php echo esc_html__('Core WordPress Functionality', 'aiomatic-automatic-ai-content-writer'); ?></th><td><input type="hidden" name="aiomatic_mcp_settings[tuned_core]" value="" /><label><input type="checkbox" name="aiomatic_mcp_settings[tuned_core]" <?php checked($opt['tuned_core'], 'on'); ?> /> <?php echo esc_html__('Registers core WordPress tools (recommended)', 'aiomatic-automatic-ai-content-writer'); ?></label></td></tr>
                    <tr class="mcp_sse"><th scope="row"><?php echo esc_html__('Plugins Related Functionality', 'aiomatic-automatic-ai-content-writer'); ?></th><td><input type="hidden" name="aiomatic_mcp_settings[tuned_plugins]" value="" /><label><input type="checkbox" name="aiomatic_mcp_settings[tuned_plugins]" <?php checked($opt['tuned_plugins'], 'on'); ?> /> <?php echo esc_html__('Plugin oriented helpers (optional)', 'aiomatic-automatic-ai-content-writer'); ?></label></td></tr>
                    <tr class="mcp_sse"><th scope="row"><?php echo esc_html__('Themes Related Functionality', 'aiomatic-automatic-ai-content-writer'); ?></th><td><input type="hidden" name="aiomatic_mcp_settings[tuned_themes]" value="" /><label><input type="checkbox" name="aiomatic_mcp_settings[tuned_themes]" <?php checked($opt['tuned_themes'], 'on'); ?> /> <?php echo esc_html__('Theme oriented helpers (optional)', 'aiomatic-automatic-ai-content-writer'); ?></label></td></tr>
                    <tr class="mcp_sse"><th scope="row"><?php echo esc_html__('Dynamic REST API', 'aiomatic-automatic-ai-content-writer'); ?></th><td><input type="hidden" name="aiomatic_mcp_settings[dynamic_rest]" value="" /><label><input type="checkbox" name="aiomatic_mcp_settings[dynamic_rest]" <?php checked($opt['dynamic_rest'], 'on'); ?> /> <?php echo esc_html__('Generate CRUD tools for posts, pages, media (optional)', 'aiomatic-automatic-ai-content-writer'); ?></label></td></tr>
<tr class="mcp_sse">
    <th scope="row">
        <?php echo esc_html__( 'Agent Session Memory', 'aiomatic-automatic-ai-content-writer' ); ?>
    </th>
    <td>
        <input type="hidden" name="aiomatic_mcp_settings[session_memory]" value="" />
        <label>
            <input type="checkbox"
                   name="aiomatic_mcp_settings[session_memory]"
                   <?php checked( $opt['session_memory'], 'on' ); ?>
                   <?php disabled( ! function_exists( 'aiomatic_mcp_session_tools' ) ); ?> />
            <?php echo esc_html__( 'Allows the AI to memorize information for its processing (optional)', 'aiomatic-automatic-ai-content-writer' ); ?>
        </label>
        <?php if ( ! function_exists( 'aiomatic_mcp_session_tools' ) ) : ?>
            <p class="description">
                <?php echo esc_html__( 'Requires latest update of the "Aimogen Extension - MCP Server Creator" plugin.', 'aiomatic-automatic-ai-content-writer' ); ?>
            </p>
        <?php endif; ?>
    </td>
</tr>
<tr class="mcp_sse">
    <th scope="row">
        <?php echo esc_html__( 'Embeddings', 'aiomatic-automatic-ai-content-writer' ); ?>
    </th>
    <td>
        <input type="hidden" name="aiomatic_mcp_settings[embeddings_sse]" value="" />
        <label>
            <input type="checkbox"
                   name="aiomatic_mcp_settings[embeddings_sse]"
                   <?php checked( $opt['embeddings_sse'], 'on' ); ?>
                   <?php disabled( ! function_exists( 'aiomatic_mcp_embeddings_tools' ) ); ?> />
            <?php echo esc_html__( 'Allows access to the AI to internal embeddings (optional)', 'aiomatic-automatic-ai-content-writer' ); ?>
        </label>
        <?php if ( ! function_exists( 'aiomatic_mcp_embeddings_tools' ) ) : ?>
            <p class="description">
                <?php echo esc_html__( 'Requires latest update of the "Aimogen Extension - MCP Server Creator" plugin.', 'aiomatic-automatic-ai-content-writer' ); ?>
            </p>
        <?php endif; ?>
    </td>
</tr>
<tr class="mcp_sse">
    <th scope="row">
        <?php echo esc_html__( 'Advanced Functionality', 'aiomatic-automatic-ai-content-writer' ); ?>
    </th>
    <td>
        <input type="hidden" name="aiomatic_mcp_settings[advanced_sse]" value="" />
        <label>
            <input type="checkbox"
                   name="aiomatic_mcp_settings[advanced_sse]"
                   <?php checked( $opt['advanced_sse'], 'on' ); ?>
                   <?php disabled( ! function_exists( 'aiomatic_mcp_advanced_tools' ) ); ?> />
            <?php echo esc_html__( 'Access tools like: Amazon Product Details, Scrape Sites & RSS, Internet Search Result, YouTube Video Search & Captions, Send Email (optional)', 'aiomatic-automatic-ai-content-writer' ); ?>
        </label>
        <?php if ( ! function_exists( 'aiomatic_mcp_advanced_tools' ) ) : ?>
            <p class="description">
                <?php echo esc_html__( 'Requires latest update of the "Aimogen Extension - MCP Server Creator" plugin.', 'aiomatic-automatic-ai-content-writer' ); ?>
            </p>
        <?php endif; ?>
    </td>
</tr>
<tr class="mcp_sse">
    <th scope="row">
        <?php echo esc_html__( 'WooCommerce Related Functionality', 'aiomatic-automatic-ai-content-writer' ); ?>
    </th>
    <td>
        <input type="hidden" name="aiomatic_mcp_settings[tuned_woocommerce]" value="" />
        <label>
            <input type="checkbox"
                   name="aiomatic_mcp_settings[tuned_woocommerce]"
                   <?php checked( $opt['tuned_woocommerce'], 'on' ); ?>
                   <?php disabled( ! class_exists( 'WooCommerce' ) ); ?> />
            <?php echo esc_html__( 'WooCommerce oriented helpers (optional)', 'aiomatic-automatic-ai-content-writer' ); ?>
        </label>
        <?php if ( ! class_exists( 'WooCommerce' ) ) : ?>
            <p class="description">
                <?php echo esc_html__( 'Requires WooCommerce to be active.', 'aiomatic-automatic-ai-content-writer' ); ?>
            </p>
        <?php endif; ?>
    </td>
</tr>
<tr class="mcp_sse">
<td colspan="2">

            <h3><?php echo esc_html__('Endpoints', 'aiomatic-automatic-ai-content-writer'); ?></h3>
            <table class="widefat striped">
                <tbody>
                    <tr>
  <th class="align-top pr-4 text-gray-600 font-medium">
    &nbsp;<?php echo esc_html__('SSE Endpoint', 'aiomatic-automatic-ai-content-writer'); ?>
  </th>
  <td>
    <div class="flex items-center gap-2 bg-gray-100 rounded-xl px-3 py-2 border border-gray-200">
      <strong class="cr_red">
        <code class="text-sm text-gray-800 break-all">
        <?php echo esc_html($sse_url); ?>
        </code>
      </strong>
      <button 
        type="button"
        class="ml-2 inline-flex items-center px-2 py-1 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded-lg shadow-sm hover:bg-gray-50 active:bg-gray-100 transition"
        onclick="navigator.clipboard.writeText('<?php echo esc_js($sse_url); ?>'); this.innerText='Copied!'; setTimeout(() => this.innerText='Copy', 2000);"
      >
        <?php echo esc_html__('Copy', 'aiomatic-automatic-ai-content-writer'); ?>
      </button>
    </div>
  </td>
</tr>
                    <tr><th>&nbsp;<?php echo esc_html__('Messages Endpoint', 'aiomatic-automatic-ai-content-writer'); ?></th><td><code><?php echo esc_html($messages_url); ?></code></td></tr>
                </tbody>
            </table>
        </td>
    </tr>
                </table>
                <p class="crsubmit"><input type="submit" name="btnSubmit" id="btnSubmit" class="button button-primary" onclick="unsaved = false;" value="<?php echo esc_html__("Save Settings", 'aiomatic-automatic-ai-content-writer');?>"/></p>
            </form>

            <h3><?php echo esc_html__('Debug', 'aiomatic-automatic-ai-content-writer'); ?></h3>
            <p><button class="button" id="aiomatic-mcp-refresh"><?php echo esc_html__('Refresh Function List', 'aiomatic-automatic-ai-content-writer'); ?></button>
            <span id="aiomatic-mcp-refresh-status" style="margin-left:6px;"></span></p>
            <pre id="aiomatic-mcp-functions" style="max-height:380px;overflow:auto;background:#111;color:#eee;padding:12px;border-radius:8px;"></pre>
<?php
    }
    else
    {
?>
        <div style="padding:20px; border-radius:12px; background:#f9f9f9; border:1px solid #ddd; text-align:center; max-width:600px; margin:20px auto;">
            <h2 style="margin-bottom:10px; color:#333;">
                <?php echo esc_html__('MCP Extension Required', 'aiomatic-automatic-ai-content-writer'); ?>
            </h2>
            <p style="margin-bottom:15px; color:#555; font-size:15px;">
                <?php echo esc_html__('This functionality is only available if the Aimogen MCP Server Extension plugin is active.', 'aiomatic-automatic-ai-content-writer'); ?>
            </p>
            <a href="https://wpbay.com/product/aiomatic-extension-mcp-server-creator/" target="_blank" 
               style="display:inline-block; padding:10px 20px; background:#0073aa; color:#fff; text-decoration:none; border-radius:6px; font-weight:bold;">
                <?php echo esc_html__('Purchase Plugin', 'aiomatic-automatic-ai-content-writer'); ?>
            </a>
        </div>
<?php
    }
?>
        </div>
<?php
$aiomatic_Main_Settings = get_option('aiomatic_Main_Settings', false);

$aiomatic_enabled = isset($aiomatic_Main_Settings['aiomatic_enabled']) ? $aiomatic_Main_Settings['aiomatic_enabled'] : '';
$responses_api    = isset($aiomatic_Main_Settings['responses_api']) ? $aiomatic_Main_Settings['responses_api'] : '';
$api_selector     = isset($aiomatic_Main_Settings['api_selector']) ? $aiomatic_Main_Settings['api_selector'] : 'openai';

$is_aiomaticapi = false;
$token = '';
if (!empty($aiomatic_Main_Settings['app_id'])) {
    $appids = preg_split('/\r\n|\r|\n/', trim($aiomatic_Main_Settings['app_id']));
    $appids = array_filter($appids);
    if (count($appids) == 1) {
        $token = $appids[array_rand($appids)];
        $token = apply_filters('aimogen_openai_api_key', $token);$token = apply_filters('aiomatic_openai_api_key', $token);
        if (aiomatic_is_aiomaticapi_key($token)) {
            $call_count = get_transient('aiomaticapi_tokens');
            if ($token != '' && $call_count !== false) {
                $is_aiomaticapi = true;
            }
        }
    }
}
?>
        <div id="tab-2" class="tab-content" style="display:none">
            <br/>
            <h3><?php echo esc_html__('MCP Server Connections', 'aiomatic-automatic-ai-content-writer'); ?></h3>
<?php if ($aiomatic_enabled === 'on' && $responses_api === 'on' && $api_selector === 'openai' && !$is_aiomaticapi): ?>
            <p><?php echo esc_html__('Configure external MCP servers here. These servers extend AI capabilities by providing tools and functions that AI models can call during conversations.', 'aiomatic-automatic-ai-content-writer'); ?></p>
<hr/><br/>
            <div class="mcp-servers-container">
                <button type="button" class="button button-primary" id="add-mcp-server"><?php echo esc_html__('New MCP Server Connection', 'aiomatic-automatic-ai-content-writer'); ?></button>
                <div id="mcp-server-list" style="margin-top:20px;">
                    <?php
                    $mcp_servers = get_option('aiomatic_mcp_servers', array());
                    if (!empty($mcp_servers)) {
                        foreach ($mcp_servers as $id => $server) {
                            ?>
                            <div class="mcp-server-entry" data-id="<?php echo esc_attr($id); ?>" style="border:1px solid #ccd0d4;padding:12px;margin-bottom:12px;border-radius:6px;background:#fff;">
                                <h4><?php echo esc_html($server['name']); ?></h4>
                                <?php if (!empty($server['description'])): ?>
                                    <p><strong><?php echo esc_html__('Description:', 'aiomatic-automatic-ai-content-writer'); ?></strong> <span class="descr"><?php echo esc_html($server['description']); ?></span></p>
                                <?php endif; ?>
                                <p>
  <strong><?php echo esc_html__('URL:', 'aiomatic-automatic-ai-content-writer'); ?></strong>
  <?php echo esc_html($server['url']); ?>
  <span class="srv-url" style="display:none;"><?php echo esc_attr($server['url']); ?></span>
</p>
                                <p>
    <strong><?php echo esc_html__('Token:', 'aiomatic-automatic-ai-content-writer'); ?></strong>
    <?php if (!empty($server['token'])): ?>
        ********
        <span class="tkn" style="display:none;"><?php echo esc_html($server['token']); ?></span>
    <?php else: ?>
        -
    <?php endif; ?>
</p>
<p>
    <strong><?php echo esc_html__('Enabled Globally:', 'aiomatic-automatic-ai-content-writer'); ?></strong>
    <?php echo !empty($server['global']) && $server['global'] === 'on' ? esc_html__('Yes', 'aiomatic-automatic-ai-content-writer') : esc_html__('No', 'aiomatic-automatic-ai-content-writer'); ?>
    <span class="srv-global" style="display:none;"><?php echo !empty($server['global']) && $server['global'] === 'on' ? 'on' : 'off'; ?></span>
</p>
                                <p><strong><?php echo esc_html__('Server ID:', 'aiomatic-automatic-ai-content-writer'); ?></strong> <?php echo esc_html($id); ?></p>
                                <button type="button" class="button edit-mcp-server"><?php echo esc_html__('Edit', 'aiomatic-automatic-ai-content-writer'); ?></button>
                                <button type="button" class="button delete-mcp-server" onclick="unsaved = false;"><?php echo esc_html__('Delete', 'aiomatic-automatic-ai-content-writer'); ?></button>
                            </div>
                            <?php
                        }
                    } else {
                        echo '<p>' . esc_html__('No MCP servers configured yet.', 'aiomatic-automatic-ai-content-writer') . '</p>';
                    }
                    ?>
                </div>
            </div>

            <!-- Add/Edit form -->
            <div id="mcp-server-form" style="display:none; margin-top:20px; background:#f9f9f9; padding:15px; border:1px solid #ccd0d4; border-radius:6px;">
                <h4><?php echo esc_html__('Add / Edit MCP Server', 'aiomatic-automatic-ai-content-writer'); ?></h4>
                <table class="form-table">
                    <tr>
                        <th><label for="mcp-server-name"><?php echo esc_html__('Name', 'aiomatic-automatic-ai-content-writer'); ?></label></th>
                        <td>
                            <input type="text" id="mcp-server-name" class="regular-text" placeholder="Your MCP Server Name" />
                            <input type="hidden" id="mcp-server-id" />
                        </td>
                    </tr>
                    <tr>
                        <th><label for="mcp-server-description"><?php echo esc_html__('Description', 'aiomatic-automatic-ai-content-writer'); ?></label></th>
                        <td>
                            <textarea id="mcp-server-description" class="large-text" rows="3" placeholder="Short description of what this server does"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="mcp-server-url"><?php echo esc_html__('URL', 'aiomatic-automatic-ai-content-writer'); ?></label></th>
                        <td><input type="text" id="mcp-server-url" class="regular-text" placeholder="Example: https://dmcp-server.deno.dev/sse" /></td>
                    </tr>
                    <tr>
                        <th><label for="mcp-server-token"><?php echo esc_html__('Token', 'aiomatic-automatic-ai-content-writer'); ?></label></th>
                        <td><input type="password" id="mcp-server-token" class="regular-text" placeholder="Bearer token for authentication (optional)" /></td>
                    </tr>
                    <tr>
                        <th><label for="mcp-server-global"><?php echo esc_html__('Enable Globally', 'aiomatic-automatic-ai-content-writer'); ?></label></th>
                        <td><input type="checkbox" id="mcp-server-global" /></td>
                    </tr>
                </table>
                <p>
                    <button type="button" class="button button-primary" onclick="unsaved = false;" id="save-mcp-server"><?php echo esc_html__('Save Server Connection', 'aiomatic-automatic-ai-content-writer'); ?></button>
                    <button type="button" class="button" id="cancel-mcp-server"><?php echo esc_html__('Cancel', 'aiomatic-automatic-ai-content-writer'); ?></button>
                </p>
            </div>
            <?php else: ?>
        <div style="margin:20px 0; padding:20px; border:1px solid #ccd0d4; border-radius:8px; background:#fff3cd; color:#856404;">
            <strong><?php echo esc_html__('MCP Servers Disabled', 'aiomatic-automatic-ai-content-writer'); ?></strong>
            <p><?php echo esc_html__('This functionality is only available when Aimogen Pro is enabled, Responses API is turned on, the API selector is set to OpenAI, and you are not using an AimogenAPI API key. Please adjust your settings to enable MCP server connections. This will work in OpenAI models and also for Anthropic models.', 'aiomatic-automatic-ai-content-writer'); ?></p>
        </div>
    <?php endif; ?>
        </div>
</div>
</section>
        </div>
</div>
<script>
jQuery(document).ready(function($) {
    function toggleMcpSse() {
        if ($('input[name="aiomatic_mcp_settings[enable_sse]"]').is(':checked')) {
            $('.mcp_sse').show();
        } else {
            $('.mcp_sse').hide();
        }
    }

    toggleMcpSse();

    $(document).on('change', 'input[name="aiomatic_mcp_settings[enable_sse]"]', function() {
        toggleMcpSse();
    });
});
(function(){
    const tabs = document.querySelectorAll('.nav-tab-wrapper .nav-tab');
    const contents = document.querySelectorAll('.tab-content');
    tabs.forEach(tab => tab.addEventListener('click', function(e){
        e.preventDefault();
        tabs.forEach(t => t.classList.remove('nav-tab-active'));
        this.classList.add('nav-tab-active');
        contents.forEach(c => c.style.display = 'none');
        const target = document.querySelector(this.getAttribute('href'));
        if (target) target.style.display = 'block';
    }));
    const btn = document.getElementById('aiomatic-mcp-refresh');
    if (btn) {
        btn.addEventListener('click', async function(){
            const pre = document.getElementById('aiomatic-mcp-functions');
            const status = document.getElementById('aiomatic-mcp-refresh-status');
            status.textContent = 'Loading...';
            try {
                const res = await fetch('<?php echo esc_js($tools_url); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                            'Authorization': 'Bearer <?php echo esc_js($bearer_token); ?>'
                    }
                });
                if (!res.ok) throw new Error("HTTP " + res.status);
                const json = await res.json();
                pre.textContent = JSON.stringify(json, null, 2);
                status.textContent = 'Done';
            } catch(e){
                status.textContent = 'Error';
                pre.textContent = e.message;
            }
        });
    }
    const addBtn = document.getElementById('add-mcp-server');
    const form = document.getElementById('mcp-server-form');
    const saveBtn = document.getElementById('save-mcp-server');
    const cancelBtn = document.getElementById('cancel-mcp-server');

    const idInput = document.getElementById('mcp-server-id'); 
    const nameInput = document.getElementById('mcp-server-name');
    const descInput = document.getElementById('mcp-server-description');
    const description = descInput.value.trim();
    const urlInput = document.getElementById('mcp-server-url');
    const tokenInput = document.getElementById('mcp-server-token');
    const enableGlobal = document.getElementById('mcp-server-global');

    addBtn?.addEventListener('click', () => {
        form.style.display = 'block';
        idInput.value = '';
        nameInput.value = '';
        urlInput.value = '';
        descInput.value = '';
        tokenInput.value = '';
        enableGlobal.checked = false;
    });

    cancelBtn?.addEventListener('click', () => { 
        form.style.display = 'none'; 
    });

    saveBtn?.addEventListener('click', async () => {
        const name = nameInput.value.trim();
        const url = urlInput.value.trim();
        const token = tokenInput.value.trim();
        const description = descInput.value.trim();
        const id = idInput.value || 'srv-' + Math.random().toString(36).substr(2, 9);
        const globalEnabled = enableGlobal.checked ? 'on' : 'off';

        if (!name) {
            alert('Please enter a server name.');
            return;
        }
        if (!url) {
            alert('Please enter a server URL.');
            return;
        }
        if (!/^http.+/i.test(url)) {
            alert('The URL must start with http');
            return;
        }

        const data = {
            action: 'aiomatic_save_mcp_server',
            id: id,
            name: name,
            description: description,
            url: url,
            global: globalEnabled,
            token: token,
            _ajax_nonce: '<?php echo wp_create_nonce("aiomatic_mcp_nonce"); ?>'
        };

        try {
            const res = await fetch(ajaxurl, {
                method: 'POST',
                body: new URLSearchParams(data)
            });
            const json = await res.json();
            if (!json.success) {
                alert('Error saving MCP server.');
            } else {
                location.reload();
            }
        } catch (e) {
            alert('Request failed: ' + e.message);
        }
    });

    document.querySelectorAll('.edit-mcp-server').forEach(btn =>
        btn.addEventListener('click', e => {
            const entry = e.target.closest('.mcp-server-entry');
            idInput.value = entry.dataset.id;
            nameInput.value = entry.querySelector('h4').textContent.trim();
            const descrSpan = entry.querySelector('.descr');
            descInput.value = descrSpan ? descrSpan.textContent.trim() : '';

            const urlSpan = entry.querySelector('.srv-url');
            urlInput.value = urlSpan ? urlSpan.textContent.trim() : '';

            const tkn = entry.querySelector('.tkn');
            tokenInput.value = tkn ? tkn.textContent.trim() : '';
            
            const globalSpan = entry.querySelector('.srv-global');
            enableGlobal.checked = globalSpan && globalSpan.textContent.trim() === 'on';

            form.style.display = 'block';
        })
    );

    document.querySelectorAll('.delete-mcp-server').forEach(btn => btn.addEventListener('click', async e => {
        if (!confirm('Delete this server?')) return;
        const entry = e.target.closest('.mcp-server-entry');
        try {
            const res = await fetch(ajaxurl, {
                method: 'POST',
                body: new URLSearchParams({
                    action: 'aiomatic_delete_mcp_server',
                    id: entry.dataset.id,
                    _ajax_nonce: '<?php echo wp_create_nonce("aiomatic_mcp_nonce"); ?>'
                })
            });
            const json = await res.json();
            if (json.success) {
                location.reload();
            } else {
                alert('Error deleting server.');
            }
        } catch (e) {
            alert('Delete failed: ' + e.message);
        }
    }));

})();
</script>
<?php
}
?>