π‘ Examples & Use Cases
Real-world examples of how to use the SFCC Development MCP Server with AI assistants for common development tasks.
π Quick Start Examples
Create a New SFCC Controller
User: βCreate a new SFCC controller for product search with proper error handlingβ
AI Assistant Response:
// Generated using SFRA best practices
'use strict';
var server = require('server');
var Logger = require('dw/system/Logger');
var ProductSearchModel = require('*/cartridge/models/search');
var ProductFactory = require('*/cartridge/scripts/factories/product');
var cache = require('*/cartridge/scripts/middleware/cache');
server.get('Show', cache.applyDefaultCache, function (req, res, next) {
var searchPhrase = req.querystring.q;
var categoryId = req.querystring.cgid;
try {
var searchModel = new ProductSearchModel(req.querystring, req.locale.id);
searchModel.search();
if (!searchModel.count) {
res.setStatusCode(404);
res.render('error/notfound');
return next();
}
var products = ProductFactory.get({
products: searchModel.productIds,
viewType: 'tile',
variationModel: req.querystring.variationModel
});
res.render('search/searchresults', {
searchModel: searchModel,
products: products,
searchPhrase: searchPhrase
});
} catch (e) {
var logger = Logger.getLogger('ProductSearch');
logger.error('Product search error: ' + e.message);
res.setStatusCode(500);
res.render('error/somethingwentwrong');
}
next();
});
module.exports = server.exports();
The AI automatically used SFRA patterns, proper error handling, caching middleware, and logging based on the best practices guides.
π Debugging Scenarios
Investigate Checkout Errors
User: βMy checkout flow is failing. Can you check the logs and help me debug?β
AI Process:
- Get Recent Errors:
get_latest_error({ limit: 10 })
- Search for Checkout Issues:
search_logs({ pattern: "checkout", logLevel: "error" })
- Analyze Error Patterns: Identifies common failure points
- Provide Solutions: Based on error analysis and best practices
Sample AI Response:
I found 3 checkout-related errors in the last hour:
- Payment Authorization Failed (5 occurrences)
- Error:
Credit card validation failed for order 00001234
- Solution: Check payment processor configuration and card validation logic
- Inventory Check Failed (2 occurrences)
- Error:
Product ABC123 not available in required quantity
- Solution: Implement proper inventory validation in basket calculation hooks
Based on SFCC best practices, I recommend adding these validation stepsβ¦
ποΈ Architecture & Planning
Plan a Custom Integration
User: βI need to integrate with a third-party shipping service. Whatβs the best approach?β
AI Process:
- Get Integration Guide:
get_best_practice_guide({ guideName: "localserviceregistry" })
- Review Service Patterns: Provides OAuth and API integration examples
- Suggest Architecture: Based on SFCC service integration patterns
Sample AI Response:
For third-party shipping integration, I recommend this architecture:
1. Service Configuration
// Use LocalServiceRegistry for external API calls var ServiceRegistry = require('dw/svc/LocalServiceRegistry'); var shippingService = ServiceRegistry.createService('shipping.api', { createRequest: function(svc, params) { svc.setRequestMethod('POST'); svc.addHeader('Authorization', 'Bearer ' + params.token); return JSON.stringify(params.shipment); }, parseResponse: function(svc, response) { return JSON.parse(response.text); } });
2. Hook Integration Points
- Use
dw.order.calculate
hook for rate calculation- Use
dw.order.shipmentShipped
for tracking updates3. Error Handling Strategy
- Implement circuit breaker pattern
- Add fallback shipping options
- Log all API interactions for debugging
π Data Model Exploration
Discover Custom Attributes
User: βWhat custom attributes are available on the Product object in my instance?β
AI Process:
- Search Product Attributes:
search_system_object_attribute_definitions({ objectType: "Product", searchRequest: { query: { match_all_query: {} } } })
- Filter Custom Attributes: Identifies non-system attributes
- Provide Usage Examples: Shows how to access attributes in code
Sample AI Response:
Found 12 custom attributes on your Product object:
Attribute ID Type Required Description brandName
String No Product brand identifier sustainabilityRating
Enum No Eco-friendly rating (1-5) technicalSpecs
Text No Technical specifications Usage in Controllers:
var product = ProductMgr.getProduct('product-id'); var brandName = product.custom.brandName; var rating = product.custom.sustainabilityRating;
Usage in Templates:
<div class="product-brand">${product.custom.brandName}</div> <div class="sustainability-rating" data-rating="${product.custom.sustainabilityRating}">
π§ Development Workflow Examples
Set Up New Cartridge
User: βCreate a new payment integration cartridge with proper structureβ
AI Process:
- Generate Cartridge:
generate_cartridge_structure({ cartridgeName: "int_payment_provider" })
- Provide Setup Guide: Based on cartridge creation best practices
- Suggest Next Steps: Integration patterns and testing approaches
Generated Structure:
int_payment_provider/
βββ cartridge/
β βββ controllers/
β β βββ PaymentProvider.js
β βββ scripts/
β β βββ hooks/
β β β βββ payment.js
β β βββ services/
β β βββ PaymentProviderService.js
β βββ templates/
β β βββ default/
β β βββ checkout/
β β βββ paymentmethods.isml
β βββ static/
β β βββ default/
β β βββ js/
β β βββ css/
β βββ client/
β βββ default/
β βββ js/
β βββ checkout/
βββ package.json
βββ webpack.config.js
βββ .eslintrc.js
π Security Review
Audit ISML Templates
User: βReview my ISML templates for security vulnerabilitiesβ
AI Process:
- Get Security Guide:
get_best_practice_guide({ guideName: "security" })
- Review Template Patterns: Analyzes for XSS and injection risks
- Provide Remediation: Specific fixes based on SFCC security practices
Sample Security Review:
Security Issues Found:
β XSS Vulnerability in
product/productdetails.isml
:<!-- VULNERABLE: Unescaped output --> <div>${product.custom.description}</div>
β Fixed Version:
<!-- SECURE: Properly escaped output --> <isprint value="${pdict.product.custom.description}" encoding="htmlcontent" />
β Missing CSRF Protection in form submission:
<!-- VULNERABLE: No CSRF token --> <form action="${URLUtils.url('Cart-AddProduct')}" method="post">
β Fixed Version:
<!-- SECURE: CSRF token included --> <form action="${URLUtils.url('Cart-AddProduct')}" method="post"> <input type="hidden" name="${pdict.csrf.tokenName}" value="${pdict.csrf.token}"/>
π Performance Optimization
Optimize Slow Product Pages
User: βMy product detail pages are loading slowly. Help me optimize them.β
AI Process:
- Get Performance Guide:
get_best_practice_guide({ guideName: "performance" })
- Analyze Logs:
search_logs({ pattern: "performance", logLevel: "warn" })
- Provide Optimization Strategy: Based on SFCC performance patterns
Sample Performance Analysis:
Performance Issues Identified:
- Database Query Optimization
- 47ms average for product variant lookups
- Solution: Implement variant caching in product model
- Image Loading Optimization
- Multiple image service calls per product
- Solution: Use lazy loading and image optimization
- Recommendation Engine Delays
- 230ms for recommendation API calls
- Solution: Implement async loading with fallbacks
Optimization Implementation:
// Optimized product model with caching var CacheMgr = require('dw/system/CacheMgr'); var cache = CacheMgr.getCache('ProductVariants'); function getProductWithVariants(productID) { var cacheKey = 'product_' + productID; var product = cache.get(cacheKey); if (!product) { product = ProductMgr.getProduct(productID); // Cache for 1 hour cache.put(cacheKey, product, 3600); } return product; }
π§ͺ Testing Patterns
Create Unit Tests for Service
User: βHelp me write unit tests for my payment service integrationβ
AI Process:
- Get Security Guide:
get_best_practice_guide({ guideName: "security" })
- Get Service Guide:
get_best_practice_guide({ guideName: "localserviceregistry" })
- Provide Test Structure: Based on SFCC security and service best practices
- Generate Test Cases: Covers success, failure, and edge cases
Generated Test Suite:
// Test suite for PaymentProviderService
var assert = require('*/cartridge/scripts/util/assert');
var PaymentService = require('*/cartridge/scripts/services/PaymentProviderService');
describe('PaymentProviderService', function() {
beforeEach(function() {
// Mock service dependencies
this.mockOrder = {
totalGrossPrice: { value: 99.99 },
customerEmail: 'test@example.com'
};
});
describe('processPayment', function() {
it('should successfully process valid payment', function() {
var result = PaymentService.processPayment(this.mockOrder, {
cardNumber: '4111111111111111',
expiryDate: '12/25',
cvv: '123'
});
assert.isTrue(result.success);
assert.isNotNull(result.transactionId);
});
it('should handle invalid card numbers', function() {
var result = PaymentService.processPayment(this.mockOrder, {
cardNumber: '1234567890123456',
expiryDate: '12/25',
cvv: '123'
});
assert.isFalse(result.success);
assert.equals(result.error, 'INVALID_CARD_NUMBER');
});
it('should handle service timeouts gracefully', function() {
// Mock service timeout
PaymentService.setTimeout(100);
var result = PaymentService.processPayment(this.mockOrder, {
cardNumber: '4111111111111111',
expiryDate: '12/25',
cvv: '123'
});
assert.isFalse(result.success);
assert.equals(result.error, 'SERVICE_TIMEOUT');
});
});
});
π― Common Use Case Patterns
Typical AI Assistant Conversations
1. βHow do Iβ¦?β Questions
- User asks about SFCC functionality
- AI uses documentation tools to provide accurate answers
- Includes code examples and best practices
2. βDebug this errorβ Requests
- User shares error messages or symptoms
- AI searches logs and analyzes patterns
- Provides root cause analysis and solutions
3. βReview my codeβ Requests
- User shares code snippets or files
- AI applies security and performance best practices
- Suggests improvements and optimizations
4. βPlan this featureβ Discussions
- User describes requirements
- AI provides architecture recommendations
- Suggests implementation approaches and patterns
5. βGenerate boilerplateβ Tasks
- User needs template code or structures
- AI creates proper SFCC-compliant implementations
- Includes proper error handling and documentation
π Integration with Development Workflow
VS Code + GitHub Copilot
// AI suggests SFCC-aware completions
var ProductMgr = require('dw/catalog/ProductMgr');
// Type "product." and get intelligent suggestions
var product = ProductMgr.getProduct(productId);
product.// β AI suggests: .name, .ID, .custom, .variant, etc.
Claude Desktop for Architecture
- Multi-turn conversations for complex planning
- Context-aware suggestions based on project structure
- Real-time documentation lookup during discussions
Cursor for Code Generation
- File-aware completions based on cartridge structure
- Rule-based suggestions for security and performance
- Intelligent refactoring across related files
Next Steps
- π Troubleshooting - Common issues and solutions
- π οΈ Available Tools - Complete tool reference
- βοΈ Configuration - Set up advanced features