DEV Community

Cover image for PrestaShop MCP Server Tutorial: How to Connect Your Store to AI Agents (2025)
Nicolas Dabene
Nicolas Dabene

Posted on • Originally published at nicolas-dabene.fr

PrestaShop MCP Server Tutorial: How to Connect Your Store to AI Agents (2025)

Unlock Your PrestaShop's AI Potential: A Guide to MCP Server Integration (2025)

Connect Your E-commerce to Intelligent AI Agents with MCP for PrestaShop

Envision this: you prompt your AI assistant, "Show me the top 10 products by sales this month and create a marketing report." Moments later, a comprehensive document arrives, complete with performance metrics, tailored recommendations, and merchandising ideas. Far from future fantasy, this capability is made real by ps_mcp_server, the innovative PrestaShop module designed to bridge your online store with advanced AI agents using the Model Context Protocol (MCP).

Throughout my extensive career in e-commerce development, few technologies have offered such profound promise for intelligent automation. MCP transforms your PrestaShop platform into a dynamic conversational API, allowing AI agents to function as genuine business partners, adept at executing intricate tasks.

Introducing the Model Context Protocol (MCP)

MCP is more than just another application programming interface; it's a meticulously crafted, stateful protocol engineered for seamless AI-system interactions. Unlike conventional REST APIs where each request operates in isolation, MCP maintains a continuous dialogue. Your AI assistant retains vital information such as language preferences, previously viewed items, and past searches, ensuring a more intuitive and efficient experience.

The ps_mcp_server module serves as the vital link between this groundbreaking protocol and the robust PrestaShop environment. Built for PHP 8.1+ and PrestaShop 8+, this module effectively exposes your store's business logic as discoverable "tools" that Large Language Models (LLMs) can automatically identify and leverage.

Current Compatibility Insight: As of this publication, PrestaShop's MCP Server officially supports ChatGPT. However, given MCP's open-source and standardized nature, we anticipate broader compatibility with other leading LLMs (like Claude, Gemini, and Dust) in the near future. The architectural design discussed here is inherently built to function with any MCP-compliant AI agent.

The key benefit of this standardized methodology? You define your business functionalities once, and every MCP-compatible AI agent can utilize them as platform support expands, eliminating the need for separate integrations for each AI service.

Why MCP Revolutionizes PrestaShop Commerce

A Protocol Tailored for Artificial Intelligence

MCP addresses a core challenge: how can AI reliably interact with complex business systems? Traditional methods, such as web scraping or generic APIs, often fall short because they lack the structured context crucial for LLMs to operate effectively.

With MCP, every exposed tool comes with built-in documentation that the AI agent can parse and comprehend. Consider it a self-describing API specifically optimized for machine intelligence. The agent inherently understands the required parameters, expected responses, and how to combine multiple tools for sophisticated workflows.

Inside the ps_mcp_server Module Architecture

This module incorporates three critical components to empower your PrestaShop store:

  • The integrated MCP server: This component actively listens for AI agent requests, dynamically identifies available tools using PHP attributes, and manages ongoing session states.
  • The embedded MCP client: Essential for STDIO (Standard Input/Output) communication, this client is especially valuable for development purposes and for standalone module operations.
  • The automated discovery engine: This system efficiently scans your modules for classes marked with #[McpTool], significantly reducing manual configuration effort.

This design ensures your MCP server remains perfectly aligned with your underlying business code, requiring minimal additional maintenance.

Setup and Initial Configuration Steps

Essential Technical Prerequisites

Before beginning, confirm your environment meets the necessary specifications:

  • PrestaShop 8.x or newer: The module relies on modern PrestaShop features, necessitating this version for optimal stability.
  • PHP 8.1 or higher: PHP attributes, a form of modern annotations, are central to the tool discovery process. PHP 8.1 also delivers vital performance enhancements for potentially resource-intensive AI tasks.
  • An MCP-enabled client: To effectively test and utilize your server, options include Claude Desktop, Dust, Gemini CLI, or MCP Inspector (a dedicated debugging utility without AI).

Understanding the File Structure

