Skip to main content
04 // ENGINEERING SPECIFICATIONPhase 0 — Foundation

Veylo: Ambient Product Discovery & Local Inventory Capability for AI Agents

A real-world product discovery capability for conversational agents like Alexa+ that translates ambiguous everyday descriptions into identified products, local business candidates, and confidence-graded inventory evidence via Model Context Protocol (MCP).

Published 2026-10-05Updated 2026-10-0611 min read
Next.js 16TypeScriptPostgreSQL (pg_trgm)Model Context ProtocolAWS BedrockZodOpenStreetMap

1. Overview#

Veylo is a real-world product discovery and local inventory verification engine designed for conversational agents (such as Alexa+) as well as human users via a web interface. Instead of requiring exact product names or SKUs, Veylo accepts ambiguous, everyday descriptions—such as "that little thing that connects my laptop to the TV" or "the tape used on pipe threads"—and guides the request through an eight-stage resolution pipeline:

Pipeline Stage Progressiontext
UNKNOWN → UNDERSTAND → IDENTIFY → SEARCH → DISCOVER → VERIFY → COMPARE → ACT

The project is currently in Phase 0 (Foundation). Rather than fabricating stock availability or hiding missing API credentials behind mock UI screens, Phase 0 establishes the core runtime contracts: a server-only Zod-validated capability matrix, a connection-bounded PostgreSQL client designed for constrained hardware, a trust-graded design system, and the directory scaffolding for Streamable HTTP Model Context Protocol (MCP) tools.

2. The Problem#

Existing e-commerce search engines and local store locators break down under two common real-world conditions:

  • Vocabulary mismatch at the point of need: Consumers frequently describe hardware, adapters, or household repair items by their physical appearance or use case rather than their catalog taxonomy (e.g., asking for "pipe thread tape" instead of "PTFE thread seal tape").
  • Hallucinated local inventory in AI assistants: General-purpose LLMs can identify what an object is, but when asked "Where can I buy this near me right now?", they either guess store names from static training weights or treat unverified web snippets as confirmed in-stock inventory.

Intended Users and Constraints#

  1. External AI Agents (via MCP): Voice and ambient assistants that need structured, callable tools (/api/mcp) to resolve an ambiguous user utterance into ranked local fulfillment options.
  2. Human Searchers (via Web UI): Users who need to identify an unfamiliar part by text (and in later phases, image or voice) and compare nearby stores.
  3. Hardware & Operational Constraints: The entire system had to be developed and run on a 4 GB RAM development machine while remaining runnable in a zero-key demo mode whenever paid upstream credentials (AWS Bedrock, Google Places, Tavily) are absent.

3. The Approach#

To satisfy both human users and external agents without duplicating business logic, Veylo is architected around three core decisions:

  1. Single-Process UI + API + MCP Server: Instead of running separate microservices for the frontend, REST backend, and MCP tool server (which would exhaust memory on a 4 GB machine), Veylo hosts the web UI, /api/health, /api/agent, and the Streamable HTTP MCP server (/api/mcp) inside a single Next.js 16 App Router process.
  2. Pluggable Provider Architecture with Keyless Defaults: Local business discovery defaults to OpenStreetMap (which requires zero API keys) and upgrades to Google Places when GOOGLE_PLACES_API_KEY is present. AI identification supports AWS Bedrock, OpenAI, and Gemini, degrading gracefully to a deterministic rules fallback (AI_PROVIDER="none") when no keys are configured.
  3. Explicit Evidence & Trust Grading: Veylo never presents web search results as confirmed shelf stock. Even in the UI layer (tailwind.config.ts), inventory states are separated into four explicit semantic trust levels: confirmed (verified database/store record), likely (high-probability category match), web (unverified Tavily web discovery), and unknown.
