Skip to main content
Openfront includes a powerful AI shopping assistant built on the Model Context Protocol (MCP). The assistant can help customers browse products, manage their cart, complete purchases, and get personalized recommendations.

AI Assistant Architecture

The AI assistant is powered by:
  • @ai-sdk/mcp - Model Context Protocol integration
  • @modelcontextprotocol/sdk - MCP server implementation
  • AI SDK - Vercel AI SDK for streaming responses
  • MCP Tools - E-commerce-specific tools for shopping workflows

MCP Integration

The MCP transport layer connects AI models to Openfront’s GraphQL API:
// app/api/mcp-transport/[transport]/route.ts

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
  Tool,
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

Available Tools

The AI assistant has access to comprehensive e-commerce tools:

Product Discovery

searchProducts - Search for products with regional pricing:
{
  name: 'searchProducts',
  description: 'Search for products with filtering capabilities',
  inputSchema: {
    type: 'object',
    properties: {
      countryCode: {
        type: 'string',
        description: 'Country code for regional pricing (e.g., "us", "ca", "gb")'
      }
    },
    required: ['countryCode']
  }
}
getProduct - Get detailed product information:
{
  name: 'getProduct',
  description: 'Get detailed product information by ID',
  inputSchema: {
    type: 'object',
    properties: {
      productId: { type: 'string' },
      countryCode: { type: 'string' }
    },
    required: ['productId', 'countryCode']
  }
}

Shopping Cart Management

createCart - Initialize a shopping cart:
{
  name: 'createCart',
  description: 'Create a new shopping cart for a specific country/region',
  inputSchema: {
    type: 'object',
    properties: {
      countryCode: { type: 'string' }
    },
    required: ['countryCode']
  }
}
addToCart - Add products to cart:
{
  name: 'addToCart',
  description: 'Add a product variant to the cart',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' },
      variantId: { type: 'string' },
      quantity: { type: 'number' }
    },
    required: ['cartId', 'variantId', 'quantity']
  }
}
getCart - View cart details:
{
  name: 'getCart',
  description: 'Get cart details including items, totals, and addresses',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' }
    },
    required: ['cartId']
  }
}

Checkout Process

setShippingAddress - Set delivery address:
{
  name: 'setShippingAddress',
  description: 'Set shipping address for the cart',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' },
      email: { type: 'string' },
      firstName: { type: 'string' },
      lastName: { type: 'string' },
      address1: { type: 'string' },
      city: { type: 'string' },
      postalCode: { type: 'string' },
      countryCode: { type: 'string' },
      province: { type: 'string' }
    },
    required: ['cartId', 'email', 'firstName', 'lastName', 'address1', 'city', 'postalCode', 'countryCode']
  }
}
getShippingOptions - Get available shipping methods:
{
  name: 'getShippingOptions',
  description: 'Get available shipping methods for the cart',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' }
    },
    required: ['cartId']
  }
}
setShippingMethod - Select shipping:
{
  name: 'setShippingMethod',
  description: 'Select a shipping method for the cart',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' },
      shippingMethodId: { type: 'string' }
    },
    required: ['cartId', 'shippingMethodId']
  }
}

Payment Processing

getPaymentProviders - List available payment methods:
{
  name: 'getPaymentProviders',
  description: 'Get available payment providers for the cart',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' }
    },
    required: ['cartId']
  }
}
createPaymentSessions - Initialize payment:
{
  name: 'createPaymentSessions',
  description: 'Initialize payment sessions for the cart',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' }
    },
    required: ['cartId']
  }
}
placeOrder - Complete purchase:
{
  name: 'placeOrder',
  description: 'Complete the checkout and create an order',
  inputSchema: {
    type: 'object',
    properties: {
      cartId: { type: 'string' }
    },
    required: ['cartId']
  }
}

Order Management

getOrder - View order details:
{
  name: 'getOrder',
  description: 'Get order details by ID',
  inputSchema: {
    type: 'object',
    properties: {
      orderId: { type: 'string' },
      secretKey: { type: 'string' }
    },
    required: ['orderId', 'secretKey']
  }
}

Regional Support

getAvailableCountries - List shipping destinations:
{
  name: 'getAvailableCountries',
  description: 'Get list of countries we ship to for customer selection',
  inputSchema: {
    type: 'object',
    properties: {},
    required: []
  }
}

AI Shopping Workflow

The assistant follows a guided workflow for order placement:
/*
IMPORTANT GUIDANCE FOR AI COMPLETION CLIENTS:

When users ask to "place an order" or "buy products", follow this workflow:

PROPER ORDER PLACEMENT WORKFLOW:
1. createCart (with customer's country)
2. searchProducts (to find products) 
3. getProduct (to get specific variants and pricing)
4. addToCart (add specific product variants)
5. setShippingAddress (with customer details)
6. getShippingOptions & setShippingMethod (select shipping)
7. placeOrder (attempt to complete the order)
8. getCheckoutLink (if placeOrder fails, provide checkout link)

CUSTOMER FLOW EXAMPLES:
- "I want to buy a black t-shirt" → Ask for country → createCart → searchProducts "black t-shirt" → show variants → addToCart → get address → complete checkout
- "Place an order for shoes size 10" → Follow full workflow above
- "Complete my purchase" → Check if cart exists, complete checkout flow
*/