Upon installation, the module automatically creates a .mcp directory within its root folder, which contains:

  • .cache: This directory stores the tool discovery cache, designed to boost performance. Deleting this cache forces a fresh scan.
  • .logs: Here, you'll find comprehensive log files (activated via module configuration) which are indispensable for troubleshooting AI interactions.

This logical arrangement ensures that MCP configurations are kept distinctly separate from your standard PrestaShop codebase.

Making Your Module MCP-Compatible

Implementing the isMcpCompliant() Method

Before any tools can be exposed, you must explicitly inform ps_mcp_server that your module supports MCP. This clear declaration prevents unnecessary scanning and allows for precise management of which modules are AI-ready.

Simply incorporate the following method into your module's main class:

<?php

class Ps_MySuperModule extends Module
{
    /**
     * Declares this module as MCP-compatible.
     *
     * This function enables ps_mcp_server to
     * automatically locate tools defined within this module
     * through the use of PHP attributes like #[McpTool].
     */
    public function isMcpCompliant()
    {
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

And that’s all! Once this method is present, the ps_mcp_server module will automatically scan your src/Mcp/Tools directory for classes containing MCP tools.

Rationale Behind This Approach

This opt-in strategy provides several key benefits: it avoids scanning all installed modules, thereby improving performance; it permits staged activation, giving you control over when a module becomes MCP-ready; and it simplifies debugging by providing clear logs on scanned modules.

Within the module's logs (.mcp/.logs), you will observe your module listed among the discovered MCP-compliant modules, along with a count of the tools identified.

Crafting Your First MCP Tool

Deconstructing an MCP Tool

An MCP tool is essentially a PHP method augmented with specific attributes that inform AI agents about its functionality. Let's walk through a practical example: a tool for searching products by name.

Create a file named src/Mcp/Tools/ProductSearchTool.php within your module:

<?php

namespace PrestaShop\Module\MySuperModule\Mcp\Tools;

use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;
use Product;

class ProductSearchTool
{
    /**
     * Locates products by their name using fuzzy matching.
     *
     * @param string $searchTerms Search queries, potentially separated by semicolons.
     * @param int $langId Identifier for the search language (defaults to preferred language).
     * @param int $limit Maximum number of results to retrieve (defaults to 10).
     * @return array A collection of found products with their associated details.
     */
    #[McpTool(
        name: 'search_product_by_name',
        description: 'Searches for products in the store by name only. Supports fuzzy matching. Results are ordered by relevance.'
    )]
    #[Schema(
        properties: [
            'searchTerms' => [
                'type' => 'string',
                'description' => 'Terms for searching. Multiple terms can be provided, separated by semicolons.'
            ],
            'langId' => [
                'type' => 'integer',
                'description' => 'The language ID for the search. Defaults to the context\'s preferred language.',
                'default' => 1
            ],
            'limit' => [
                'type' => 'integer',
                'description' => 'The maximum number of product results to return.',
                'default' => 10
            ]
        ],
        required: ['searchTerms']
    )]
    public function searchProducts(string $searchTerms, int $langId = 1, int $limit = 10): array
    {
        // Divide the input string into separate search terms.
        $terms = explode(';', $searchTerms);

        // Apply PrestaShop's built-in fuzzy search logic.
        $results = Product::searchByName($langId, $terms[0]);

        // Truncate the results based on the specified limit.
        return array_slice($results, 0, $limit);
    }
}
Enter fullscreen mode Exit fullscreen mode

Unpacking the Attributes

The #[McpTool] attribute establishes your tool's core identity:

  • The name attribute must be unique, clearly descriptive, and formatted in snake_case. This is the exact identifier the AI agent will use to invoke your tool.
  • The description is critically important: it instructs the AI agent on precisely when and how to deploy this tool. Be explicit about its use cases, any limitations, and the method of result sorting.

The #[Schema] attribute defines the parameters your tool accepts:

  • properties enumerates each parameter, specifying its data type, a comprehensive description, and optionally a default value.
  • required indicates which parameters are compulsory. An AI agent omitting a required parameter will receive a distinct error message.

Robust Input Validation

While MCP automatically performs type validation based on your Schema, it's always wise to incorporate additional sanity checks within your code:

public function searchProducts(string $searchTerms, int $langId = 1, int $limit = 10): array
{
    // Fundamental validation for search terms.
    if (empty(trim($searchTerms))) {
        throw new \InvalidArgumentException('Search terms cannot be empty.');
    }

    // Set a practical limit to prevent system overload.
    if ($limit > 100) {
        $limit = 100;
    }

    // Verify the existence of the specified language ID.
    if (!Language::getLanguage($langId)) {
        throw new \InvalidArgumentException("Invalid language ID provided: {$langId}.");
    }

    // Your specific business logic follows...
}
Enter fullscreen mode Exit fullscreen mode

AI agents can sometimes generate unexpected values. These validation layers are crucial for safeguarding your system against erratic or malicious behavior.

Principles of Effective AI Tool Design

Clear and Focused Descriptions

Your tool descriptions are primarily for machine interpretation, not human. Therefore, optimize them for maximum LLM comprehension:

  • Be explicit about data formats: use "Date in YYYY-MM-DD format" instead of just "Date."
  • Specify limitations: include "Maximum 100 results" in both the description and the schema.
  • Guide agents towards alternatives: state "For advanced search options, refer to search_product_advanced."
  • Clarify sorting mechanisms: "Results are ordered by decreasing relevance."

The quality of your tool descriptions makes a significant difference. An AI agent relies on these descriptions to determine the appropriate tool and how to utilize it. Consider this transformation:

Ambiguous description:

description: 'Retrieves products'
Enter fullscreen mode Exit fullscreen mode

Refined description:

description: 'Locates products by their name only. Fuzzy matching is active. Results are sorted by relevance. For searches based on category or price, utilize the search_product_advanced tool.'
Enter fullscreen mode Exit fullscreen mode

The enhanced version clearly defines the search type, operational behavior (fuzzy matching), result ordering, and even suggests an alternative tool for different search needs.

Maintain Consistent Terminology

Adopt uniform vocabulary across all your tools. If you use langId for a language parameter in one tool, avoid switching to languageId in another. This consistency helps agents build connections between different tools and effectively plan multi-step workflows.

Example of standardized vocabulary:

// ✅ Consistent across all tools
'langId' => 'Language ID'
'limit' => 'Maximum number of results'
'offset' => 'Starting point for pagination'

// ❌ Inconsistent
Tool 1: 'langId', 'maxResults', 'start'
Tool 2: 'languageId', 'limit', 'offset'
Enter fullscreen mode Exit fullscreen mode

Managing Query Complexity

Protect your server from excessively demanding queries. A misconfigured AI agent could, for instance, request 10,000 products simultaneously, leading to database overload.

#[Schema(
    properties: [
        'limit' => [
            'type' => 'integer',
            'description' => 'Maximum number of results (cap at 100)',
            'default' => 10,
            'maximum' => 100  // Enforced technical limit
        ]
    ]
)]
public function searchProducts(string $searchTerms, int $limit = 10): array
{
    // A final check to ensure the limit is honored.
    $limit = min($limit, 100);

    // Proceed with search logic, respecting the applied limit...
}
Enter fullscreen mode Exit fullscreen mode

This proactive, defensive strategy guarantees stable system performance, even when interacting with less-than-optimally configured AI agents.

State Management Capabilities with MCP

The Stateful Protocol: A Core MCP Advantage

Unlike conventional REST APIs, MCP operates as a stateful protocol. This means the server actively preserves contextual information for each connected client, significantly enhancing the user experience.

Consider an AI agent assisting a French-speaking customer. Instead of repeatedly specifying langId: 2 for every tool call, the agent can store this preference within the session state:

// Initial interaction: agent identifies the user's preferred language.
$context->setState('preferred_lang', 2);

// Subsequent tool invocations: the language is automatically retrieved and used.
$langId = $context->getState('preferred_lang', 1);
Enter fullscreen mode Exit fullscreen mode

Practical State Use Cases

  • Personalization: Storing preferences like preferred language, currency, or shipping country.
  • Interaction History: Recalling viewed products to offer more relevant recommendations.
  • Multi-step Processes: Enabling an agent to progressively build a shopping cart by remembering previous selections.
  • Query Optimization: Caching frequently accessed data within the session for faster retrieval.

While state management is not strictly mandatory, it undeniably facilitates smoother, more natural interactions for the end-user.