Specification table (Layer, Technology Choice, Engineering Rationale)
LayerTechnology ChoiceEngineering Rationale
Application RuntimeNext.js 16 (App Router) + TypeScriptUnifies UI, API routes, and MCP server in one Node.js process to fit a 4 GB RAM budget
Data & Fuzzy SearchPostgreSQL (Supabase) via pg + pg_trgmRelational model for products, aliases, stores, and inventory with trigram similarity matching
Agent InterfaceMCP Server (Streamable HTTP) at /api/mcpExposes identical product identification and local discovery tools to external agents and the web app
AI IdentificationPluggable AWS Bedrock / OpenAI / Gemini / RulesAvoids vendor lock-in and guarantees offline/demo operability
Local PlacesOpenStreetMap (default) or Google PlacesZero-key default for local testing with optional commercial enrichment

4. System Architecture#

Veylo separates client-visible UI routes from server-only capability modules (lib/) and MCP tool definitions (mcp/). Every external dependency is gated through lib/env.ts before any database or network call is attempted.

SYSTEM SCHEMATIC // VEYLO SINGLE-PROCESS NEXT.JS + MCP CAPABILITY ARCHITECTURE
01. Clients & Calling Agents
Next.js Web UI

Ambiguous query form (/ and /search) with trust-layer status badges

React 19 · Tailwind CSS
External Agents (Alexa+)

Structured tool invocations over Streamable HTTP transport

@modelcontextprotocol/sdk
HTTP GET/POST & Streamable HTTP MCP
02. Next.js 16 Unified Process Boundary
MCP Server (/api/mcp)

Exposes product identification, alias lookup, and inventory verification tools

mcp/server · mcp/tools
Health & Capability Probe (/api/health)

Returns active/fallback/missing provider states and DB ping latency

app/api/health/route.ts
Environment & Capability Matrix

Zod-validated env parser enforced at build time via server-only

lib/env.ts · Zod
Validated Server-Only Calls
03. Data & Pluggable External Providers
PostgreSQL Pool (max: 5)

Products, colloquial aliases (pg_trgm), local stores, and stock evidence

lib/db.ts · pg · Supabase
AI Identification Layer

Pluggable Bedrock / OpenAI / Gemini with deterministic rules fallback

lib/ai
Places & Web Discovery

Keyless OpenStreetMap default, Google Places, and Tavily fallback

lib/places · lib/search
Figure: Veylo Single-Process Next.js + MCP Capability Architecture

5. Engineering Deep Dive#

5.1 Build-Time Secret Isolation and Capability Reporting#

A common vulnerability in full-stack Next.js applications is accidentally importing a server configuration module into a client component, or exposing raw environment variables in diagnostic endpoints. In lib/env.ts, Veylo imports "server-only" on line 1—causing Next.js to fail the build immediately if any client bundle references the module—and normalizes empty strings in .env.local into undefined before validating with Zod.

Rather than returning booleans or raw configuration values, capabilities() computes a deterministic tri-state ("active" | "missing" | "fallback") for every subsystem:

lib/env.tstypescript
import "server-only";
import { z } from "zod";

const emptyToUndefined = (v: unknown) =>
  typeof v === "string" && v.trim() === "" ? undefined : v;
const optionalString = z.preprocess(emptyToUndefined, z.string().optional());

const EnvSchema = z.object({
  VEYLO_MODE: z.preprocess(emptyToUndefined, z.enum(["demo", "live"]).default("demo")),
  DATABASE_URL: optionalString,
  DATABASE_SSL: z.preprocess(emptyToUndefined, z.enum(["true", "false"]).default("true")),
  AI_PROVIDER: z.preprocess(
    emptyToUndefined,
    z.enum(["bedrock", "openai", "gemini", "none"]).default("none")
  ),
  PLACES_PROVIDER: z.preprocess(emptyToUndefined, z.enum(["osm", "google"]).default("osm")),
  GOOGLE_PLACES_API_KEY: optionalString,
  TAVILY_API_KEY: optionalString,
  MCP_AUTH_TOKEN: optionalString,
});

export type CapabilityStatus = "active" | "missing" | "fallback";

