mdxui

Product Contexts

How Products render in Web, API, and MCP contexts

Product Contexts

Products render differently depending on the context in which they're accessed. The same Product can render as a web component, an API response, or an MCP tool - each optimized for its environment and consumer.


Rendering Contexts

Context Types

ContextConsumerFormatUse Case
WebBrowser, HumanHTML/ReactMarketing sites, dashboards
APIApplication, DeveloperJSON/GraphQLProgrammatic access
MCPAI Agent, LLMMCP ProtocolAgent tool calls

Web Context

In web contexts, Products render as React components with full visual presentation.

Component Hierarchy

// Products can render as:
ProductApp      // Full application
  ProductView   // Individual page/view
    ProductPanel // Dashboard widget

ProductSite     // Marketing site
  ProductPage   // Site page
    ProductSection // Page section

ProductCard     // Card component
ProductList     // Grid/list of cards
ProductItem     // Single list item

Web Rendering Examples

As Full Application

import { ProductApp } from '@mdxui/cockpit'

// Renders complete SaaS application
<ProductApp product={product} />

Output: Full web application with:

  • Header and navigation
  • Sidebar with menu items
  • Dashboard views
  • Settings pages
  • Responsive layout

As Marketing Page

import { ProductPage } from '@mdxui/beacon'

// Renders marketing landing page
<ProductPage product={product} pageType="home" />

Output: Marketing page with:

  • Hero section
  • Feature showcase
  • Pricing tiers
  • Testimonials
  • CTA sections

As Card Component

import { ProductCard } from '@mdxui/beacon'

// Renders product card
<ProductCard product={product} variant="detailed" />

Output: Product card with:

  • Product image
  • Title and description
  • Pricing information
  • Feature highlights
  • Action button

Web Context Props

All web components receive standardized props:

interface WebContextProps {
  /** Visual styling */
  className?: string
  variant?: string
  theme?: ThemeConfig

  /** Interactivity */
  onClick?: () => void
  onHover?: () => void
  disabled?: boolean

  /** Layout */
  layout?: string
  orientation?: 'vertical' | 'horizontal'

  /** Display options */
  loading?: boolean
  error?: string
  showImage?: boolean
  showPricing?: boolean
}

API Context

In API contexts, Products serialize to JSON or GraphQL responses for programmatic access.

REST API Response

// GET /api/products/:id
GET /api/products/prod_abc123

Response:

{
  "id": "prod_abc123",
  "name": "Acme API",
  "type": "API",
  "business": "biz_xyz789",
  "description": "RESTful API for data enrichment",
  "isActive": true,
  "stripeProductId": "prod_stripe_123",

  "interfaces": {
    "hasAPI": true,
    "hasRPC": false,
    "hasMCP": true,
    "hasSDK": true,
    "hasCLI": true
  },

  "features": {
    "docs": [
      {
        "id": "feat_1",
        "name": "Data Enrichment",
        "description": "Enrich company and contact data"
      },
      {
        "id": "feat_2",
        "name": "Real-time Validation",
        "description": "Validate data in real-time"
      }
    ],
    "hasNextPage": false,
    "totalDocs": 2
  },

  "prices": [
    {
      "id": "price_free",
      "amount": 0,
      "currency": "USD",
      "type": "usage",
      "interval": "request",
      "includedQuantity": 1000
    },
    {
      "id": "price_payg",
      "amount": 0.001,
      "currency": "USD",
      "type": "usage",
      "interval": "request"
    }
  ],

  "industries": [
    "B2B SaaS",
    "Data & Analytics"
  ],

  "productCategories": [
    "API Platform",
    "Data Enrichment"
  ],

  "updatedAt": "2024-03-20T10:30:00Z",
  "createdAt": "2024-01-15T08:00:00Z"
}

GraphQL Query

query GetProduct($id: ID!) {
  Product(id: $id) {
    id
    name
    type
    description
    isActive

    interfaces {
      hasAPI
      hasMCP
      hasSDK
    }

    features {
      docs {
        id
        name
        description
      }
    }

    prices {
      id
      amount
      currency
      type
      interval
    }

    business {
      id
      name
    }
  }
}

Response:

{
  "data": {
    "Product": {
      "id": "prod_abc123",
      "name": "Acme API",
      "type": "API",
      "description": "RESTful API for data enrichment",
      "isActive": true,
      "interfaces": {
        "hasAPI": true,
        "hasMCP": true,
        "hasSDK": true
      },
      "features": {
        "docs": [...]
      },
      "prices": [...],
      "business": {
        "id": "biz_xyz789",
        "name": "Acme Corp"
      }
    }
  }
}

API Endpoints

Product collection is available via REST and GraphQL:

// REST API
GET    /api/products           // List products
GET    /api/products/:id       // Get product by ID
POST   /api/products           // Create product
PATCH  /api/products/:id       // Update product
DELETE /api/products/:id       // Delete product

// Query parameters
?where[type][equals]=API
?where[isActive][equals]=true
?where[business][equals]=biz_123
&limit=20&page=1&sort=-createdAt

// GraphQL
query Products($where: Product_where) {
  Products(where: $where) {
    docs { ... }
    totalDocs
    hasNextPage
  }
}

API Context Serialization

Products automatically serialize for API responses:

// Auto-serialization
const product = await payload.findByID({
  collection: 'products',
  id: 'prod_123',
})

// Returns JSON-serializable object
return Response.json(product)

Serialization Rules:

  • All dates → ISO 8601 strings
  • Relationships → ID strings or full objects (depth control)
  • Null/undefined → explicit null
  • Arrays → empty arrays if no data

MCP Context