HTTP Connection for Production Environments

Benefits of HTTP Transport

For production deployments, HTTP is the recommended transport mechanism due to several compelling reasons:

  • Broad Compatibility: All major MCP clients (Claude, ChatGPT, Dust, Gemini) natively support HTTP.
  • Scalability: An HTTP server can efficiently manage hundreds of concurrent connections.
  • Robust Security: Features such as token authentication, HTTPS encryption, and granular permission management are readily available.
  • Comprehensive Monitoring: Facilitates centralized logging, performance metric tracking, and anomaly detection.

Configuring for Various Clients

Claude Desktop requires a local JSON configuration file that points to your server and includes your authentication token:

{
  "mcpServers": {
    "prestashop-shop": {
      "url": "https://your-store.com/modules/ps_mcp_server/endpoint",
      "token": "your-secure-token"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Dust and Gemini CLI currently provide the most straightforward connection, utilizing a simple token without requiring OAuth. These are excellent choices for initial production testing.

For ChatGPT and other clients, OAuth2 support will be introduced in upcoming module versions (V1). For now, Dust or Gemini are preferable for production use.

Essential Security Considerations

When using HTTP, security must be a top priority:

  • Always deploy HTTPS in production environments; never use plain HTTP.
  • Regularly refresh your authentication tokens (a refresh every 30 days is advisable).
  • Activate logging to monitor for any unusual or suspicious tool invocations.
  • Implement rate limiting (planned for the next module version) to guard against abuse.

Debugging and Monitoring Your MCP Server

Analyzing Log Files

The .mcp/.logs directory contains invaluable debugging information:

  • mcp-server.log: Records all incoming requests, executed tools, and any errors encountered.
  • tool-discovery.log: Displays results from module scans, detailing discovered tools and any attribute-related errors.
  • session.log: Logs the creation and destruction of sessions, along with client-specific state management events.

Enable logs during development phases for detailed insights; for performance reasons, disable them in production unless actively diagnosing an issue.

MCP Inspector: Your Ultimate Debugging Companion

MCP Inspector is a dedicated graphical debugging tool that connects directly to your server without involving any AI. It’s perfect for:

  • Confirming that your tools are being correctly discovered.
  • Testing tool calls with a variety of parameters.
  • Observing tool responses without the inherent unpredictability of an AI agent.
  • Validating your JSON schema before integrating a live AI client.

Install it via npm and direct it to your MCP server. You will immediately see all your tools listed, complete with their full documentation.

Common Issues and Their Solutions

  • "No tools discovered": Ensure isMcpCompliant() returns true in your module, your tool classes reside in src/Mcp/Tools, and #[McpTool] attributes are correctly imported.
  • "Invalid token": Regenerate a fresh token in the module configuration and copy it precisely, avoiding any trailing spaces.
  • "Connection timeout": In STDIO mode, verify that the PHP process has execution permissions. For HTTP connections, inspect your web server configuration and firewall rules.

Best Practices for Crafting AI Agent Tools

Self-Describing Documentation

Your tool descriptions are read by machines. Optimize them for LLM understanding:

  • Precision in Formats: Instead of "Date," specify "Date in YYYY-MM-DD format."
  • Clear Limitations: Explicitly state "Maximum 100 results" in both the description and the schema.
  • Guidance to Alternatives: Suggest "For comprehensive searches, consider search_product_advanced."
  • Explanation of Sorting: Describe "Results are sorted by decreasing relevance."

Robust Permission Management

Even with MCP handling authentication, implement additional permission checks within your tools:

public function updateProduct(int $productId, array $data): array
{
    // Validate the access rights of the user associated with the session.
    if (!$this->context->employee->hasAccess('AdminProducts', 'edit')) {
        throw new \PrestaShopException('Insufficient permissions to modify products.');
    }

    // Perform validation on the provided data.
    $this->validateProductData($data);

    // Safely update the product.
    $product = new Product($productId);
    $product->hydrate($data);
    $product->save();

    return ['success' => true, 'id' => $productId];
}
Enter fullscreen mode Exit fullscreen mode

This layered security approach ensures that even if a token is compromised, standard PrestaShop permissions remain enforced.

Preventing Infinite Loops

AI agents can occasionally fall into repetitive patterns, calling the same tool repeatedly with similar parameters. Implement mechanisms to detect and prevent such behaviors:

private function detectLoop(string $toolName, array $params): void
{
    $sessionHistory = $this->context->getState('tool_history', []);

    // Record the current tool invocation.
    $sessionHistory[] = [
        'tool' => $toolName,
        'params' => $params,
        'timestamp' => time()
    ];

    // Maintain a record of the last 10 calls.
    $sessionHistory = array_slice($sessionHistory, -10);

    // Identify if the same tool has been called 5 or more times with identical parameters.
    $similarCalls = array_filter($sessionHistory, function($call) use ($toolName, $params) {
        return $call['tool'] === $toolName &&
               json_encode($call['params']) === json_encode($params);
    });

    if (count($similarCalls) >= 5) {
        throw new \RuntimeException("Looping behavior detected: tool '{$toolName}' invoked 5 times with identical parameters.");
    }

    $this->context->setState('tool_history', $sessionHistory);
}
Enter fullscreen mode Exit fullscreen mode

This straightforward protective measure helps avert catastrophic scenarios where a malfunctioning agent could overwhelm your server.

Full Example: A Boilerplate Module

Recommended Directory Structure

To jumpstart your development, consider using the ps_mcp_boilerplate repository, which offers a complete foundational structure:

ps_my_mcp_module/
├── ps_my_mcp_module.php          # Primary module class containing isMcpCompliant()
├── src/
│   └── Mcp/
│       └── Tools/
│           ├── ProductSearchTool.php
│           ├── OrderManagementTool.php
│           └── CustomerAnalyticsTool.php
├── config/
│   └── services.yml               # Symfony configuration for Dependency Injection
└── README.md
Enter fullscreen mode Exit fullscreen mode

Comprehensive Tool Implementation

Here's a practical example of an order management tool:

<?php

namespace PrestaShop\Module\MyMcpModule\Mcp\Tools;

use PhpMcp\Server\Attributes\McpTool;
use PhpMcp\Server\Attributes\Schema;
use Order;
use Context;

class OrderManagementTool
{
    private Context $context;

    public function __construct(Context $context)
    {
        $this->context = $context;
    }

    #[McpTool(
        name: 'get_recent_orders',
        description: 'Retrieves recent orders, with options for filtering. Returns order ID, customer details, total amount, and status. Results are sorted by descending date.'
    )]
    #[Schema(
        properties: [
            'limit' => [
                'type' => 'integer',
                'description' => 'The number of orders to fetch (maximum: 50)',
                'default' => 10
            ],
            'status' => [
                'type' => 'string',
                'description' => 'Filter orders by status: pending, paid, shipped, delivered, cancelled',
                'default' => null
            ],
            'days' => [
                'type' => 'integer',
                'description' => 'Retrieve orders from the last N days (maximum: 90)',
                'default' => 7
            ]
        ]
    )]
    public function getRecentOrders(
        int $limit = 10,
        ?string $status = null,
        int $days = 7
    ): array {
        // Apply robust validations.
        $limit = min($limit, 50);
        $days = min($days, 90);

        // Construct the query based on parameters.
        $dateFrom = date('Y-m-d', strtotime("-{$days} days"));

        $orders = Order::getOrdersWithInformations(
            $limit,
            0, // starting offset
            ['date_add', 'DESC']
        );

        // Filter the results by status if a specific status is provided.
        if ($status) {
            $orders = array_filter($orders, function($order) use ($status) {
                return strtolower($order['order_state']) === strtolower($status);
            });
        }

        // Standardize and format the output.
        return array_map(function($order) {
            return [
                'id' => $order['id_order'],
                'reference' => $order['reference'],
                'customer' => [
                    'id' => $order['id_customer'],
                    'name' => $order['customer_name'],
                    'email' => $order['customer_email']
                ],
                'total' => (float) $order['total_paid'],
                'currency' => $order['currency'],
                'status' => $order['order_state'],
                'date' => $order['date_add']
            ];
        }, $orders);
    }
}
Enter fullscreen mode Exit fullscreen mode