export function capabilities() {
  const e = env();
  const hasAws = Boolean(e.AWS_ACCESS_KEY_ID && e.AWS_SECRET_ACCESS_KEY);

  const aiConfigured =
    (e.AI_PROVIDER === "bedrock" && hasAws && Boolean(e.BEDROCK_MODEL_ID)) ||
    (e.AI_PROVIDER === "openai" && Boolean(e.OPENAI_API_KEY)) ||
    (e.AI_PROVIDER === "gemini" && Boolean(e.GEMINI_API_KEY));

  const placesStatus: CapabilityStatus =
    e.PLACES_PROVIDER === "google"
      ? e.GOOGLE_PLACES_API_KEY
        ? "active"
        : "missing"
      : "active"; // OpenStreetMap requires no API key

  return {
    mode: e.VEYLO_MODE,
    database: (e.DATABASE_URL ? "active" : "missing") as CapabilityStatus,
    ai: {
      provider: e.AI_PROVIDER,
      status: (aiConfigured ? "active" : "fallback") as CapabilityStatus,
    },
    places: { provider: e.PLACES_PROVIDER, status: placesStatus },
    webSearch: (e.TAVILY_API_KEY ? "active" : "missing") as CapabilityStatus,
  };
}

5.2 Resource-Constrained PostgreSQL Connection Pooling#

During development with Next.js Fast Refresh (HMR), naive module-scoped new Pool() instantiations leak database connections on every file save, quickly exhausting both Supabase's connection pooler limits and local memory. lib/db.ts caches a single Pool instance on globalThis.__veyloPool with a strict cap of max: 5 connections and a 5-second connection timeout.

Furthermore, pingDatabase() measures round-trip query latency (select 1) while sanitizing any thrown driver error down to its short error code (err.code ?? "connection_failed"), guaranteeing that a malformed DATABASE_URL containing credentials can never be echoed in an error stack trace:

lib/db.tstypescript
import "server-only";
import { Pool, type QueryResultRow } from "pg";
import { env } from "@/lib/env";

declare global {
  var __veyloPool: Pool | undefined;
}

export function getPool(): Pool {
  const e = env();
  if (!e.DATABASE_URL) {
    throw new Error("DATABASE_URL is not configured");
  }
  if (!globalThis.__veyloPool) {
    globalThis.__veyloPool = new Pool({
      connectionString: e.DATABASE_URL,
      ssl: e.DATABASE_SSL === "true" ? { rejectUnauthorized: false } : undefined,
      max: 5,
      idleTimeoutMillis: 30_000,
      connectionTimeoutMillis: 5_000,
    });
  }
  return globalThis.__veyloPool;
}

export async function pingDatabase(): Promise<{
  ok: boolean;
  latencyMs?: number;
  error?: string;
}> {
  if (!Boolean(env().DATABASE_URL)) return { ok: false, error: "not_configured" };
  const started = Date.now();
  try {
    await getPool().query("select 1");
    return { ok: true, latencyMs: Date.now() - started };
  } catch (err) {
    // Surface a short error class only — connection strings must never leak.
    const code = (err as { code?: string }).code ?? "connection_failed";
    return { ok: false, error: code };
  }
}

5.3 Safe Operational Health Endpoint#

The /api/health route combines the static capability report with the live database ping so developers and calling agents can inspect which subsystems are live before dispatching a multi-step tool workflow:

app/api/health/route.tstypescript
import { NextResponse } from "next/server";
import { capabilities } from "@/lib/env";
import { pingDatabase } from "@/lib/db";

export const dynamic = "force-dynamic";

export async function GET() {
  const caps = capabilities();
  const db = await pingDatabase();

  return NextResponse.json({
    service: "veylo",
    status: "ok",
    time: new Date().toISOString(),
    capabilities: {
      ...caps,
      database: db.ok ? "active" : caps.database === "missing" ? "missing" : "error",
    },
    database: db,
  });
}

6. Technical Demo#

Technical Walkthrough & Verification
Recorded video walkthrough coming soon

Technical walkthrough recording coming soon

Walkthrough of Veylo's Phase 0 foundation: server-only environment capability introspection, single-process Next.js + Streamable HTTP MCP architecture, and the 4-tier inventory trust layer.

