Jump to content

Recommended Posts

ClicShopping Version 4.08 and more :

MCP (Model Context Protocol) Documentation for ClicShopping

Overview

The ClicShopping MCP (Model Context Protocol) system allows for the integration of external Node.js or Python servers to extend the e-commerce application’s capabilities with advanced Artificial Intelligence functionalities. It provides a modular architecture for communication between ClicShopping and external services via standardized protocols.

What is MCP?

MCP is a communication protocol that enables applications to interact with language models and AI services in a standardized manner. In the context of ClicShopping, it facilitates:

  • Bidirectional communication between the e-commerce application and external AI servers
  • Integration of intelligent agents for task automation
  • Data access via secured REST APIs
  • Real-time monitoring and analytics of interactions

Importance in E-commerce

Advantages:

  • Intelligent automation: Automatic order management, product recommendations
  • 24/7 customer support: Smart chatbots for customer assistance
  • Advanced analytics: Predictive analysis of sales and customer behavior
  • Personalization: AI-based personalized recommendations
  • Inventory optimization: Demand forecasting and automatic management

Disadvantages:

  • Implementation complexity: Requires advanced technical skills
  • Infrastructure costs: External servers and AI services
  • External dependency: Risk of third-party service outages
  • Security: Management of tokens and secure access

Examples of potential implementations:

πŸ”— Social Media Integrations
  • Instagram Shopping: Automatic product synchronization with Instagram posts
  • Facebook Marketplace: Automatic publication of new products
  • TikTok Shop: Integration with TikTok trends for recommendations
  • Pinterest: Automatic creation of pins for popular products
🏒 ERP Integrations
  • SAP: Synchronization of stocks, orders, and customers
  • Oracle NetSuite: Accounting integration and financial management
  • Microsoft Dynamics: Synchronization of customer and sales data
  • Odoo: Full CRM/ERP integration with inventory management
πŸ“ˆ Marketing Integrations
  • Mailchimp: Automatic customer segmentation and targeted campaigns
  • HubSpot: Lead scoring and customer journey automation
  • Google Analytics 4: Advanced tracking of conversions and behavior
  • Facebook Ads: Automatic optimization of advertising campaigns
πŸ’³ Payment Integrations
  • Stripe: Management of subscriptions and recurring payments
  • PayPal: Integration of payments and refunds
  • Klarna: Installment payments and credit scoring
  • Apple Pay/Google Pay: Optimized mobile payments
πŸ“¦ Logistics Integrations
  • DHL/UPS/FedEx: Automatic shipping cost calculation and tracking
  • Amazon FBA: Amazon stock management and synchronization
  • Shopify Fulfillment: Optimization of distribution centers
  • ShipStation: Multi-carrier shipping automation
🎯 Analytics & BI Integrations
  • Tableau: Advanced sales dashboards
  • Power BI: Predictive analytics and automated reports
  • Google Data Studio: Marketing and performance reporting
  • Mixpanel: Advanced user event tracking
πŸ€– AI & Chatbot Integrations
  • OpenAI GPT: Smart chatbot for customer support
  • Dialogflow: Multilingual conversation management
  • Zendesk: Automation of support tickets
  • Intercom: Real-time chat with lead qualification
πŸ“± Mobile Integrations
  • React Native: Native mobile application
  • Flutter: Cross-platform iOS/Android app
  • PWA: Progressive Web Application
  • Push Notifications: Personalized notifications
πŸ” Security Integrations
  • Auth0: Advanced authentication and authorization
  • Okta: Identity and access management
  • Cloudflare: DDoS protection and CDN
  • Sentry: Real-time error monitoring

Examples of Integration Code

Example 1: Instagram Shopping Integration

// New MCP endpoint for Instagram
class InstagramIntegration extends \ClicShopping\OM\PagesAbstract
{
    public function syncProductsToInstagram(): void
    {
        $products = $this->getProductsForSync();
        
        foreach ($products as $product) {
            $instagramData = [
                'name' => $product['products_name'],
                'description' => $product['products_description'],
                'price' => $product['products_price'],
                'image_url' => $product['products_image'],
                'availability' => $product['products_quantity'] > 0 ? 'in stock' : 'out of stock'
            ];
            
            $this->postToInstagramAPI($instagramData);
        }
    }
}