This example tool effectively demonstrates all recommended best practices: rigorous validation, clear descriptions, strong type hinting, and consistent result formatting.

Elevating Your Store with MCP Tools Plus

If you aim to fully harness the power of PrestaShop's MCP Server without the overhead of building all your own tools, MCP Tools Plus offers a ready-to-use solution that significantly enhances the server's core capabilities.

A Ready-to-Use Advanced Implementation

Developed by BusinessTech/PrestaModule, MCP Tools Plus is a premium module designed to augment the PS MCP Server with sophisticated management functionalities. It transforms your AI assistant into a proactive management ally, capable of:

  • Automated Financial Reporting: Extracting and formatting sales data for accounting, complete with integrated PDF export and email functionalities.
  • Orchestrated Marketing Campaigns: Facilitating advanced customer segmentation, generating personalized promotional codes, and executing multi-stage marketing workflows.
  • Catalog Optimization: Automatically identifying high-potential or underperforming products and suggesting concrete actions for improvement.
  • Third-Party Service Integration: Offering native connectivity with services like Qonto (for payment verification) and Brevo (for email campaigns), with more business tools anticipated as the MCP protocol gains wider adoption.

A Modular and Scalable Design

The architecture of MCP Tools Plus perfectly embodies the modular vision of MCP. Each feature is exposed as an independent tool that your AI agent can intelligently discover and combine. This design ensures continuous evolution and adaptability to your specific operational requirements.