Walkthrough Sequence & Checkpoints

  1. 00:00
    Ambiguous Intent to Concrete Action — Why standard keyword search fails when users describe an object by function rather than SKU.
  2. 01:15
    Single-Process Next.js + MCP Architecture — Running UI routes, REST health checks, and Streamable HTTP MCP tools inside a 4 GB RAM footprint.
  3. 02:30
    Zero-Secret Capability Introspection — Inspecting /api/health and lib/env.ts to verify active vs. fallback provider states.
View Written Walkthrough Summary / Transcript ▾

Veylo starts from a common failure mode in voice and ambient computing: a user knows what a physical item does ('that tape used on pipe threads' or 'that little adapter connecting my laptop to the TV'), but does not know its canonical name—let alone which nearby store carries it right now.

In Phase 0, the architectural focus is establishing a strict trust boundary before wiring stochastic model calls. The environment layer in lib/env.ts uses server-only and Zod preprocessing to evaluate which providers (AWS Bedrock, OpenAI, Gemini, OpenStreetMap, Google Places, Tavily, and PostgreSQL) are active, missing, or running in deterministic fallback mode.

Because the development environment is constrained to a 4 GB RAM machine and Supabase connection poolers enforce strict connection caps, Veylo consolidates the web UI, API routes, and the Streamable HTTP MCP server into a single Next.js 16 process backed by a 5-connection pg Pool.

7. Challenges and Trade-offs#

  • Fitting UI, API, and MCP inside 4 GB RAM: Running separate processes for a Next.js frontend, a standalone Express/Fastify MCP server, and a local database container caused frequent swap thrashing on a 4 GB development machine. Consolidating the MCP server into a Next.js App Router route (/api/mcp) using Streamable HTTP eliminated redundant Node.js processes and TypeScript compilation watchers.
  • Preventing False Confidence in Inventory Results: Early design iterations considered merging Tavily web search results into the same list as database-verified store inventory. However, scraping a retailer's general product page does not prove local shelf stock. I separated web discovery into its own explicit trust tier (trust-web) so the UI and MCP responses never claim an item is in stock without primary inventory evidence.
  • Handling Empty `.env` Strings in Zod: Developers frequently copy .env.example to .env.local, leaving keys like OPENAI_API_KEY= as empty strings. Standard z.string().optional() treats "" as a valid present string rather than undefined. Wrapping optional fields in z.preprocess(emptyToUndefined, ...) prevented false-positive capability detection.

8. Testing and Validation#

  • Build-Time Server Boundary Verification: Verified that importing lib/env.ts or lib/db.ts from a client component immediately fails next build via the server-only package guard.
  • Health & Capability Matrix Scenarios: Tested /api/health across zero-credential (VEYLO_MODE=demo), partial-credential (OpenStreetMap active, AI in fallback), and invalid-schema states to confirm that secret values and connection strings are never serialized in HTTP responses.
  • Known Limitations (Phase 0): The project is currently in its Phase 0 foundation. The core environment validation, database pool, health endpoint, and search UI shell (/ and /search) are implemented, while the end-to-end pg_trgm alias resolution query pipeline, voice input (Phase 8), and camera vision upload (Phase 9) are scheduled for subsequent phases.

9. What I Learned#

  • Design trust states into the schema and design system first: When building AI systems that bridge digital search and physical-world actions (like driving to a local hardware store), distinguishing verified evidence from probabilistic inference is an architectural requirement, not a UI polish step.
  • Hardware constraints force cleaner architecture: Designing for a 4 GB RAM ceiling forced disciplined connection pooling (max: 5), zero unnecessary client libraries, and a unified single-process server layout.

10. Future Improvements#

  • Phase 1–3 (Database Schema & Trigram Alias Search): Populate db/schema/ and db/seed/ with product taxonomy, colloquial alias tables indexed with PostgreSQL pg_trgm, and deterministic local store inventory fixtures.
  • Phase 4–6 (Streamable HTTP MCP Tool Wiring): Implement the callable MCP tools in mcp/tools/ (identify_product, find_nearby_inventory, verify_evidence) and expose them via mcp/server/.
  • Phase 8–9 (Multimodal Input): Enable the currently disabled voice (Mic) and camera (Camera) controls on the homepage using AWS Bedrock vision models and S3 presigned uploads.