File size: 13,578 Bytes
2be6245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
PrestaShop MCP Server
A Model Context Protocol server that provides tools for accessing PrestaShop product data.
"""

import asyncio
import json
import logging
from typing import Any, Dict, List, Optional
from urllib.parse import urlencode

import httpx
from mcp.server import Server
from mcp.types import (
    Resource,
    Tool,
    TextContent,
    ImageContent,
    EmbeddedResource,
    CallToolRequest,
    CallToolResult,
    ListToolsRequest,
    ListToolsResult,
    ListResourcesRequest,
    ListResourcesResult,
    ReadResourceRequest,
    ReadResourceResult,
)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Default PrestaShop API configuration
DEFAULT_API_BASE = "https://shop.mcp.integration.ambris.com"
DEFAULT_TIMEOUT = 30

class PrestaShopMCPServer:
    """MCP Server for PrestaShop integration"""
    
    def __init__(self, api_base: str = DEFAULT_API_BASE):
        self.api_base = api_base.rstrip('/')
        self.server = Server("prestashop-mcp")
        self.setup_handlers()
    
    def setup_handlers(self):
        """Set up MCP server handlers"""
        
        @self.server.list_tools()
        async def list_tools() -> List[Tool]:
            """List available tools"""
            return [
                Tool(
                    name="get_product_details",
                    description="Get detailed information about a PrestaShop product including name, description, price, and features",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "product_id": {
                                "type": "integer",
                                "description": "The ID of the product to retrieve"
                            },
                            "lang_id": {
                                "type": "integer", 
                                "description": "Language ID for localized content",
                                "default": 1
                            }
                        },
                        "required": ["product_id"]
                    }
                ),
                Tool(
                    name="get_product_features",
                    description="Get product features and specifications from PrestaShop",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "product_id": {
                                "type": "integer",
                                "description": "The ID of the product to get features for"
                            }
                        },
                        "required": ["product_id"]
                    }
                ),
                Tool(
                    name="get_product_images",
                    description="Get product images and media from PrestaShop",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "product_id": {
                                "type": "integer", 
                                "description": "The ID of the product to get images for"
                            }
                        },
                        "required": ["product_id"]
                    }
                ),
                Tool(
                    name="search_products",
                    description="Search for products in PrestaShop catalog",
                    inputSchema={
                        "type": "object",
                        "properties": {
                            "query": {
                                "type": "string",
                                "description": "Search query term"
                            },
                            "limit": {
                                "type": "integer",
                                "description": "Maximum number of results to return",
                                "default": 10
                            },
                            "category_id": {
                                "type": "integer",
                                "description": "Optional category ID to filter results"
                            }
                        },
                        "required": ["query"]
                    }
                )
            ]
        
        @self.server.call_tool()
        async def call_tool(name: str, arguments: Dict[str, Any]) -> List[TextContent]:
            """Handle tool calls"""
            try:
                if name == "get_product_details":
                    return await self._get_product_details(arguments)
                elif name == "get_product_features":
                    return await self._get_product_features(arguments)
                elif name == "get_product_images":
                    return await self._get_product_images(arguments)
                elif name == "search_products":
                    return await self._search_products(arguments)
                else:
                    return [TextContent(
                        type="text",
                        text=f"Unknown tool: {name}"
                    )]
            except Exception as e:
                logger.error(f"Error calling tool {name}: {e}")
                return [TextContent(
                    type="text",
                    text=f"Error calling tool {name}: {str(e)}"
                )]
    
    async def _make_api_request(self, endpoint: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
        """Make HTTP request to PrestaShop API"""
        url = f"{self.api_base}/index.php"
        
        # Default parameters
        default_params = {
            "fc": "module",
            "module": "ambaiagent", 
            "controller": "api"
        }
        
        if params:
            default_params.update(params)
        
        async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
            try:
                response = await client.get(url, params=default_params)
                response.raise_for_status()
                
                data = response.json()
                if not data.get('success', False):
                    raise Exception(f"API error: {data.get('error', 'Unknown error')}")
                
                return data
                
            except httpx.TimeoutException:
                raise Exception("Request timeout - PrestaShop API took too long to respond")
            except httpx.HTTPStatusError as e:
                raise Exception(f"HTTP error {e.response.status_code}: {e.response.text}")
            except json.JSONDecodeError:
                raise Exception("Invalid JSON response from PrestaShop API")
    
    async def _get_product_details(self, arguments: Dict[str, Any]) -> List[TextContent]:
        """Get detailed product information"""
        product_id = arguments.get("product_id")
        lang_id = arguments.get("lang_id", 1)
        
        if not product_id:
            return [TextContent(
                type="text",
                text="Error: product_id is required"
            )]
        
        try:
            data = await self._make_api_request("", {
                "action": "get_product",
                "product_id": product_id,
                "lang_id": lang_id
            })
            
            product = data.get("product", {})
            
            # Format the product information
            result = f"""PRESTASHOP PRODUCT DETAILS (ID: {product_id})

