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:
UNKNOWN → UNDERSTAND → IDENTIFY → SEARCH → DISCOVER → VERIFY → COMPARE → ACTThe 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#
- 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. - 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.
- 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
demomode 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:
- 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. - 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_KEYis present. AI identification supports AWS Bedrock, OpenAI, and Gemini, degrading gracefully to a deterministic rules fallback (AI_PROVIDER="none") when no keys are configured. - 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), andunknown.
| Layer | Technology Choice | Engineering Rationale |
|---|---|---|
| Application Runtime | Next.js 16 (App Router) + TypeScript | Unifies UI, API routes, and MCP server in one Node.js process to fit a 4 GB RAM budget |
| Data & Fuzzy Search | PostgreSQL (Supabase) via pg + pg_trgm | Relational model for products, aliases, stores, and inventory with trigram similarity matching |
| Agent Interface | MCP Server (Streamable HTTP) at /api/mcp | Exposes identical product identification and local discovery tools to external agents and the web app |
| AI Identification | Pluggable AWS Bedrock / OpenAI / Gemini / Rules | Avoids vendor lock-in and guarantees offline/demo operability |
| Local Places | OpenStreetMap (default) or Google Places | Zero-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.
Ambiguous query form (/ and /search) with trust-layer status badges
Structured tool invocations over Streamable HTTP transport
Exposes product identification, alias lookup, and inventory verification tools
Returns active/fallback/missing provider states and DB ping latency
Zod-validated env parser enforced at build time via server-only
Products, colloquial aliases (pg_trgm), local stores, and stock evidence
Pluggable Bedrock / OpenAI / Gemini with deterministic rules fallback
Keyless OpenStreetMap default, Google Places, and Tavily fallback
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:
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:
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:
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 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
- 00:00Ambiguous Intent to Concrete Action — Why standard keyword search fails when users describe an object by function rather than SKU.
- 01:15Single-Process Next.js + MCP Architecture — Running UI routes, REST health checks, and Streamable HTTP MCP tools inside a 4 GB RAM footprint.
- 02:30Zero-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.exampleto.env.local, leaving keys likeOPENAI_API_KEY=as empty strings. Standardz.string().optional()treats""as a valid present string rather thanundefined. Wrapping optional fields inz.preprocess(emptyToUndefined, ...)prevented false-positive capability detection.
8. Testing and Validation#
- Build-Time Server Boundary Verification: Verified that importing
lib/env.tsorlib/db.tsfrom a client component immediately failsnext buildvia theserver-onlypackage guard. - Health & Capability Matrix Scenarios: Tested
/api/healthacross zero-credential (VEYLO_MODE=demo), partial-credential (OpenStreetMap active, AI infallback), 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-endpg_trgmalias 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/anddb/seed/with product taxonomy, colloquial alias tables indexed with PostgreSQLpg_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 viamcp/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.