Implementation Example

Basic Shopping Conversation

import { streamText } from 'ai';
import { openrouter } from '@openrouter/ai-sdk-provider';
import { experimental_createProviderRegistry as createProviderRegistry } from 'ai';
import { createMCPClient } from '@ai-sdk/mcp';

const registry = createProviderRegistry({
  openrouter: openrouter({
    apiKey: process.env.OPENROUTER_API_KEY,
  }),
});

const mcpClient = await createMCPClient({
  transport: {
    type: 'http',
    url: `${baseUrl}/api/mcp-transport/http`,
    headers: {
      cookie: request.headers.get('cookie') || '',
    },
  },
});

const result = streamText({
  model: registry.languageModel('openrouter:anthropic/claude-4.5-sonnet'),
  messages: [
    {
      role: 'system',
      content: `You are a helpful shopping assistant. Help customers:
        - Find products
        - Add items to cart
        - Complete purchases
        - Track orders
        
        Always ask for country/region first for accurate pricing.
        Be friendly and guide them through the process.`
    },
    ...conversationHistory
  ],
  tools: mcpClient.getTools(),
});
The assistant can provide rich product displays:
// When using searchProducts tool, returns HTML UI
const productsHTML = `
  <div class="products-grid">
    <div class="product-card">
      <img src="${product.thumbnail}" alt="${product.title}">
      <h3>${product.title}</h3>
      <p class="price">${formattedPrice}</p>
      <button onclick="addToCart('${variant.id}')">Add to Cart</button>
    </div>
  </div>
`;

GraphQL Integration

The MCP server directly queries Openfront’s GraphQL API:
async function executeGraphQL(query: string, variables?: any): Promise<any> {
  const response = await fetch(graphqlEndpoint, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Cookie': cookie,
    },
    body: JSON.stringify({ query, variables }),
  });

  const result = await response.json();
  if (result.errors) {
    throw new Error(`GraphQL execution failed: ${JSON.stringify(result.errors)}`);
  }
  return result;
}

Schema Introspection

The assistant can explore the data model:
{
  name: 'listModels',
  description: 'List all available GraphQL models/types in the system'
}

{
  name: 'getFieldsForType',
  description: 'Get all available fields for a specific GraphQL type'
}

{
  name: 'searchModels',
  description: 'Search for models by name pattern'
}

Advanced Features

Smart Product Recommendations

The AI can suggest products based on conversation:
// Customer: "I need something for running in cold weather"
// AI searches and recommends:
- Winter running jacket
- Thermal base layers
- Running gloves
- Cold weather shoes

Conversational Cart Management

// Customer: "Add the blue one in medium"
// AI understands context from previous product view
// Automatically adds correct variant

Checkout Assistance

// Customer: "Ship to my home address"
// AI can use previously stored addresses
// Offers to auto-fill or confirm details

Configuration

Environment Variables

OPENROUTER_API_KEY=sk-or-...
NEXT_PUBLIC_AI_ENABLED=true

AI Model Selection

Configure which AI model to use:
const model = registry.languageModel(
  'openrouter:anthropic/claude-4.5-sonnet'
);

// Or use other providers:
// 'openrouter:openai/gpt-4'
// 'openrouter:google/gemini-pro'

Security Considerations

Authentication

MCP transport includes session cookies:
const mcpClient = await createMCPClient({
  transport: {
    type: 'http',
    url: mcpTransportUrl,
    headers: {
      cookie: request.headers.get('cookie') || '',
    },
  },
});

Data Access

AI assistant respects:
  • User authentication state
  • Regional availability
  • Product visibility
  • Inventory levels

Best Practices

Conversation Design

  • Ask for country early for accurate pricing
  • Guide customers through checkout steps
  • Confirm important details
  • Provide clear next steps

Error Handling

  • Handle out-of-stock gracefully
  • Provide alternatives when products unavailable
  • Explain payment issues clearly
  • Offer checkout link as fallback

User Experience

  • Show product images and prices
  • Provide cart summaries
  • Display shipping options clearly
  • Confirm order details before completion

Monitoring and Analytics

Track AI Interactions

interface AIInteraction {
  userId?: string;
  sessionId: string;
  tool: string;
  success: boolean;
  duration: number;
  error?: string;
}

function logInteraction(interaction: AIInteraction) {
  // Send to analytics
  analytics.track('ai_tool_use', interaction);
}

Common Queries

  • Product searches
  • Cart operations
  • Checkout completions
  • Order lookups
  • Abandoned carts

Build docs developers (and LLMs) love