Name: {product.get('name', 'N/A')}
Description: {product.get('description', 'N/A')}
Short Description: {product.get('description_short', 'N/A')}
Price: {product.get('price', 'N/A')}
Reference: {product.get('reference', 'N/A')}
EAN13: {product.get('ean13', 'N/A')}
Weight: {product.get('weight', 'N/A')}
Quantity: {product.get('quantity', 'N/A')}
Active: {product.get('active', 'N/A')}
Available for Order: {product.get('available_for_order', 'N/A')}

Categories: {json.dumps(product.get('categories', []), indent=2)}
Features: {json.dumps(product.get('features', []), indent=2)}
Images: {json.dumps(product.get('images', []), indent=2)}

Full Product Data:
{json.dumps(product, indent=2)}"""
            
            return [TextContent(type="text", text=result)]
            
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"Error retrieving product {product_id}: {str(e)}"
            )]
    
    async def _get_product_features(self, arguments: Dict[str, Any]) -> List[TextContent]:
        """Get product features"""
        product_id = arguments.get("product_id")
        
        if not product_id:
            return [TextContent(
                type="text", 
                text="Error: product_id is required"
            )]
        
        try:
            data = await self._make_api_request("", {
                "action": "get_product",
                "product_id": product_id
            })
            
            product = data.get("product", {})
            features = product.get("features", [])
            
            if not features:
                result = f"No features found for product {product_id}"
            else:
                result = f"PRESTASHOP PRODUCT FEATURES (ID: {product_id}):\n\n"
                result += json.dumps(features, indent=2)
            
            return [TextContent(type="text", text=result)]
            
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"Error retrieving features for product {product_id}: {str(e)}"
            )]
    
    async def _get_product_images(self, arguments: Dict[str, Any]) -> List[TextContent]:
        """Get product images"""
        product_id = arguments.get("product_id")
        
        if not product_id:
            return [TextContent(
                type="text",
                text="Error: product_id is required"
            )]
        
        try:
            data = await self._make_api_request("", {
                "action": "get_product",
                "product_id": product_id
            })
            
            product = data.get("product", {})
            images = product.get("images", [])
            
            if not images:
                result = f"No images found for product {product_id}"
            else:
                result = f"PRESTASHOP PRODUCT IMAGES (ID: {product_id}):\n\n"
                result += json.dumps(images, indent=2)
            
            return [TextContent(type="text", text=result)]
            
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"Error retrieving images for product {product_id}: {str(e)}"
            )]
    
    async def _search_products(self, arguments: Dict[str, Any]) -> List[TextContent]:
        """Search for products"""
        query = arguments.get("query")
        limit = arguments.get("limit", 10)
        category_id = arguments.get("category_id")
        
        if not query:
            return [TextContent(
                type="text",
                text="Error: query is required"
            )]
        
        try:
            params = {
                "action": "search_products",
                "query": query,
                "limit": limit
            }
            
            if category_id:
                params["category_id"] = category_id
            
            data = await self._make_api_request("", params)
            
            products = data.get("products", [])
            
            if not products:
                result = f"No products found for query: '{query}'"
            else:
                result = f"PRESTASHOP PRODUCT SEARCH RESULTS for '{query}':\n\n"
                result += json.dumps(products, indent=2)
            
            return [TextContent(type="text", text=result)]
            
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"Error searching for products with query '{query}': {str(e)}"
            )]
    
    async def run(self, transport_type: str = "stdio"):
        """Run the MCP server"""
        if transport_type == "stdio":
            from mcp.server.stdio import stdio_server
            async with stdio_server() as (read_stream, write_stream):
                await self.server.run(
                    read_stream,
                    write_stream,
                    self.server.create_initialization_options()
                )
        else:
            raise ValueError(f"Unsupported transport type: {transport_type}")

def main():
    """Main entry point"""
    import argparse
    
    parser = argparse.ArgumentParser(description="PrestaShop MCP Server")
    parser.add_argument(
        "--api-base",
        default=DEFAULT_API_BASE,
        help="PrestaShop API base URL"
    )
    parser.add_argument(
        "--transport",
        choices=["stdio"],
        default="stdio", 
        help="Transport mechanism"
    )
    
    args = parser.parse_args()
    
    server = PrestaShopMCPServer(api_base=args.api_base)
    
    try:
        asyncio.run(server.run(args.transport))
    except KeyboardInterrupt:
        logger.info("Server stopped by user")
    except Exception as e:
        logger.error(f"Server error: {e}")
        raise

if __name__ == "__main__":
    main()