Example 2: SAP ERP Integration

// Synchronization with SAP via MCP
class SAPIntegration extends \ClicShopping\OM\PagesAbstract
{
    public function syncOrdersToSAP(): void
    {
        $orders = $this->getPendingOrders();
        
        foreach ($orders as $order) {
            $sapData = [
                'order_number' => $order['orders_id'],
                'customer_code' => $order['customers_id'],
                'order_date' => $order['date_purchased'],
                'items' => $this->formatOrderItems($order['items'])
            ];
            
            $response = $this->sendToSAP($sapData);
            $this->updateOrderStatus($order['orders_id'], $response['status']);
        }
    }
}

Example 3: AI Chatbot with OpenAI

// Smart chatbot for customer support
class AIChatbot extends \ClicShopping\OM\PagesAbstract
{
    public function handleCustomerInquiry(string $message): array
    {
        $context = $this->getCustomerContext();
        
        $prompt = "As an e-commerce assistant, help this customer: " . $message;
        $prompt .= "\nCustomer context: " . json_encode($context);
        
        $response = $this->callOpenAI($prompt);
        
        // If necessary, create a support ticket
        if ($this->requiresHumanIntervention($response)) {
            $this->createSupportTicket($message, $context);
        }
        
        return [
            'response' => $response,
            'requires_human' => $this->requiresHumanIntervention($response),
            'suggested_products' => $this->extractProductSuggestions($response)
        ];
    }
}

Example 4: Predictive Analytics

// Sales prediction with AI
class PredictiveAnalytics extends \ClicShopping\OM\PagesAbstract
{
    public function predictSales(): array
    {
        $historicalData = $this->getSalesHistory();
        $externalFactors = $this->getExternalData(); // Weather, events, etc.
        
        $prediction = $this->runMLModel([
            'historical_sales' => $historicalData,
            'seasonality' => $this->getSeasonalityFactors(),
            'external_factors' => $externalFactors,
            'inventory_levels' => $this->getCurrentInventory()
        ]);
        
        return [
            'predicted_sales' => $prediction['sales'],
            'recommended_stock' => $prediction['stock_recommendations'],
            'confidence_score' => $prediction['confidence'],
            'risk_factors' => $prediction['risks']
        ];
    }
}

Concrete Use Cases

πŸ›’ B2C E-commerce

  • Personalized recommendations: β€œCustomers who bought this product also viewed…”
  • 24/7 chat support: Automatic assistance with escalation to a human
  • Intelligent inventory management: Stock-out prediction
  • Dynamic pricing: Automatic price adjustment based on competition

🏒 B2B E-commerce

  • Personalized catalog: Prices and products according to the customer
  • Large order management: ERP integration for high volumes
  • Automated reporting: Dashboards for resellers
  • Discount management: Automatic calculation based on commercial agreements

🎯 Marketplace

  • Multi-vendor synchronization: Centralized stock management
  • Fraud detection: Automatic detection of suspicious transactions
  • Fee optimization: Automatic commission calculation
  • Dispute management: Automation of resolution processes

πŸ“± Mobile Commerce

  • Smart push notifications: Personalized notifications
  • Geolocation: Location-based offers
  • Mobile payments: Apple Pay/Google Pay integration
  • Image recognition: Product search by photo

Measurable Business Benefits

πŸ“ˆ Sales Performance

  • +25% conversion thanks to personalized recommendations
  • -40% shopping cart abandonment with the smart chat
  • +30% average cart value via cross-sell suggestions
  • -60% order processing time with automation

πŸ’° Cost Optimization

  • -50% support costs with chat automation
  • -30% logistics costs with inventory optimization
  • -25% marketing costs with precise targeting
  • -70% human errors with process automation

🎯 Customer Experience

  • +90% customer satisfaction with 24/7 support
  • -80% response time to customer inquiries
  • +45% loyalty thanks to personalization
  • +60% problem resolution rate on first interaction

MCP Architecture

General Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   ClicShopping  │◄──►│    MCP Server   │◄──►│    AI Services  β”‚
β”‚   (PHP Core)    β”‚    β”‚  (Node.js/Python)β”‚    β”‚   (OpenAI, etc.)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     Database    β”‚    β”‚   Monitoring    β”‚    β”‚    Analytics    β”‚
β”‚                 β”‚    β”‚     & Logs      β”‚    β”‚    & Reports    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

ClicShopping MCP Architecture

The ClicShopping MCP system is organized into several components:

1. Core Classes

  • MCPConnector: Connection and protocol management
  • McpMonitor: Performance oversight and monitoring
  • McpService: Core services for MCP operations
  • McpDecisionAgent: Intelligent agent for automation

2. API Endpoints

  • /mcp&customersProducts: Products API
  • /mcp&ragBI: RAG (Retrieval-Augmented Generation) Interface for admins - the rag must ve activated
  • You are free to create other EndPoints (see example above)

3. Admin Configuration

  • Administration interface for configuring MCP servers
  • Token, port, SSL management
  • Real-time monitoring

What is Not Provided with the APP

The Chat

The chat interface is not included in the ClicShopping application. To implement it:

Chat construction and connection:

  1. Create a chat interface (HTML/CSS/JavaScript)
  2. Connect to the MCP server via WebSocket or HTTP
  3. Use the available API endpoints:
    // Example of chat connection
    const chatEndpoint = 'http://your-domain/index.php?mcp&customersProducts';
    
    // Sending a message
    fetch(chatEndpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token
      },
      body: JSON.stringify({
        message: 'Looking for products',
        context: {
          user_type: 'client',
          session_id: 'unique_session_id'
        }
      })
    });

    Β 

The Node.js/Python MCP Server

The external MCP server is not provided with the application. To build it:

Node.js MCP Server Example:

// Example of a Node.js MCP server
const express = require('express');
const app = express();

app.post('/mcp/products', async (req, res) => {
  // Logic for processing product requests
  const response = await processProductRequest(req.body);
  res.json(response);
});

app.listen(3000, () => {
  console.log('MCP server started on port 3000');
});

Server Connection:

  • Configuration in the ClicShopping admin: Host, Port, SSL, Token
  • API Usage: Access via the /Shop/json routes

Configuration and Usage

Configuration in the Administration

MCP configuration is done directly in the ClicShopping administration interface:

Available parameters:

  • Server Host: Address of the MCP server (default: localhost)
  • Server Port: Port of the MCP server (default: 3000)
  • SSL: Secure protocol activation
  • Token: Authentication token for security
  • Status: MCP module activation/deactivation

Alert configuration:

  • Latency thresholds: Maximum response time
  • Availability thresholds: Maximum downtime
  • Notifications: Email alert configuration

Access API - Shop Routes

The MCP API is accessible via the /Shop/json routes of ClicShopping:

1. CustomersProducts.php

This class serves as the main entry point for the MCP products API. It manages:

Main features:

  • Product list: GET ?mcp&customersProducts&action=products
    Product detail: GET ?mcp&customersProducts&action=product&id={ID}
    Search: GET ?mcp&customersProducts&action=search&query={TERM}
    Statistics: GET ?mcp&customersProducts&action=stats
    Categories: GET ?mcp&customersProducts&action=categories
    Recommendations: GET ?mcp&customersProducts&action=recommendations
    Customer chat: POST ?mcp&customersProducts (with JSON body)

    Β 

  • Β 

Example usage:

# Product list
curl "http://localhost/clicshopping_test/index.php?mcp&customersProducts&action=products&limit=5"

# Product search
curl "http://localhost/clicshopping_test/index.php?mcp&customersProducts&action=search&query=washcloth"

# Customer chat (POST)
curl -X POST "http://localhost/clicshopping_test/index.php?mcp&customersProducts" \
  -H "Content-Type: application/json" \
  -d '{"message": "I am looking for cleaning products", "context": {"user_type": "client"}}'

2. RagBI.php

RAG (Retrieval-Augmented Generation) interface identical to ClicShopping’s internal chat but accessible via MCP:
To use it, you must activate the Agent RAG-BI inside the administration.