In MCP (Model Context Protocol) contexts, Products expose as tools and resources for AI agents.

MCP Tool Definition

Products can be exposed as MCP tools:

{
  "name": "get_product",
  "description": "Retrieve product information by ID",
  "inputSchema": {
    "type": "object",
    "properties": {
      "product_id": {
        "type": "string",
        "description": "Product ID (e.g., prod_abc123)"
      },
      "include_features": {
        "type": "boolean",
        "description": "Include product features",
        "default": false
      },
      "include_pricing": {
        "type": "boolean",
        "description": "Include pricing information",
        "default": false
      }
    },
    "required": ["product_id"]
  }
}

MCP Tool Implementation

// MCP server implements product tools
export const productTools = {
  name: 'get_product',
  description: 'Get product details',
  inputSchema: GetProductSchema,

  async execute(args: { product_id: string }) {
    const product = await payload.findByID({
      collection: 'products',
      id: args.product_id,
    })

    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(product, null, 2)
        }
      ]
    }
  }
}

MCP Resource

Products can be exposed as MCP resources:

{
  "uri": "product://prod_abc123",
  "name": "Acme API Product",
  "description": "Product details for Acme API",
  "mimeType": "application/json"
}

MCP Usage Example

AI agent using product MCP tool:

// Claude Desktop config
{
  "mcpServers": {
    "products": {
      "command": "npx",
      "args": ["-y", "@acme/products-mcp"]
    }
  }
}

Agent conversation:

User: What are the features of product prod_abc123?

Claude: I'll check the product details.
<use_mcp_tool server="products" tool="get_product">
  { "product_id": "prod_abc123", "include_features": true }
</use_mcp_tool>

Based on the product information:

Acme API includes these features:
- Data Enrichment: Enrich company and contact data
- Real-time Validation: Validate data in real-time
- API Access: RESTful API with rate limiting

MCP Tool Collection

Multiple product-related tools:

export const productMCPTools = {
  // Read operations
  get_product: {
    description: 'Get product by ID',
    execute: async (args) => { ... }
  },

  list_products: {
    description: 'List all products',
    execute: async (args) => { ... }
  },

  search_products: {
    description: 'Search products by criteria',
    execute: async (args) => { ... }
  },

  // Analytics
  get_product_usage: {
    description: 'Get product usage metrics',
    execute: async (args) => { ... }
  },

  get_product_pricing: {
    description: 'Get product pricing tiers',
    execute: async (args) => { ... }
  }
}

Context Detection

Components automatically detect their context:

// Context detection
function detectContext(): 'web' | 'api' | 'mcp' {
  if (typeof window !== 'undefined') return 'web'
  if (process.env.MCP_SERVER) return 'mcp'
  return 'api'
}

// Adaptive rendering
export function Product({ product, context }: ProductProps) {
  const ctx = context || detectContext()

  switch (ctx) {
    case 'web':
      return <ProductComponent product={product} />
    case 'api':
      return Response.json(product)
    case 'mcp':
      return { type: 'text', text: JSON.stringify(product) }
  }
}

Context-Specific Optimizations

Web Context

  • Lazy loading: Load product data on scroll
  • Image optimization: Responsive images, WebP
  • Caching: Client-side caching of product data
  • SEO: Meta tags, structured data
  • Accessibility: ARIA labels, keyboard navigation

API Context

  • Response size: Exclude unnecessary fields
  • Pagination: Limit results per page
  • Compression: Gzip/Brotli compression
  • Rate limiting: Protect against abuse
  • Versioning: API version support

MCP Context

  • Streaming: Stream large responses
  • Tool composition: Combine multiple tools
  • Caching: Cache tool results
  • Error handling: Graceful degradation
  • Timeout handling: Long-running operations

Multi-Context Examples

Same Product, Three Contexts

Web (React Component)

<ProductCard product="prod_abc123" variant="detailed" />

API (REST Endpoint)

curl https://api.acme.com/products/prod_abc123

MCP (AI Agent Tool)

await callTool('get_product', { product_id: 'prod_abc123' })

Context Transformation

// Source: MDXLD Product definition
const productData = {
  $id: 'https://acme.com/products/api',
  name: 'Acme API',
  type: 'API',
  // ...
}

// Web: Renders as React component
<ProductApp product={productData} />

// API: Serializes to JSON
Response.json(productData)

// MCP: Exposes as tool
{
  name: 'acme_api',
  description: 'Access Acme API product',
  execute: () => productData
}

Best Practices

Context-Aware Design

Design products to work well in all contexts:

interface Product {
  // Core data (all contexts)
  id: string
  name: string
  type: ProductType
  description: string

  // Relationships (depth control)
  business: string | Business
  features?: Feature[]

  // Web-specific (optional)
  images?: string[]
  theme?: ThemeConfig

  // API-specific (metadata)
  updatedAt: string
  createdAt: string

  // MCP-specific (capabilities)
  mcpTools?: MCPTool[]
}

Progressive Enhancement

Start with minimal data, enhance per context:

// Base product (MCP/API)
const baseProduct = {
  id: 'prod_123',
  name: 'Product',
  type: 'API',
}

// Enhanced for API
const apiProduct = {
  ...baseProduct,
  features: await loadFeatures(),
  prices: await loadPrices(),
}

// Enhanced for Web
const webProduct = {
  ...apiProduct,
  images: await loadImages(),
  testimonials: await loadTestimonials(),
}

Context Fallbacks

Provide fallbacks when context detection fails:

<ProductCard
  product={product}
  fallback={<ProductSkeleton />}
  error={<ProductError />}
/>

Next Steps

On this page