To delve deeper into specific use cases, explore real-world automation scenarios, and grasp how MCP Tools Plus can revolutionize your daily management, consult our comprehensive guide: PrestaShop MCP Server & MCP Tools Plus: The Ultimate AI Assistant Guide.

Essential References and Further Learning

Official Documentation

  • Model Context Protocol: The complete protocol specification is available at modelcontextprotocol.io. Dive in to explore advanced concepts like resources, prompts, and sampling.
  • PHP-MCP: Server and client libraries are extensively documented at github.com/php-mcp. Here, you'll find examples of advanced attributes and common development patterns.

Boost Your E-commerce Productivity with MCP Tools Plus

Imagine transforming your PrestaShop store into an intelligent, AI-powered platform using pre-built, powerful tools.

Automated Reports

Generate detailed accounting and analytics reports in seconds, streamlining your financial oversight.

Smart Marketing

Leverage advanced customer segmentation and AI-driven personalized campaigns to connect more effectively with your audience.

Comprehensive Automation

Implement complex workflows and simplify integrations with third-party services, enhancing operational efficiency.

✨ Discover MCP Tools Plus

This advanced suite of tools extends the core PS MCP Server, equipping it with intelligent management features. It’s designed to evolve your AI assistant into an indispensable management partner.

  • Simple installation
  • PrestaShop 8+ compatible

Ready to enhance your PrestaShop store's capabilities? Learn more about MCP Tools Plus here.

Final Thoughts

The Model Context Protocol marks a significant shift in how our PrestaShop stores can interact with artificial intelligence. By intelligently exposing your business logic through clearly defined tools, you cultivate an ecosystem where AI agents become invaluable assistants, capable of automating complex and time-consuming tasks.

The ps_mcp_server module makes this powerful integration accessible to any PHP developer familiar with the PrestaShop platform. Its attribute-based approach drastically streamlines development: simply define your tools, annotate them appropriately, and the system seamlessly handles their exposure to AI agents.

The potential applications are vast and exciting: automated product management, insightful predictive sales analysis, responsive intelligent customer support, on-demand report generation, and dynamic pricing optimization. Truly, your imagination is the only constraint.

Begin by developing a straightforward tool, perhaps a product search function. Test it rigorously with MCP Inspector, then integrate Claude or Gemini to start experimenting with intelligent automation. You will quickly grasp the transformative power that MCP brings to your e-commerce operations.


Stay Connected and Explore More!

Enjoyed this deep dive into PrestaShop MCP Server? Don't miss out on future insights, tutorials, and e-commerce innovations!

  • Subscribe to my YouTube channel: For hands-on demos, development tips, and expert discussions, head over to @ndabene06.
  • Connect with me on LinkedIn: Join my professional network for updates on cutting-edge e-commerce technology and industry trends: Nicolas Dabène on LinkedIn.

Let's continue building the future of e-commerce together!

Top comments (0)