Features:

  • Semantic queries: Smart search in the database
  • Analytical queries: Analysis of sales and performance data
  • OpenAI Integration: Use of language models for responses
  • Translation cache: Performance optimization

Example usage:

# RAG BI Query
curl -X POST "http://localhost/clicshopping_test/index.php?mcp&ragBI" \
  -H "Content-Type: application/json" \
  -d '{"message": "Give me a table of the evolution of turnover by month for the year 2025"}'

3. customerOrders.php

Customer order management API:

Features:

  • Order list: GET ?mcp&customerOrders&action=list_orders&customer_id={ID}
    Order detail: GET ?mcp&customerOrders&action=read_order&order_id={ID}
    Cancellation: POST ?mcp&customerOrders&action=cancel_order
    Messages: POST ?mcp&customerOrders&action=send_message
    History: GET ?mcp&customerOrders&action=history&order_id={ID}

    Β 

  • Β 

Examples of Future Implementation

Agentic Approach

The MCP system supports the implementation of intelligent agents for:

  1. Recommendation Agent:

    // Example of a Recommendation Agent
    class RecommendationAgent {
      public function analyzeCustomerBehavior($customerId) {
        // Analyze customer behavior
        // Generate personalized recommendations
      }
    }

    Β 

  2. Stock Management Agent:

    // Example of a Stock Management Agent
    class StockAgent {
      public function predictDemand($productId) {
        // Demand prediction
        // Optimization of stock levels
      }
    }

    Β 

  3. Customer Support Agent:

    // Example of a Support Agent
    class SupportAgent {
      public function handleCustomerInquiry($message) {
        // Process customer inquiries
        // Automatic escalation if necessary
      }
    }

    Β 


Monitoring and CronJobs

Monitoring System

The MCP system includes complete monitoring:

Monitored metrics:

  • Response time: Latency of MCP requests
  • Availability: Uptime of the MCP server
  • Errors: Error rate and error types
  • Security: Intrusion attempts and unauthorized access

Automatic alerts:

  • Performance thresholds: Alerts if response time > threshold
  • Service outages: Notifications in case of unavailability
  • Suspicious activities: Detection of attacks or abuse

CronJob Configuration

The MCP system uses scheduled tasks for:

1. Health Monitoring (every 5 minutes)

// CronJob: McpHealthCron
// Checks the health of the MCP server
// Stores alerts in the database
// Cleans up old alerts (>30 days)

2. Decision Agent (every 5 minutes)

// CronJob: mcp_agent
// Executes the intelligent decision agent
// Processes automated tasks
// Updates recommendations

CronJob Configuration:

Β 
# Add to crontab
*/5 * * * * /usr/bin/php /path/to/clicshopping/index.php?cronId={CRON_ID}

Security

Authentication and Authorization

Access Tokens:

  • Secure generation: Unique tokens per session
  • Automatic expiration: Token rotation
  • Validation: Verification on every request

Endpoint protection:

  • Configured CORS: Controlled access by origin
  • Parameter validation: Input sanitization
  • Production mode: Access restrictions in production

Security Best Practices

  1. Use HTTPS in production
  2. Configure strong tokens and renew them regularly
  3. Limit access by IP if necessary
  4. Monitor logs to detect suspicious activities
  5. Regularly update dependencies

Troubleshooting

Common Problems

1. Connection to the MCP server fails

  • Check the configuration (host, port, SSL)
  • Verify that the MCP server is started
  • Check error logs

2. Authentication errors

  • Verify the token validity
  • Check permission configuration
  • Check security logs

3. Degraded performance

  • Check monitoring metrics
  • Optimize database queries
  • Increase resource limits

Logs and Debugging

Log files:

  • MCP Logs: Available in the database and admin interface (export) for various traceability
  • PHP Error Logs: Standard PHP configuration
  • Monitoring Logs: mcp_alerts database

Support and Resources

Additional Documentation

Link to post
Guest
This topic is now closed to further replies.
Γ—
Γ—
  • Create New...

Important Information

By using this site, you agree to our Terms of Use