Skip to content
ImagineWorld

PostgreSQL and MCP:T he B lueprint for a R obust AI A ssistant

node_idnode-book_ai-ready-postgresql-18_chapter-20-postgresql-and-mcp-t-he-b-lueprint-for-a-r-obust-ai-a-ssista
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num20
chapter_titlePostgreSQL and MCP:T he B lueprint for a R obust AI A ssistant
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 20 — PostgreSQL and MCP:T he B lueprint for a R obust AI A ssistant

Section titled “Chapter 20 — PostgreSQL and MCP:T he B lueprint for a R obust AI A ssistant”

PostgreSQL and MCP: The Blueprint for a Robust AI Assistant

Section titled “PostgreSQL and MCP: The Blueprint for a Robust AI Assistant”

If Chapter 19*,* Production-Ready AI Embedding Pipeline Patterns was the engine room, pipelines, queues, retries, and freshness, then this chapter is the cockpit. So far, we’ve taught PostgreSQL how to store meaning (pgvector), maintain meaning (embedding pipelines), and retrieve meaning (semantic search and recommendations). That’s a powerful foundation, but it still leaves a gap between capability and experience. Users don’t want to “run a vector query.” They want to ask things like the following:

  • Find something like a tailored men ’ s jacket under $500.
  • Show me polo shirts in different colors, but only what ’ s currently priced.
  • What are the closest alternatives to this product?

A good assistant makes those questions feel natural and makes the answers feel trustworthy.

This chapter is about building that assistant without sacrificing the discipline of a database system. We will design two chatbot layers:

  • A c urated q uery a ssistant or b asic SQL c hat: Think of it as a “menu-based” assistant: it selects from pre-approved query templates, so behavior stays safe by construction, predictable in performance, and easy to audit
  • A g overned q uery a ssistant or d ynamic SQL: Think of it as a “supervised” assistant: it can generate SQL for richer questions, but only inside strict guardrails (SELECT -only, enforced LIMITs, schema whitelists, and logged execution)

So far, this still sounds like “chat.”

But the moment we let an LLM choose actions such as run a query, call a function, or fetch rows, we’ve crossed a line: We are no longer building conversation. We are granting capability. And capability changes the game.

An AI prompt can suggest behavior. An AI prompt cannot enforce behavior!

You can tell the LLM, ” Only run SELECT.”But the database won’t read your prompt; it will run what the LLM tells it to.

You can state in the prompt, ” Always LIMIT 10.” But the database won’t enforce your good intentions if the LLM tells it otherwise. You can write ” Never touch sensitive tables.” But ” never ” is not a security boundary.

This is the production realization: Once the model can operate, safety must move from language to system design. That’s where the Model Context Protocol (MCP) enters, not as a buzzword, but as the missing layer between “LLM intent” and “system execution.”

This chapter covers the following topics:

  • Building an AI chatbot in PostgreSQL
  • The dynamic SQL chatbot
  • Introducing MCP: The contract between models and tools

The MCP is the contract that turns “the model wants to do something” into “the system allows a specific tool call, under policy, and returns evidence.” Without the MCP, the model tends to act like a clever intern: it writes suggestions in free-form text and hopes someone else runs them safely.

With the MCP, the model acts like a client of an API: it must choose from the tools you defined, send typed inputs, and accept the results returned by the system.

So, instead of the model improvising: ” Here ’ s some SQL you should run… ”, the MCP makes the interaction explicit and enforceable:

  • Tool choice is explicit (the model must pick a named capability, not invent one)
  • Inputs are typed (p_question text, p_k, p_row_limit, optional filters)
  • Execution is policy-bound (read-only role, schema allowlist, timeouts, row caps)
  • Outputs are structured (rows as evidence, plus optional metadata)
  • Every action is auditable (what tool ran, what SQL ran, what came back)

Now our assistant stops being “a chat feature” and becomes something more valuable: a governed interface to the database.

That means we can expose a small, safe tool surface built from the PostgreSQL functions and views that we already created – tools such as the following:

  • api.sf_similar_items(p_query_text, p_k) for semantic retrieval
  • Curated views over product.* and embeddings.*
  • Controlled execution paths that return rows (and nothing else)

We will stay grounded in the same e-commerce schema you’ve used throughout this book: product.category, product.brand, product.product, product.product_variant, product.product_variant_price, and the embedding tables in embeddings.*.

The goal is not just “a chatbot.” The goal is a production-grade assistant that combines semantic meaning with relational truth: pricing rules, variant attributes, and business constraints, while remaining secure, observable, and predictable.

And that naturally sets up the next section: implementing MCP tool routing for our Postgres assistant.

Because once you have a contract, the next question is simple and practical: Which tool should handle which question, and how do we route safely, every time?

In the previous chapters, we taught PostgreSQL how to store, index, and retrieve meaning. Now we’re going to teach PostgreSQL something more visible: how to communicate and talk to the user in natural language.

Not the “hand-wavy demo” kind of talking. The grounded kind, where answers come from rows, not from imagination.

We will build our chatbot using three functions. Think of them as three roles in a small play:

  • Retriever: Finds the most relevant products using embeddings (pgvector + SQL joins)
  • Narrator: Turns query results into a human response without inventing facts
  • Orchestrator:Coordinates both, returning the answer and the evidence

We will use these functions exactly as written next.

The retriever is the assistant’s semantic engine. It takes a user question, converts it into an embedding vector, compares it against product embeddings, and returns the closest matches – already joined with category and current price, so the results are immediately usable. The following function implements the retriever component:

CREATE OR REPLACE FUNCTION api.sf_similar_items(
p_query_text text,
p_k integer DEFAULT 10
)
RETURNS TABLE (
product_id integer,
name text,
category text,
shortdescription text,
longdescription text,
price numeric,
distance double precision
)
LANGUAGE plpgsql
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog, public, api, product, embeddings
AS $$
DECLARE
v_qvec vector(1536);
BEGIN
v_qvec := api.openai_embed(p_query_text)::vector(1536);
RETURN QUERY
WITH res AS MATERIALIZED (
SELECT
p.id AS product_id,
p.label::text AS name,
c.label::text AS category,
p.shortdescription::text AS shortdescription,
p.longdescription::text AS longdescription,
pvp.price AS price,
(v_qvec <=> pe.embedding) AS distance
FROM product.product p
JOIN embeddings.product_embedding pe
ON pe.product_id = p.id
JOIN product.category c
ON c.id = p.category_id
JOIN product.product_variant pv
ON pv.product_id = p.id
JOIN product.product_variant_price pvp
ON pvp.product_variant_id = pv.id
AND pvp.current = true
)
SELECT
res.product_id,
res.name,
res.category,
res.shortdescription,
res.longdescription,
res.price,
res.distance
FROM res
ORDER BY res.distance
LIMIT p_k;
END;
$$;

When a user says, ” looking for tailored clothing,” we don’t want keyword matching like ” tailored must appear in the description.”

We want meaning-based matching: ” tailored ” should find items such as blazers, formal shirts, and sports coats, even if the word ” tailored ” isn’t present.

That’s exactly what api.sf_similar_items does:

  • Step A: Convert the question into an embedding vector using api.openai_embed(query_text)
  • Step B: Compare that vector against stored product vectors in embeddings.product_embedding
  • Step C: Join back to relational truth:
    1. Product name + descriptions 2. Category 3. Only current pricing via product_variant_price.current = true
  • Step D: Return the top p_k results ordered by distance (lower distance = closer meaning)

The joins matter! Notice this query is not “vector-only.” It is vector and SQL discipline:

  • Vectors find what feels relevant
  • SQL ensures results are valid (category, current price, joins to real rows)

So, the database stays honest.

From the start, we make this production-shaped. Notice what we did not do:

  • We did not dump the whole product table into the model
  • We did not let the model invent joins
  • We did not let an external system become the source of truth

Instead, api.sf_similar_items makes meaning retrieval feel like a regular SQL function: predictable, bounded, and auditable:

  • LIMIT p_k bounds the workload
  • MATERIALIZED keeps the retrieval plan stable (and prevents re-evaluation surprises)
  • Joins enforce relational truth: category + current price

This is the first rule of database-native AI: use vectors to find candidates, then use SQL to enforce reality.

The basic query outputs the following:

SELECT
product_id,
name,
category,
price
FROM api.sf_similar_items('looking for tailored clothing', 1);
product_id | name | category | price
------------+-----------------------------------------+----------+-------
14 | Suit coat - business perfect, by Brioni | Pants | 98.43
(1 row)

Rows are truthful, but they are not always friendly. This function is the voice: it takes the question and the rows (as JSON) and produces a clear human response.

The most important design choice is it explicitly tells the model not to invent beyond the rows. The model becomes a narrator, not an oracle. The following function implements the narrator component:

CREATE OR REPLACE FUNCTION api.sf_answer_with_openai(
p_question text,
p_rows jsonb
)
RETURNS text
LANGUAGE plpython3u
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog, public, api, product, embeddings
AS $$
import json
import random
import ssl
import time
import urllib.error
import urllib.request
def _get_guc(p_name: str):
v_rv = plpy.execute(
"SELECT current_setting(%s, true) AS v",
[p_name],
)
if not v_rv or v_rv[0]["v"] is None:
return None
return v_rv[0]["v"]
def _call_openai_chat_completions(p_payload: dict, p_api_key: str, p_org):
v_headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {p_api_key}",
"User-Agent": "pg18book-plpython-openai-chat/1.0",
}
if p_org:
v_headers["OpenAI-Organization"] = p_org
v_req = urllib.request.Request(
url="https://api.openai.com/v1/chat/completions",
data=json.dumps(p_payload).encode("utf-8"),
headers=v_headers,
method="POST",
)
v_ctx = ssl.create_default_context()
with urllib.request.urlopen(v_req, context=v_ctx, timeout=30) as v_resp:
v_raw = v_resp.read().decode("utf-8", errors="replace")
return json.loads(v_raw)
def _extract_content(p_data: dict) -> str:
if "choices" not in p_data or not p_data["choices"]:
raise Exception("Unexpected OpenAI response: missing choices")
v_msg = p_data["choices"][0].get("message", {})
v_content = v_msg.get("content", None)
if v_content is None:
raise Exception("Unexpected OpenAI response: missing message content")
return str(v_content).strip()
v_api_key = _get_guc("api.openai_api_key")
v_org = _get_guc("api.openai_organization")
if not v_api_key:
raise Exception(
"OpenAI API key not set. Use: "
"SELECT set_config('api.openai_api_key','sk-...','f');"
)
v_rows = json.dumps(p_rows)
v_system = (
"You are a helpful assistant.\n"
"Take the user question and the SQL rows returned, and write a clear, "
"human reply.\n"
"- Mention the question.\n"
"- Summarize how many results were found.\n"
"- List items with their label, price if present, and category.\n"
"- Do not invent anything beyond rows JSON.\n"
"Schema tables/columns:\n"
"- product.product(id, category_id, brand_id, label, shortdescription, "
"longdescription)\n"
"- embeddings.product_embedding(product_id, embedding)\n"
"- product.category(id, label, description)\n"
"- product.brand(id, label, description)\n"
"- product.product_variant(id, product_id, attributes)\n"
"- product.product_variant_price(id, product_variant_id, price, validity, "
"current)\n"
"- api.category_complements(category_name, complements)\n"
"\n"
"Rules:\n"
"- Categories are broad: product.category.label values like 'Jeans', "
"'Shirt', 'Skirt'.\n"
"- Gender words (women, men, kids) appear in product.label, NOT in "
"category.\n"
"- Price: product_variant_price.price (alias pvp).\n"
"- Color/size attributes are in product_variant.attributes (JSONB).\n"
"- Category: product.category.label (alias pc). Join pc ON pc.id = "
"p.category_id.\n"
"- To use price/color: JOIN product_variant pv ON pv.product_id = p.id "
"AND JOIN product_variant_price pvp ON pvp.product_variant_id = pv.id.\n"
"- Use LOWER() for case-insensitive filters, e.g. LOWER(p.label) LIKE "
"'%women%'.\n"
"- Only SELECT. No semicolons.\n"
"- Prefer clear aliases (product_name, price).\n"
"- If no rows are returned just respond.\n"
)
v_user = f"Question: {p_question}\n\nRows: {v_rows}"
v_payload = {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": v_system},
{"role": "user", "content": v_user},
],
"temperature": 0.2,
"max_tokens": 500,
}
v_attempts = 6
for v_i in range(v_attempts):
try:
v_data = _call_openai_chat_completions(v_payload, v_api_key, v_org)
return _extract_content(v_data)
except urllib.error.HTTPError as v_e:
v_body = v_e.read().decode("utf-8", errors="ignore") if hasattr(v_e, "read") else ""
v_code = getattr(v_e, "code", None)
v_transient = v_code in (429, 500, 502, 503, 504)
v_last = (v_i == v_attempts - 1)
if (not v_transient) or v_last:
raise Exception(
f"OpenAI HTTP {v_code} (attempt {v_i + 1}/{v_attempts}). "
f"Body: {v_body[:400]} ..."
)
v_retry_after = None
try:
v_retry_after = v_e.headers.get("Retry-After")
except Exception:
v_retry_after = None
if v_retry_after:
try:
v_sleep_s = float(v_retry_after)
except Exception:
v_sleep_s = (2 ** v_i) * 0.5 + random.uniform(0, 0.3)
else:
v_sleep_s = (2 ** v_i) * 0.5 + random.uniform(0, 0.3)
time.sleep(v_sleep_s)
except urllib.error.URLError:
v_last = (v_i == v_attempts - 1)
if v_last:
raise
time.sleep((2 ** v_i) * 0.5 + random.uniform(0, 0.2))
except Exception:
v_last = (v_i == v_attempts - 1)
if v_last:
raise
time.sleep((2 ** v_i) * 0.5 + random.uniform(0, 0.2))
$$;

Let’s walk through what the function does.

Retrieval gives us rows, but rows aren’t user-friendly. A chatbot needs to communicate in natural language – it needs to speak. That’s what api.sf_answer_with_openai(p_question, p_rows) does:

  • It receives:
    • The original user question
      • The SQL results as JSON (p_rows)
  • It asks the model to produce a clear response
  • But with a hard rule: do not invent anything beyond the rows

This design is subtle but important. The LLM does not browse your database. It does not freely query tables. It only sees the records you pass in. That keeps the model in the role it’s good at: summarizing and communicating, not acting as a database.

This function is not “AI doing SQL.” It’s AI doing what it should: turning structured evidence into human language.

Now we’ll combine retrieval and narration into a single call of api.sf_chat. This is our first chatbot.

CREATE OR REPLACE FUNCTION api.sf_chat(
p_question text,
p_k integer DEFAULT 10
)
RETURNS TABLE (
assistant_text text,
rows jsonb
)
LANGUAGE plpgsql
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog, public, api, product, embeddings
AS $$
DECLARE
v_data jsonb;
BEGIN
SELECT jsonb_agg(t)
INTO v_data
FROM (
SELECT
s.product_id,
s.name,
s.category,
s.shortdescription,
s.longdescription,
s.price,
s.distance
FROM api.sf_similar_items(p_question, p_k) s
) t;
assistant_text := api.sf_answer_with_openai(p_question, v_data);
rows := coalesce(v_data, '[]'::jsonb);
RETURN NEXT;
END;
$$;

What it does is combine the two steps into one simple interface:

  • Get semantically similar items using api.sf_similar_items
  • Aggregate those rows into JSON
  • Pass them to api.sf_answer_with_openai
  • Return:
    • assistant_text
      • rows (so we can inspect what it used)

This gives us an assistant with the following qualities:

  • Grounded in real data
  • Reproducible (the same rows map to the same answer)
  • Debuggable (you can inspect rows)

What you get back is intentionally two-part:

  • assistant_text: the user-facing answer
  • rows: the evidence the answer was based on

That second one is your truth anchor. When someone says, ” Why did the bot recommend this?”, you don’t argue. You point to the rows underlying the answer.

Figure 20.1: Coordinator, retriever, narrator, and their respective LLM interfaces

Figure 20.1 shows how the coordinator, retriever, and narrator work together to generate the response. The retriever uses the LLM’s embedding generation API to identify meaningful rows, and the narrator uses the chat completion API to convert the rows into an easily understandable natural-language answer.

Before we chat, we need embeddings and an API key.

SELECT set_config('api.openai_api_key','sk-...YOUR_KEY...', false);
SELECT api.embed_products(25);

Now you can run queries like this:

-- Tip (psql): results can be wide. Use expanded output or disable the pager:
-- \x
-- \pset pager off
SELECT * FROM api.sf_chat('looking for tailored clothing', 1);
SELECT * FROM api.sf_chat('Tell me about polo shirts in different colors', 2);
SELECT * FROM api.sf_chat('What are the best pants for men?', 1);

Take this example:

SELECT * FROM api.sf_chat('looking for tailored clothing', 1);

It produces the following result:

-[ RECORD 1 ]--+-----------------------------------------------------------------
assistant_text | You asked for tailored clothing, and I found 1
| result that matches your request.
| Here are the details:
| - **Product Name**: Suit coat - business perfect, by
| Brioni
| - **Price**: $98.43
| - **Category**: Pants
|
| This suit coat is crafted from premium wool or
| wool-blend fabrics, offering a sharp yet comfortable
| silhouette. It is designed for versatility, suitable
| for both formal occasions and smart-casual wear.
rows | [{"name": "Suit coat - business perfect, by Brioni",
| "price": 98.43, "category": "Pants", "distance":
|0.5368103661054147, "product_id": 14, "..."}]

At this stage, we have a working assistant. But we haven’t yet made it smart about constraints. A real user rarely asks only for ” similar.” They ask for the following:

  • ” under $100 ”
  • ” only current price ”
  • ” blue color ”
  • ” business casual ”
  • ” Show me shirts, not jackets.”

That’s where we need dynamic behavior.

Making it more robust: Using embeddings.sf_get_query_embedding

Section titled “Making it more robust: Using embeddings.sf_get_query_embedding”

Right now, api.sf_similar_items embeds the query text every time. That’s correct, but in production, it introduces latency and increases costs because it interacts with the LLM every time.

This is where your earlier helper that uses the query cache belongs. We can keep the function design identical and simply swap:

SELECT api.openai_embed(query_text)::vector(1536) INTO qvec;

for:

SELECT embeddings.sf_get_query_embedding(query_text)::vector(1536) INTO qvec;

That single change makes repeated queries faster and cheaper, and it provides a clean point for model-version discipline (model_id) and cache eviction, as discussed in Chapter 19.

Now we move from a “fixed” chatbot to a dynamic one: the assistant can interpret a user request, translate it into a SQL query, and execute it.

This is where many systems go off the rails because a dynamic SQL chatbot must obey two laws:

  • The model may propose SQL, but the system must enforce policy
  • Every executed query must be bounded and auditable

So, we do not give the model unrestricted SQL execution. We give it a safe execution lane.

What does “dynamic” mean in our schema

Section titled “What does “dynamic” mean in our schema”

A user might ask: ” Show me polo shirts under $80 that are currently priced, and mention available colors.”

Our schema tells us exactly what ” colors ” means:

  • Color lives in product.product_variant.attributes (JSONB)
  • Price lives in product.product_variant_price
  • Current pricing requires pvp.current = true
  • The product label carries words such as ” polo ”

So, a safe query might look like this:

SELECT
p.id,
p.label,
c.label AS category,
pvp.price,
pv.attributes->>'color' AS color
FROM product.product p
JOIN product.category c ON c.id = p.category_id
JOIN product.product_variant pv ON pv.product_id = p.id
JOIN product.product_variant_price pvp
ON pvp.product_variant_id = pv.id
AND pvp.current = true
WHERE LOWER(p.label) LIKE '%polo%'
AND pvp.price <= 80
LIMIT 3;

It would produce the following output:

id | label | category | price | color
----+---------------------------+----------+-------+-------
20 | Tommy Hilfiger Polo Shirt | Shirts | 31.72 | navy
20 | Tommy Hilfiger Polo Shirt | Shirts | 31.72 | white
20 | Tommy Hilfiger Polo Shirt | Shirts | 31.72 | red
(3 rows)

The chatbot’s job is to generate queries like this, but only inside a sandbox.

A safe dynamic SQL executor (SELECT-only + LIMIT + Allowlist)

Section titled “A safe dynamic SQL executor (SELECT-only + LIMIT + Allowlist)”

Up to now, our chatbot has been beautifully disciplined. It takes a question, uses embeddings to retrieve relevant products, and relies on the model only to explain the rows it was given. That’s safe, grounded, and production-shaped.

But real users don’t always ask ” what ’ s similar?” They ask for constraints:

  • ” Show me polo shirts under $80.”
  • ” Only items with current pricing.”
  • ” Only men ’ s clothing.”
  • ” Show different colors and sizes.”
  • ” Give me 10 options, not 100.”

This is where the next evolution becomes tempting: Let the model write SQL.

That temptation is also where many developers accidentally build a SQL-shaped foot-gun. So, we’ll do something better.

We will build a dynamic SQL chatbot, but we’ll put it on rails to keep it on the straight and narrow:

  • The model may propose SQL
  • PostgreSQL will police SQL
  • The answer will be grounded in rows

This section introduces a production pattern you’ll reuse everywhere: Models suggest. Systems enforce. Databases verify.

A safe dynamic SQL executor must enforce a few non-negotiables:

  1. SELECT -only:
    • No inserts. No updates. No deletes. No DDL. No “oops, I dropped the table.”
  2. A hard row limit:
    • Every query must have a LIMIT, and we must cap it.
  3. An allowlist of schemas/tables:
    • The model only gets access to the set of tables we explicitly permit:
      • product.*
      • embeddings.* (optionally)
      • api.* views/functions (optionally)
  4. No multi-statement execution: One query only. No semicolons. No stacked statements.
  5. Auditable behavior: We should be able to log what was asked and what was executed (we’ll keep it minimal here, but the hook matters).

Now, we’ll implement the simplest safe version using a helper function: api.sf_safe_select(...).

A minimal “safe” query runner: api.sf_safe_select

Section titled “A minimal “safe” query runner: api.sf_safe_select”

This function accepts a SQL string (generated by the model), validates it, enforces a maximum LIMIT, and returns JSONB rows that we can feed directly into api.sf_answer_with_openai(...).

This is the function definition for a safe SQL executor:

CREATE OR REPLACE FUNCTION api.sf_safe_select(
p_sql text,
p_max_rows integer DEFAULT 50
)
RETURNS jsonb
LANGUAGE plpgsql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, api, product, embeddings
AS $$
DECLARE
v_sql text;
v_rows jsonb;
BEGIN
--- Normalize whitespace
v_sql := regexp_replace(coalesce(p_sql, ''), '\s+', ' ', 'g');
--- Single statement only (reject semicolons)
IF position(';' IN v_sql) > 0 THEN
RAISE EXCEPTION 'Only a single SELECT statement is allowed (no semicolons).'
USING ERRCODE = '42601';
END IF;
--- Must start with SELECT or WITH (CTE)
IF NOT (v_sql ~* '^\s*(select|with)\y') THEN
RAISE EXCEPTION 'Only SELECT queries are allowed.'
USING ERRCODE = '42501';
END IF;
--- Reject dangerous keywords (defense-in-depth)
IF v_sql ~* '\y(insert|update|delete|merge|drop|alter|create|truncate|grant|revoke|comment|vacuum|analyze|copy|call|do)\y' THEN
RAISE EXCEPTION 'Non-SELECT keywords detected. Query rejected.'
USING ERRCODE = '42501';
END IF;
--- Disallow system schemas
IF v_sql ~* '\y(pg_catalog|information_schema)\y' THEN
RAISE EXCEPTION 'System schemas are not allowed.'
USING ERRCODE = '42501';
END IF;
--- Require allowed schemas (intentionally strict)
IF v_sql !~* '\y(product|api|embeddings)\.' THEN
RAISE EXCEPTION
'Query must reference allowed schemas (product., embeddings., api.).'
USING ERRCODE = '42501';
END IF;
--- Add LIMIT only if missing
IF v_sql !~* '\ylimit\y' THEN
--- If query ends with FOR UPDATE/SHARE variants, insert LIMIT before it
IF v_sql ~* '\yfor\s+(update|share|no\s+key\s+update|key\s+share)\y\s*$' THEN
v_sql := regexp_replace(
v_sql,
'(\yfor\s+(update|share|no\s+key\s+update|key\s+share)\y\s*)$',
format(' LIMIT %s \1', p_max_rows),
1, 1, 'i'
);
ELSE
v_sql := v_sql || format(' LIMIT %s', p_max_rows);
END IF;
END IF;
--- Wrap to return JSON
v_sql := format(
'SELECT coalesce(jsonb_agg(t), ''[]''::jsonb) FROM (%s) t',
v_sql
);
EXECUTE v_sql INTO v_rows;
RETURN coalesce(v_rows, '[]'::jsonb);
END;
$$;

Here are examples of how the safe executor stops potentially malicious SQL:

SELECT api.sf_safe_select('INSERT INTO TEST VALUES(1,2)', 3);
ERROR: Only SELECT queries are allowed.
CONTEXT: PL/pgSQL function safe_select(text,integer) line 16 at RAISE
SELECT api.sf_safe_select('SELECT * FROM pg_catalog.pg_class', 4);
ERROR: System schemas are not allowed.
CONTEXT: PL/pgSQL function safe_select(text,integer) line 26 at RAISE
SELECT api.sf_safe_select('SELECT * FROM public.test', 4);
ERROR: Query must reference allowed schemas (product., embeddings., api.).
CONTEXT: PL/pgSQL function safe_select(text,integer) line 31 at RAISE

This is intentionally minimal but real:

  • It blocks multi-statement tricks
  • It blocks obvious non- SELECT intent
  • It blocks system schema access
  • It requires queries to touch only product, embeddings, or APIs
  • It hard-caps output via an enforced limit

Is it perfect? No. But it is a strong baseline, and it demonstrates the pattern: the model doesn ’ t get to run wild, the database stays in charge.

Turning a question into SQL (the model proposes, the database enforces)

Section titled “Turning a question into SQL (the model proposes, the database enforces)”

Now we need a function that asks the model for an SQL query.

The prompt must be strict:

  • It must use our schema
  • It must only use SELECT
  • It must always include LIMIT
  • It must prefer the joins we already know are correct (especially current = true pricing)
  • It must return SQL only (no commentary)

Here is the function definition for the SQL generator:

CREATE OR REPLACE FUNCTION api.sf_sql_from_question(
p_question text,
p_row_limit integer DEFAULT 20
)
RETURNS text
LANGUAGE plpython3u
VOLATILE
AS $$
import json
import ssl
import urllib.request
rv = plpy.execute("SELECT current_setting('api.openai_api_key', true) AS k")
v_api_key = rv[0]["k"] if rv and rv[0]["k"] is not None else None
if not v_api_key:
raise Exception("OpenAI API key not set.")
v_system = f"""
You are a PostgreSQL SQL generator for an e-commerce schema.
Return ONLY SQL (no markdown, no explanation, no semicolons).
Hard rules:
- SELECT or WITH only.
- Must include LIMIT {p_row_limit}.
- Use only these schemas: product, embeddings, api.
- Prefer current price only: JOIN product.product_variant_price pvp ON pvp.product_variant_id = pv.id AND pvp.current = true
- product table: product.product p (id, category_id, brand_id, label, shortdescription, longdescription, image_filename)
- category table: product.category c (id, label, description)
- brand table: product.brand b (id, label, description)
- variants: product.product_variant pv (id, product_id, attributes JSONB)
- price: product.product_variant_price pvp (product_variant_id, price, validity, current)
- For color/size use pv.attributes->>'color', pv.attributes->>'size'
- For case-insensitive text: use LOWER(p.label) LIKE '%...%'
Output columns should be useful: id, label, category, price, and attributes when relevant.
"""
v_user = f"Question: {p_question}"
v_payload = {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": v_system},
{"role": "user", "content": v_user}
],
"temperature": 0.0,
"max_tokens": 250
}
v_headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {v_api_key}"
}
v_ctx = ssl.create_default_context()
v_req = urllib.request.Request(
"https://api.openai.com/v1/chat/completions",
data=json.dumps(v_payload).encode("utf-8"),
headers=v_headers
)
with urllib.request.urlopen(v_req, context=v_ctx) as resp:
v_data = json.loads(resp.read().decode("utf-8"))
v_sql = v_data["choices"][0]["message"]["content"].strip()
# Defensive cleanup: remove trailing semicolons if model slips
v_sql = v_sql.replace(";", "")
return v_sql
$$;

This function is intentionally narrow. It doesn’t try to be clever. It tries to be safe.

  1. It reads the OpenAI API key from Postgres settings:
    rv = plpy.execute("SELECT current_setting('api.openai_api_key', true) AS k")
    v_api_key = rv[0]["k"] if rv and rv[0]["k"] is not None else None
    if not v_api_key:
    raise Exception("OpenAI API key not set.")
    • If the key isn’t set, the function throws " OpenAI API key not set "
      • This is how the database securely stores the credentials (via a GUC parameter)
  2. It builds “instructions” for the AI model (the SYSTEM prompt). The SYSTEM block tells the model the following:
    • You are a SQL generator for this e-commerce schema
      • Return only SQL – no explanations, no markdown
      • Safety/shape rules
  3. Only SELECT or WITH
  4. Must include LIMIT {p_row_limit}
  5. Only use schemas: product, embeddings, and APIs
  6. Prefer current price rows using a specific join condition
  7. Provides the schema map (tables + important columns)
  8. Gives conventions for things such as the following:
    • pv.attributes- > > 'color' for color
      • LOWER(p.label) LIKE '%...%' for case-insensitive search
  9. Suggests what columns to output (id, label, category, price, etc.) Think of this as a guardrail + schema cheat-sheet for the model.
  10. Sends the user question to the model (USER prompt):
    v_user = f"Question: {p_question}"
    This is the actual question you passed in.
  11. Calls the OpenAI Chat Completions API. It sends a request such as the following:
    • model: gpt-4o-mini
      • messages: [system, user]
      • temperature: 0.0 (makes output deterministic/less “creative”)
      • max_tokens: 250 (caps response size)
  12. Extracts the SQL from the response:
    v_sql = v_data["choices"][0]["message"]["content"].strip()
  13. Returns the SQL string.

That string can then be passed into something like your api.sf_safe_select() function to execute safely.

Now we’ll assemble the pipeline:

  • The model proposes SQL (api.sf_sql_from_question)
  • The database validates and executes safely (api.sf_safe_select)
  • The model narrates the results (api.sf_answer_with_openai)

The chatbot returns both answer and evidence (rows and SQL)

Here is the function definition for our dynamic chatbot:

CREATE OR REPLACE FUNCTION api.sf_dynamic_chat(
p_question text,
p_row_limit integer DEFAULT 20
)
RETURNS TABLE (
assistant_text text,
sql_used text,
rows jsonb
)
LANGUAGE plpgsql
VOLATILE
AS $$
DECLARE
v_sql text;
v_rows jsonb;
BEGIN
--- Ask model for SQL
v_sql := api.sf_sql_from_question(p_question, p_row_limit);
--- Execute safely (SELECT-only + limit + allowlist)
v_rows := api.sf_safe_select(v_sql, p_row_limit);
--- Narrate based only on returned rows
assistant_text := api.sf_answer_with_openai(p_question, v_rows);
sql_used := v_sql;
rows := v_rows;
RETURN NEXT;
END;
$$;

This is the moment when the chatbot becomes “dynamic,” yet remains disciplined.

The model is not your DBA. It’s your junior analyst with a clipboard – useful, fast, and occasionally overconfident. So, PostgreSQL remains the grown-up in the room. Here’s an example:

  • First, make sure that the OpenAI API key is set:
    SELECT set_config('api.openai_api_key','sk-...YOUR_KEY...', false);
  • Then run the query:
    SELECT * FROM api.sf_dynamic_chat('Show me polo shirts under $80 with current price', 1);

This creates the following output:

-[ RECORD 1 ]--+-----------------------------------------------------------------------------------------------------------------
assistant_text | You asked for polo shirts under $80 with the current price. I found 3 results for you.
|
| 1. **Label**: Tommy Hilfiger Polo Shirt
| - **Price**: $31.72
| - **Category**: Shirts
| - **Attributes**: Size M, Color navy, Style
| classic polo
| 2. **Label**: Tommy Hilfiger Polo Shirt
| - **Price**: $31.72
| - **Category**: Shirts
| - **Attributes**: Size L, Color white, Style
| classic polo
|
| 3. **Label**: Tommy Hilfiger Polo Shirt
| - **Price**: $31.72
| - **Category**: Shirts
| - **Attributes**: Size XL, Color red, Style
| classic polo
sql_used | SELECT p.id, p.label, c.label AS category,
| pvp.price, pv.attributes
| FROM product.product p
| JOIN product.category c ON p.category_id = c.id
| JOIN product.product_variant pv ON p.id =
| pv.product_id
| JOIN product.product_variant_price pvp ON
| pvp.product_variant_id = pv.id AND pvp.current =
| true
| WHERE LOWER(p.label) LIKE '%polo%' AND pvp.price <
| 80
| LIMIT 10
rows | [{"id": 20, "label": "Tommy Hilfiger Polo Shirt", "price": 31.72,
| "category": "Shirts", "attributes": {"logo": "flag", "size":..}]

Here is another example:

SELECT * FROM api.sf_dynamic_chat('Show me men''s shirts in blue, include the color attribute', 1);

The model should use the following:

  • pv.attributes- > > 'color'
  • LOWER(p.label) LIKE '%men%' or similar text signal
  • pvp.current = true

This is an important note: dynamic SQL is great for filters, but it is not semantic retrieval by default. If you want meaning-based retrieval, you still want api.sf_similar_items (and we can teach the dynamic assistant to call it).

For now, we’ll keep it simple:

  • Dynamic SQL handles structured constraints
  • Semantic search handles meaning retrieval

In later sections (and especially with MCP), we will let the assistant choose which tool to use.

Why don’t we add embeddings.sf_get_query_embedding at this point

Section titled “Why don’t we add embeddings.sf_get_query_embedding at this point”

We can use embeddings.sf_get_query_embedding here for robustness, but not inside api.sf_sql_from_question because that function generates SQL, it doesn’t embed. Instead, it belongs in the semantic tool path:

  • api.sf_similar_items currently calls api.openai_embed(query_text) on every request
  • In production, we can replace it with cached embeddings:
    1. Fewer API calls 2. Lower latency for repeated queries 3. Model versioning becomes manageable

So, we teach it the following as refinement:

  • Dynamic SQL = structured filtering chatbot
  • Semantic retrieval = meaning chatbot
  • Query embedding cache = production efficiency layer

This keeps the architecture clean and keeps each function honest about its job. In production, you typically add the following:

  • A dedicated DB role with read-only access to allowed schemas
  • Query logging (question, SQL, duration, row count, user)
  • Timeouts/ statement_timeout
  • Stricter parsing (AST-based validation rather than regex) (Abstract Syntax Tree)
  • A tool protocol (MCP) so the model chooses from safe tools instead of writing arbitrary SQL

And that’s exactly why the next arc matters: once you can do this safely, you can do it at scale.

Teaching the assistant when to use semantic search vs. dynamic SQL

Section titled “Teaching the assistant when to use semantic search vs. dynamic SQL”

At this point, we’ve built two “brains” inside PostgreSQL:

  • Semantic brain (meaning-first): api.sf_chat(), which uses api.sf_similar_items() and embeddings and pgvector
  • Structured brain (rules-first): api.sf_dynamic_chat(), which generates SQL, uses api.sf_safe_select(), returns rows, and narrates

Both are useful. Both are correct. But both can disappoint if used at the wrong time.

A semantic engine is brilliant at “I don’t know the exact words, but I know what I mean.” A structured SQL engine is brilliant at ” I know exactly what I want; please obey the constraints.” Your job in production is not to pick one. Your job is to route the request to the right tool consistently, predictably, and safely.

So, we’ll build a tiny “traffic cop” function: a router.

Think of user questions as falling into two lanes:

Here are some examples:

  • “looking for tailored clothing”
  • “something like a leather jacket but lighter”
  • “outfits for a formal occasion”
  • “similar to Boss but more casual”

These questions are under-specified on purpose. The user is asking the system to interpret intent, then use api.sf_chat(p_question, p_k) (semantic retrieval and narration).

Here are some examples:

  • “polo shirts under $80”
  • “show blue shirts and include color”
  • “only items with current price”
  • “limit to 10 and order by price”

These questions are asking for rule obedience more than meaning; therefore, the system should use api.sf_dynamic_chat(p_question, p_row_limit) (guarded SQL and narration).

Yes, some questions are hybrids. We’ll handle those too.

We’re going to do something deliberately humble:

  • Classify the question using lightweight heuristics
  • Choose one of the two tools
  • Return the answer and the evidence

We’ll keep it simple because this is still the “build the engine” chapter, not the “build the operating system” chapter. Here is a simple router that uses lightweight heuristics to route the query to the semantic chatbot or the dynamic SQL chatbot.

CREATE OR REPLACE FUNCTION api.sf_route_chat(
p_question text,
p_k integer DEFAULT 10,
p_row_limit integer DEFAULT 20
)
RETURNS TABLE (
tool_used text,
assistant_text text,
rows jsonb
)
LANGUAGE plpgsql
VOLATILE
AS $$
DECLARE
v_question_lc text := lower(coalesce(p_question, ''));
BEGIN
/*
Routing heuristic:
- If question contains explicit constraints (price, color, size, limit, current,
category), prefer dynamic SQL chatbot.
- Otherwise, prefer semantic chatbot.
This is intentionally conservative: structured constraints should be enforced
by SQL.
*/
IF v_question_lc ~ (
'\yunder\y|\yless than\y|\yprice\y|\$|\ycolor\y|\ysize\y|\ylimit\y|' ||
'\ycurrent\y|\yin[- ]stock\y|\ycategory\y|\ybrand\y'
)
THEN
tool_used := 'dynamic_sql';
SELECT dc.assistant_text,
dc.rows
INTO assistant_text,
rows
FROM api.sf_dynamic_chat(p_question, p_row_limit) dc;
RETURN NEXT;
ELSE
tool_used := 'semantic';
SELECT c.assistant_text,
c.rows
INTO assistant_text,
rows
FROM api.sf_chat(p_question, p_k) c;
RETURN NEXT;
END IF;
END;
$$;

This routing logic is intentionally opinionated:

  1. If the user expresses constraints, let SQL enforce them.
  2. If the user expresses intent, let embeddings interpret them.

That rule will save you an entire category of “the chatbot sounds right but violates reality.”

Here are a couple of examples:

SELECT * FROM api.sf_route_chat('Show me one polo shirts under $80 with current price', 1,1);

Here’s the output:

-[ RECORD 1 ]
tool_used | dynamic_sql
assistant_text | You asked for polo shirts under $80 with the current price. I found
| 3 results for you.
|
| 1. **Label**: Tommy Hilfiger Polo Shirt
| - **Price**: $31.72
| - **Category**: Shirts
| - **Attributes**: Size M, Color navy, Style classic polo
|
| 2. **Label**: Tommy Hilfiger Polo Shirt
| - **Price**: $31.72
| - **Category**: Shirts
| - **Attributes**: Size L, Color white, Style classic polo
|
| 3. **Label**: Tommy Hilfiger Polo Shirt
| - **Price**: $31.72
| - **Category**: Shirts
| - **Attributes**: Size XL, Color red, Style classic polo
rows | [{"id": 20, "label": "Tommy Hilfiger Polo Shirt", "price": 31.72,
| "category": "Shirts", "attributes": {"logo": "flag", "size": "M",
| "color": "navy", "style": "classic polo"}}, {"id": 20, "label":
| "Tommy Hilfiger Polo Shirt", "price": 31.72, "category": "...]

Here’s another example:

SELECT * FROM api.sf_route_chat('I am looking for tailored clothing', 1,1);

The output:

-[ RECORD 1 ]
tool_used | semantic
assistant_text | You asked for tailored clothing, and I found 2 results that match
| your request.
|
| 1. **Suit coat - business perfect, by Brioni**
| - **Price:** $98.43
| - **Category:** Pants
| - **Description:** Classic tailored suit coat - premium wool,
| sharp silhouette, versatile elegance.
|
| 2. **Suit coat - business perfect, by Brioni**
| - **Price:** $98.43
| - **Category:** Pants
| - **Description:** Classic tailored suit coat - premium wool,
| sharp silhouette, versatile elegance.
|
| Both items are the same suit coat, offering a refined and versatile
| option for tailored clothing.
rows | [{"name": "Suit coat - business perfect, by Brioni", "price":
| 98.43, "category": "Pants", "distance": 0.5368103661054147,
| "product_id": 14, "longdescription": "Refined Versatility:...}]

Handling the hybrid question (the real world)

Section titled “Handling the hybrid question (the real world)”

The real world loves hybrids: “Show me something like a leather jacket, but under $150.”

This is both semantic and structured. Our simple router will likely pick dynamic SQL (because it saw “under $150”), but dynamic SQL may not capture “like a leather jacket” well.

So, the production-friendly pattern is as follows:

  1. Semantic retrieval to get candidates.
  2. SQL filtering to enforce constraints.

In PostgreSQL, that’s a beautiful shape:

  • Step 1: get top N candidates with api.sf_similar_items(...)
  • Step 2: filter by price/category/attributes
  • Step 3: narrate

We can implement a hybrid function that does exactly that.

A hybrid chat: Semantic candidates and SQL filters

Section titled “A hybrid chat: Semantic candidates and SQL filters”

Hybrid here means two different kinds of logic cooperating – each doing what it’s best at.

First, semantic retrieval (vector search) answers: ” What items feel like this question?” It gives us a ranked candidate list based on meaning. This is soft matching: useful for discovery, not for enforcing rules.

Second, relational filtering (SQL constraints) answers: ” Which of these candidates are actually allowed?” Price, categories, size/color attributes in JSONB; inventory rules are hard constraints; SQL is the judge.

We use a staged approach:

  • Meaning first: retrieve the top-N candidates by embedding similarity (high recall)
  • Rules second: apply strict SQL filters to those candidates (high precision)
  • Explain with evidence: narrate only what survived, grounded in returned rows

That’s the hybrid pattern: semantic recall + relational precision. For the first version, we’ll support the most common constraint: a price ceiling (show me jacket-like items, but under $150).

Think of SQL like a bouncer: vectors build the guest list, SQL checks the ID.

Here is the definition for the hybrid chat function that calls api.sf_similar_items(p_question, p_k) first to get the set of products matching the meaning, then applies the SQL filter based on price, and finally calls api.``sf_ answer_with_openai to provide a natural language answer.

CREATE OR REPLACE FUNCTION api.sf_hybrid_chat(
p_question text,
p_max_price numeric DEFAULT NULL,
p_k integer DEFAULT 20
)
RETURNS TABLE (
assistant_text text,
rows jsonb
)
LANGUAGE plpgsql
VOLATILE
AS $function$
DECLARE
v_data jsonb;
BEGIN
SELECT jsonb_agg(t)
INTO v_data
FROM (
SELECT
s.product_id,
s.name,
s.category,
s.shortdescription,
s.longdescription,
s.price,
s.distance
FROM api.sf_similar_items(p_question, p_k) AS s
WHERE (p_max_price IS NULL OR s.price <= p_max_price)
ORDER BY s.distance
LIMIT 10
) t;
assistant_text := api.sf_answer_with_openai(p_question, coalesce(v_data, '[]'::jsonb));
rows := coalesce(v_data, '[]'::jsonb);
RETURN NEXT;
END;
$function$;

Here’s a hybrid example:

SELECT * FROM api.sf_hybrid_chat('something like a leather jacket but lighter', 150, 20);

Now the assistant does what we expect it to do:

  1. Meaning retrieval first.
  2. Business constraints second.
  3. Narration last.

Why this still isn’t “production-safe enough” (and why MCPh exists)

Section titled “Why this still isn’t “production-safe enough” (and why MCPh exists)”

We’ve done something powerful. We let the model generate SQL, and we didn’t let it run wild – we constrained it, capped it, forced it into allowed schemas, and made it return evidence. That’s already a big step up from the usual “LLM vibes and hope” approach. Still, this isn’t the end of the safety story. Regex validation is a seatbelt, not an airbag, not a crash test, and not driving school. It reduces harm, but it doesn’t guarantee the behavior of a growing system – especially once you add more tools, more app surfaces, more teams, and more ways for the model to “help.” At that point, production doesn’t just need careful implementation. It needs explicit contracts, permissioned access, structured tool schemas, policy enforcement, and standardized telemetry and audit. That’s the opening door to the Model Context Protocol (MCP).

Before we introduce MCP, it helps to clear up a common mental collision: people often blend together “RAG with chat,” “the database-grounded chat we built,” and “MCP,” as if they’re the same thing with different labels. Retrieval Augmented Generation (RAG) and the MCP are cousins, but not twins. Classic RAG is mostly about retrieving unstructured text chunks (documents, paragraphs, snippets) and stuffing that context into the model’s prompt so it can generate an answer. Your controls are often prompt-based, and the model still does much of the work of interpreting, filtering, and summarizing. What we built in PostgreSQL is different in a crucial way: our retrieval is not chunks of unstructured text, it’s rows – structured evidence pulled from a source-of-truth database using SQL and pgvector. The database enforces relational truth – current price joins, categories, variants, business constraints – and the AI model’s job becomes narration and explanation, not invention. So, RAG is “bring context to the model,” while our PostgreSQL assistant is “bring evidence to the model.” Figure 20.2 compares RAG and the MCP.

Figure 20.2: Juxtaposition of RAG and the MCP

That distinction already matters, but it still leaves a bigger gap: once we allow the model to choose actions – run queries, call functions, fetch rows – we’ve moved from “chat” into “operations.” This is where prompts alone stop being enough. Prompts are advice, production needs contracts. Once a system becomes operational, you want the same discipline you apply everywhere else in engineering: explicit interfaces, typed inputs, enforceable permissions, predictable outputs, and logs that tell you what happened when something feels off.

That is exactly what the MCP provides. The MCP is best understood as a standard for how a model interacts with tools (databases, APIs, services) through a well-defined, governed interface. Instead of the model improvising in free-form text – “Here’s some SQL you should run…” – MCP turns tool use into a structured handshake: the model selects a tool, the tool has an explicit schema, the system executes the call under policy, the model receives the result, and then the model explains it. In other words, the MCP is the difference between a model suggesting actions and a model calling functions with typed inputs under enforcement.

This is also the cleanest way to explain how the MCP differs from what we already built. Our PostgreSQL functions – api.sf_similar_items, api.``sf_ chat, api.sf_dynamic_chat, and the curated views – are the tools. The MCP is the contract and execution boundary that makes those tools governable at scale. Today, we’ve built a safe car. The MCP is the road rules, the safety standards, the inspection process, and the dashboard that keeps the system honest as it grows. With the MCP, tool choice becomes explicit instead of implied. Inputs become typed and validated instead of buried in prose. Policies become enforceable at the boundary – read-only roles, schema allowlists, row caps, timeouts, audit logging – so safety is not something you ask for in the prompt, it’s something the system enforces by design.

If you want a simple mental map, chat is the model speaking; RAG is the model speaking with retrieved context. Our PostgreSQL assistant is the model speaking from SQL evidence rows with relational truth enforced by the database, and MCP is the layer that lets the model speak and act, but only through governed tool contracts with typed inputs, enforced policies, and auditability. That’s why the MCP matters here. We’ve already built the tool layer inside PostgreSQL. The MCP is how we expose that tool layer safely and consistently – without turning your database into an improvisation stage. That sets us up perfectly for the next section: implementing MCP tool routing for our Postgres assistant, where the question becomes not “can the model do this?” but “how does it choose the right tool – reliably, safely, and under policy?”

Up to this point, our assistant has been application logic inside PostgreSQL: embeddings to retrieve, SQL to ground, and an LLM to narrate results.

But the moment we let the model choose actions – which function to call, what query to run, what parameters to pass – we’re no longer just answering questions; we’re operating a system.

RAG is about retrieving context to help the model write an answer. What we’re doing is tool execution against a source of truth. When tools enter the picture, prompts stop providing sufficient governance and control. That’s why we need a contract now.

Introducing the MCP: The contract between models and tools

Section titled “Introducing the MCP: The contract between models and tools”

By now, you can feel the shape of what we’ve built. We didn’t just “add AI” to PostgreSQL. We built a small reasoning loop:

  • Turn a question into meaning (embeddings)
  • Retrieve grounded candidates (SQL and pgvector)
  • Narrate what we found (LLM as a translator, not an inventor)

Then we took one step further: dynamic SQL – carefully, with guardrails.

That’s where the story gets interesting.

Once you allow a model to do things such as running queries, fetching data, and calling functions, you’ve crossed from “assistant” into “agent.” Agents need something humans have always needed: a contract.

Not vibes, not hope, and not “we told it to behave” – an actual contract, and that is what the MCP provides.

MCP stands for Model Context Protocol. In practice, think of it as a standard way for an AI model to interact with tools and systems such as databases, APIs, and services through a well-defined interface.

The model doesn’t improvise actions in free-form text such as this: “Here’s some SQL I think you should run…”

The MCP pushes the interaction into a structured form:

  1. The model selects a tool
  2. The tool has an explicit schema
  3. The system executes the tool call
  4. The model receives the tool result
  5. The model explains the result

It’s the difference between the following:

  • A model making suggestions
  • A model calling a function with typed inputs under policy

The MCP turns “AI that talks” into “AI that operates,” without turning your production systems into a gambling table.

Why the MCP matters for database assistants

Section titled “Why the MCP matters for database assistants”

A database is not a chat window. It’s a source of truth. The risks of using AI with a database aren’t just hallucination. There are these risks:

  • The model queries the wrong thing
  • It returns sensitive data you didn’t intend to expose
  • It runs expensive queries that melt your cluster
  • It bypasses business rules by accident
  • It mixes “semantic vibe” with “transactional truth” incorrectly

In other words, the failure mode isn’t embarrassment; it’s real damage.

The MCP matters because it introduces three disciplines that AI prompts alone cannot guarantee:

  1. Tool choice becomes explicit Instead of the model deciding silently, it must choose from a defined toolset. For us, those tools are already emerging naturally:
    • api.sf_chat(p_question, p_k) (semantic retrieval and narration)
      • api.sf_dynamic_chat(p_question, p_row_limit) (guarded SQL generation and safe execution)
      • api.sf_hybrid_chat(p_question, p_max_price, p_k) (semantic first, SQL constraints second) With MCP, the model doesn’t “invent” an approach. It chooses a tool.
  2. Inputs become typed and validated A tool isn’t a paragraph. It’s a function call. So instead of passing ambiguous text like: Get me some results and filter by something… You pass arguments such as the following:
    • p_question: text
      • p_k: int
      • p_max_price: numeric
      • p_row_limit: int That results in the following:
    • Fewer accidental mistakes
      • Easier enforcement (range limits, defaults, caps)
      • Reproducible behavior
  3. Policies become enforceable With the MCP, you don’t just tell the model “don’t do bad things.” You constrain what the model can do by design:
    • Read-only database role
      • Allowlisted schemas
      • Enforced row limits
      • Statement timeouts
      • Tool-specific permission checks
      • Auditable logs of tool calls and outputs

This is where production confidence comes from.

A prompt is advice. A protocol is governance.

The MCP and the core idea: One system, two truths

Section titled “The MCP and the core idea: One system, two truths”

Earlier, we framed a production system as “two speeds of truth”:

  • O perational truth: exact, immediate, must never lie
  • S emantic truth: meaningful, retrievable, can use eventual consistency (but must be correct)

The MCP helps keep these truths from contaminating each other.

Without the MCP, the model tends to blur lines:

  • It may treat semantic similarity as certainty
  • It may treat partial query results as the complete truth
  • It may try to “help” by guessing missing facts (i.e., hallucinating)

With the MCP, we design the interaction so the model is always anchored:

  • Semantic retrieval is always backed by embeddings.*
  • Operational constraints are always enforced by SQL
  • Narration is always grounded in rows returned

This is how we preserve trust.

How the MCP maps to what we’ve already built

Section titled “How the MCP maps to what we’ve already built”

Let’s make the connection explicit. In our database-first design, MCP tools look like well-named, well-bounded functions:

  1. Semantic search tool
    • api.sf_chat(p_question, p_k)
      • Returns: assistant text and evidence rows
  2. Structured query tool
    • api.sf_dynamic_chat(p_question, p_row_limit)
      • Returns: assistant text, SQL used, and evidence rows
  3. Hybrid tool
    • api.sf_hybrid_chat(p_question, p_max_price, p_k)
      • Returns: assistant text and evidence rows

If you squint, you’ll notice something elegant: We have already built the “tool layer” inside PostgreSQL. The MCP is how you expose that tool layer to a model safely and consistently, without making the model your DBA.

The practical payoff: Fewer prompts, more systems

Section titled “The practical payoff: Fewer prompts, more systems”

Once the MCP is in place, you stop doing “prompt engineering gymnastics” such as the following:

  • “Only output SQL.”
  • “Don’t use semicolons.”
  • “Never query system tables.”
  • “Always add LIMIT.”
  • “Don’t leak PII.”

Those are fragile because they live in the prompt language. Instead, you put the safety in the tool contract:

  • The tool enforces SELECT -only
  • The tool enforces allowlists
  • The tool enforces row caps
  • The tool uses a read-only role
  • The tool logs everything

The model can still be creative – in explanation, synthesis, and UX. But it cannot exceed the permissions of the tools you give it. That’s the difference between a clever demo and a durable product.

Now that we’ve introduced the MCP, the path forward becomes clear:

  1. We refine our tools so they are MCP-ready:
    • Stable inputs and outputs
      • Consistent row schemas
      • Predictable error handling
  2. We decide what we will allow the model to do:
    • Semantic retrieval
      • Structured retrieval
      • Hybrid retrieval
      • (Later) Safe analytics and reporting
  3. We add production controls around them:
    • Statement timeouts
      • Query cost controls
      • Role-based access
      • Auditing and monitoring

In other words, we don’t just build a chatbot. We build an AI interface to PostgreSQL that behaves like a responsible citizen.

The model can speak. PostgreSQL can enforce. The MCP makes the handshake real.

MCP-ready tool design for PostgreSQL: inputs, outputs, limits, and auditability

Section titled “MCP-ready tool design for PostgreSQL: inputs, outputs, limits, and auditability”

The MCP becomes powerful when your tools stop behaving like “clever tricks” and start behaving like products. A production tool has a few qualities:

  • It is predictable
  • It is bounded
  • It is easy to validate
  • It is easy to observe
  • It fails safely

So, in this section, we’ll take the functions we already built – api.sf_chat, api.sf_similar_items, api.sf_dynamic_chat, and friends – and tighten them into MCP-ready tools, not through changing their soul, but by sharpening their definitions. Clean definitions enable you to run fast and remain safe.

What “MCP-ready” means for a database tool

Section titled “What “MCP-ready” means for a database tool”

For a PostgreSQL function to behave like a proper MCP tool, it should satisfy four rules:

Rule 1: Stable, typed inputs

Inputs should be explicit and hard to misunderstand:

  • p_question text
  • p_k int
  • p_row_limit int
  • p_ max_price numeric

Avoid “magic” inputs such as the following:

  • JSON blobs with optional keys
  • Free-form directives mixed with user language
  • Implicit defaults that change behavior unpredictably

Rule 2: Bounded outputs

The tool must control the following:

  • How many rows can be returned (hard cap)
  • Which columns are returned (intentional schema)
  • How large responses can grow (avoid megabyte payloads)

This isn ’ t just performance, it ’ s trust and safety.

Rule 3: Evidence-first responses

A model should never have to “guess.” A tool should return the following:

  • Structured rows (evidence)
  • Optional helper metadata
  • Only then should the model narrate

This is why our design – rows + narration – is exactly right.

Rule 4: Auditability

You should be able to answer the following:

  • What question was asked?
  • What tool was used?
  • What SQL was run (if any)?
  • How long it took
  • How many rows were returned
  • Whether it succeeded or failed

MCP doesn’t force you to log, but production will.

Our current function is already strong:

  • It embeds the query (api.openai_embed)
  • It ranks products by vector distance (< = >``)
  • It joins in category and current price
  • It returns a typed table

That’s a great “tool surface.”

But there are two improvements that make it more production-shaped.

Improvement A: Separate “embedding computation” from “search execution”

Section titled “Improvement A: Separate “embedding computation” from “search execution””

Right now, api.sf_similar_items always embeds the query inside the function call.

That’s fine for demos and low volume. In production, repeated queries can waste calls and add latency. So, we give it an optional vector input:

  • If caller provides v_qvec, skip embedding
  • If caller provides p_query_text, embed it

This creates a clean bridge to caching (embeddings.sf_get_query_embedding) without changing the mental model.

Improvement B: Make the row limit and safety explicit

Section titled “Improvement B: Make the row limit and safety explicit”

We already accept p_k. We should clamp it down and make sure the values are always within safe boundaries.

This is the MCP-friendly version with the optional vector and a check constraint for p_k.

CREATE OR REPLACE FUNCTION api.sf_similar_items_v2(
p_query_text text DEFAULT NULL,
p_qvec_in vector(1536) DEFAULT NULL,
p_k int DEFAULT 10
)
RETURNS TABLE(
product_id int,
name text,
category text,
shortdescription text,
longdescription text,
price numeric,
distance double precision
)
LANGUAGE plpgsql
AS $$
DECLARE
v_qvec vector(1536);
p_k_safe int;
BEGIN
p_k_safe := GREATEST(1, LEAST(p_k, 50)); -- hard cap
IF p_qvec_in IS NOT NULL THEN
v_qvec := p_qvec_in;
ELSE
IF p_query_text IS NULL OR btrim(p_query_text) = '' THEN
RAISE EXCEPTION 'p_query_text or p_qvec_in must be provided';
END IF;
SELECT embeddings.sf_get_query_embedding(p_query_text)::vector(1536) INTO v_qvec;
END IF;
RETURN QUERY
WITH res AS MATERIALIZED (
SELECT
p.id AS product_id,
p.label::text AS name,
c.label::text AS category,
p.shortdescription::text AS shortdescription,
p.longdescription::text AS longdescription,
pvp.price AS price,
(v_qvec <=> pe.embedding) AS distance
FROM product.product p
JOIN embeddings.product_embedding pe ON p.id = pe.product_id
JOIN product.category c ON c.id = p.category_id
JOIN product.product_variant pv ON pv.product_id = p.id
JOIN product.product_variant_price pvp
ON pvp.product_variant_id = pv.id
AND pvp.current = true
ORDER BY pe.embedding <=> v_qvec
)
SELECT * FROM res
LIMIT p_k_safe;
END;
$$;

Now this function has become a true MCP tool:

  • Deterministic inputs
  • Bounded outputs
  • Typed result
  • Reusable in multiple flows (cached embeddings, hybrid pipelines)

Plugging in embeddings.sf_get_query_embedding

Section titled “Plugging in embeddings.sf_get_query_embedding”

Now we can show the production upgrade without changing the reader’s mental model:

WITH q AS (
SELECT embeddings.sf_get_query_embedding('looking for tailored clothing') AS qvec
)
SELECT *
FROM q, api.sf_similar_items_v2(NULL, q.qvec, 5);

This is a subtle but powerful shift:

  • The embedding can be cached
  • The search remains pure and fast
  • The tool contract stays clean

Your chatbot stays snappy, and your OpenAI bill stays sane.

api.sf_answer_with_openai(p_question, p_rows jsonb) is already “tool-shaped”:

  • It takes a question
  • It takes rows as evidence
  • It produces narration

To make it more MCP-friendly, we add one principle: The rows schema must be stable.

So, you should decide what columns you want “assistant-grade” tools to always provide. For your commerce dataset, a strong default is the following:

  • product_id
  • name
  • category
  • price
  • distance (optional)
  • attributes (optional)

Stability makes tools composable.

The final MCP-ready surface: the semantic tool and the dynamic tool

Section titled “The final MCP-ready surface: the semantic tool and the dynamic tool”

Now we’ll tighten the top-level tools as the model-facing entry points.

Instead of the model calling api.sf_similar_items and api.sf_answer_with_openai separately, you already created the ideal wrapper: api.sf_chat.

That’s exactly what MCP likes:

  • One tool call
  • One result
  • One evidence block

We’ll keep it, but we’ll cap p_k and make sure it uses caching if available.

For dynamic SQL, the tool shape should return the following:

  • assistant_text
  • rows (evidence)
  • sql_used (for audit)

We already do that in api.sf_dynamic_chat.

The MCP readiness improvements here are as follows:

  • Enforce statement_timeout for safety
  • Log the execution (optional, but recommended)
  • Ensure row limit is hard-capped

Even though we don’t build a full observability stack in this chapter, auditability is a must-have.

Here is a simple log table:

CREATE TABLE IF NOT EXISTS api.chat_audit_log (
id bigserial PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now(),
tool_used text NOT NULL,
question text NOT NULL,
sql_used text,
row_count int,
success boolean NOT NULL DEFAULT true,
error text
);

Now, our tools can write one row per call – for example, inside api.sf_dynamic_chat, after successful execution:

INSERT INTO api.chat_audit_log(tool_used, question, sql_used, row_count, success)
VALUES ('dynamic_sql', p_question, v_sql, jsonb_array_length(v_rows), true);

On error, we log the exception.

This turns “chatbot behavior” into something we can monitor like any other production system.

When we expose these tools through the MCP, we want the model to have exactly this experience:

  • Tool names are clear:
    • semantic_chat
      • dynamic_chat
      • hybrid_chat
  • Inputs are typed:
    • p_question
      • p_k / p_limit
      • p_max_price (optional)
  • Outputs are predictable:
    • rows + text (+ SQL if dynamic)
  • Limits are enforced:
    • Row caps
      • Timeouts
      • Allowlists

That means the model can focus on what it does best:

  • Interpreting intent
  • Picking the right tool
  • Summarizing results clearly

And the database can focus on what it does best:

  • Enforcing truth
  • Controlling access
  • Guaranteeing safe execution

That’s the handshake MCP was born for.

Implementing MCP tool routing for our PostgreSQL AI assistant

Section titled “Implementing MCP tool routing for our PostgreSQL AI assistant”

We now have multiple “brains” inside PostgreSQL: semantic retrieval (api.sf_chat), dynamic SQL (api.sf_dynamic_chat), and (optionally) hybrid patterns. The only question left is: how does the assistant reliably and safely choose the right one?

MCP’s answer is simple: tool selection is explicit, and policy is enforceable. So, we don’t rely on prompts such as “choose wisely.” We route with rules.

For this chapter, we keep the tool catalog intentionally small:

  • Semantic tool (api.sf_chat(p_question, p_k): Best when the user asks “something like…” / “recommend…” / intent-based browsing
  • Dynamic SQL tool (api.sf_dynamic_chat(question, row_limit)): Best when the user asks for filters, counts, ordering, or precise constraints
  • Hybrid tool (optional: api.sf_hybrid_chat(...)): Best when the user wants meaning and constraints (e.g., “like X under $Y”)

The model can propose a tool. The system enforces that choice with caps, allowlists, and timeouts.

A practical rule-of-thumb works well:

  • Semantic if the question is open-ended: similar, like, recommend, tailored, formal, casual…
  • Dynamic SQL if the question is structured: under $X, cheapest, count, average, by category/brand…
  • Hybrid if both appear together

This keeps “meaning” and “truth” in their own lanes. Here is a minimal router function:

DROP FUNCTION IF EXISTS api.sf_route_chat(
p_question text,
p_k integer,
p_row_limit integer
);
CREATE OR REPLACE FUNCTION api.sf_route_chat(
p_question text,
p_k integer DEFAULT 10,
p_row_limit integer DEFAULT 20
)
RETURNS TABLE (
tool_used text,
assistant_text text,
rows jsonb,
sql_used text
)
LANGUAGE plpgsql
VOLATILE
AS $function$
DECLARE
v_q text := lower(coalesce(p_question, ''));
v_has_constraints boolean;
v_has_intent boolean;
BEGIN
v_has_constraints :=
v_q ~ (
'\yunder\y|\yprice\y|\$|\ycheapest\y|\ymost expensive\y|\ycount\y|\yavg\y|' ||
'\ygroup\y|\ybrand\y|\ycategory\y|\ycolor\y|\ysize\y'
);
v_has_intent :=
v_q ~ (
'\ylike\y|\ysimilar\y|\yrecommend\y|\ytailored\y|\yformal\y|\ycasual\y|\yvibe\y'
);
--- Hybrid (constraints + intent)
IF v_has_constraints AND v_has_intent THEN
tool_used := 'hybrid';
sql_used := NULL;
SELECT h.assistant_text,
h.rows
INTO assistant_text,
rows
FROM api.sf_hybrid_chat(p_question, NULL, greatest(1, least(p_k, 30))) h;
--- One audit row per successful call
INSERT INTO api.chat_audit_log (tool_used, question, sql_used, row_count, success)
VALUES ('hybrid', p_question, NULL, jsonb_array_length(coalesce(rows, '[]'::jsonb)), true);
RETURN NEXT;
RETURN;
END IF;
--- Dynamic SQL (constraints)
IF v_has_constraints THEN
tool_used := 'dynamic_sql';
SELECT d.assistant_text,
d.rows,
d.sql_used
INTO assistant_text,
rows,
sql_used
FROM api.sf_dynamic_chat(p_question, greatest(1, least(p_row_limit, 50))) d;
--- One audit row per successful call
INSERT INTO api.chat_audit_log (tool_used, question, sql_used, row_count, success)
VALUES (
'dynamic_sql',
p_question,
sql_used,
jsonb_array_length(coalesce(rows, '[]'::jsonb)),
true
);
RETURN NEXT;
RETURN;
END IF;
--- Semantic default
tool_used := 'semantic';
sql_used := NULL;
SELECT c.assistant_text,
c.rows
INTO assistant_text,
rows
FROM api.sf_chat(p_question, greatest(1, least(p_k, 30))) c;
--- One audit row per successful call
INSERT INTO api.chat_audit_log (tool_used, question, sql_used, row_count, success)
VALUES ('semantic', p_question, NULL, jsonb_array_length(coalesce(rows, '[]'::jsonb)), true);
RETURN NEXT;
END;
$function$;

This function is “MCP-ready” because it does the following:

  • Keeps inputs typed and bounded (caps on p_k and p_row_limit)
  • Returns evidence rows every time
  • Exposes tool_used (great for debugging and audit)

Let’s look at two examples. The first one will use the hybrid tool, and the second one the dynamic SQL tool.

SELECT tool_used, assistant_text
FROM api.sf_route_chat('looking for tailored clothing', 2, 2);

The result indicates the tool (a hybrid in this case) and provides a friendly narrative explaining the results.

-[ RECORD 1 ]--+-------------------------------------------------------------------------------------------------------
tool_used | hybrid
assistant_text | You asked for tailored clothing, and I found 2 results for you.
|
| 1. **Suit coat - business perfect, by Brioni**
| - **Price:** $98.43
| - **Category:** Pants
| - **Description:** Classic tailored suit coat - premium wool,
| sharp silhouette, versatile elegance...
| Both items are the same, featuring a refined and versatile design
| suitable for various occasions.
SELECT tool_used, sql_used, assistant_text
FROM api.sf_route_chat('Show me polo shirts under $80', 2, 2);

The result of the second query shows that the dynamic SQL tool was used, the actual SQL, and also provides a friendly narrative explaining the results.

-[ RECORD 1 ]--+----------------------------------------------------------------------------------------------------
tool_used | dynamic_sql
sql_used | WITH polo_shirts AS (
| SELECT p.id, p.label, c.label AS category, pvp.price,
| pv.attributes +
| FROM product.product p
| JOIN product.category c ON p.category_id = c.id
| JOIN product.product_variant pv ON p.id = pv.product_id
| JOIN product.product_variant_price pvp ON
| pvp.product_variant_id = pv.id AND pvp.current = true+
| WHERE LOWER(p.label) LIKE '%polo%' AND pvp.price < 80
| )
| SELECT id, label, category, price, attributes
| FROM polo_shirts
| LIMIT 2
assistant_text | You asked to see polo shirts under $80. I found 2 results for you.
|
| 1. **Label**: Tommy Hilfiger Polo Shirt
| **Price**: $31.72
| **Category**: Shirts
| **Attributes**: Size - M, Color - Navy, Style - Classic Polo
|
| 2. **Label**: Tommy Hilfiger Polo Shirt
| **Price**: $31.72
| **Category**: Shirts
| **Attributes**: Size - L, Color - White, Style - Classic Polo

That’s the core idea: the model can speak, but the system steers.

Next, we’ll harden the steering with production controls: roles, timeouts, cost guards, and audit logging.

Adding production controls for MCP tools: Roles, timeouts, row caps, and cost guards

Section titled “Adding production controls for MCP tools: Roles, timeouts, row caps, and cost guards”

A chatbot demo is a sparkler; a production chatbot is a furnace. Once you expose database tools to a model – directly or through MCP – you must assume three things will happen sooner or later:

  1. A query will be too expensive.
  2. An answer will try to leak too much data.
  3. A model will misunderstand intent and run the wrong kind of query.

So, this section is about building seatbelts. Not because we don’t trust the model, but because we trust physics, and we know that Murphy’s law (anything that can go wrong will go wrong) is usually correct.

We will keep the controls practical and PostgreSQL-native, and we’ll apply them to the exact functions we’ve built in this chapter.

Guardrail 1: Use a r ead- o nly r ole for t ool e xecution

The cleanest safety control is also the oldest: least privilege.

Create a dedicated role for the assistant that meets the following criteria:

  1. Can only SELECT from the tables it needs
  2. Cannot INSERT / UPDATE / DELETE
  3. Cannot change schema
  4. Cannot access unrelated schemas (such as internal HR tables, finance tables, etc.)

Here is a sample implementation of this guardrail.

-- A role used by the MCP server / assistant runtime
CREATE ROLE mcp_assistant NOINHERIT;
-- Allow it to connect
GRANT CONNECT ON DATABASE aidb TO mcp_assistant;
-- Allow usage on schemas it needs
GRANT USAGE ON SCHEMA api, product, embeddings TO mcp_assistant;
-- Allow SELECT from required tables
GRANT SELECT ON
product.category,
product.brand,
product.product,
product.product_variant,
product.product_variant_price,
embeddings.product_embedding
TO mcp_assistant;
-- Allow execute on the specific functions we expose as tools
GRANT EXECUTE ON FUNCTION
api.sf_chat(text,int),
api.sf_similar_items(text,int),
api.sf_route_chat(text,int,int),
api.sf_dynamic_chat(text,int)
TO mcp_assistant;

If you add other tools later, you’ll intentionally grant access to maintain the least privilege principle.

No wildcard grants! No surprises! This single step prevents an entire class of disasters.

Guardrail 2: Enforce t imeouts so ” b ad q uestions ” d on ’ t b ecome i ncidents

Dynamic SQL is powerful. It is also a tool that needs to be handled with care. Even with allowlists and LIMITs, a query can still be slow. So, we enforce timeouts at execution time.

There are two common approaches:

  • Set statement_timeout at the role level (simple, global)
  • Set statement_timeout inside the tool function (surgical, per call)

Here, we look at setting statement_timeout at the role level:

ALTER ROLE mcp_assistant SET statement_timeout = '2s';

Here, we look at setting statement_timeout at the function level (inside your executor function):

PERFORM set_config('statement_timeout', '2000ms', true);

A timeout is not a failure – it’s a boundary that keeps your database from being held hostage by a single tool call.

Guardrail 3: Hard r ow c **aps (**b ecause LIMITs can be ” f orgotten ”****)

Models are surprisingly good at adding the LIMIT statement to queries. They are also surprisingly good at forgetting it at the worst moment. So, we don’t request a row limit. We enforce it.

You’ve already been doing this in the router (LEAST(p_row_limit, 50)), which is the right pattern. Apply the same rule inside:

  • api.sf_dynamic_chat
  • The SQL executor
  • Any function that returns JSON arrays

Here’s a simple rule of thumb: 10–50 rows for interactive chat Anything larger belongs in analytics/reporting UI, not a chatbot

Guardrail 4: Constrain d ynamic SQL to an a llowlist

Creating a dynamic SQL chatbot does not mean “run arbitrary SQL.” It means the following:

  • The model generates a query
  • The system enforces that the query is safe
  • The database executes it with bounded resources

Your allowlist should enforce the following:

  • SELECT only
  • No semicolons (prevents chaining)
  • No DDL/DML keywords (INSERT / UPDATE / DELETE / DROP / ALTER /…)
  • Only approved schemas (product, embeddings, maybe APIs)
  • Must include a LIMIT (or the executor injects one)

A practical validator (regex-based, “good enough” for a book chapter):

CREATE OR REPLACE FUNCTION api.sf_is_safe_select(
p_sql text
)
RETURNS boolean
LANGUAGE plpgsql
STABLE
AS $function$
DECLARE
v_sql_lc text := lower(coalesce(p_sql, ''));
BEGIN
--- Block empty
IF btrim(v_sql_lc) = '' THEN
RETURN false;
END IF;
--- Only one statement
IF position(';' IN v_sql_lc) > 0 THEN
RETURN false;
END IF;
--- Must start with SELECT or WITH
IF v_sql_lc !~ '^\s*(select|with)\y' THEN
RETURN false;
END IF;
--- Block dangerous keywords
IF v_sql_lc ~ '\y(insert|update|delete|drop|alter|create|truncate|grant|revoke|copy|call|do)\y' THEN
RETURN false;
END IF;
--- Restrict schemas (adjust as needed)
IF v_sql_lc ~ '\y(pg_catalog|information_schema)\y' THEN
RETURN false;
END IF;
RETURN true;
END;
$function$;

This way, the executor refuses anything that is not considered safe. This is a guardrail you can explain clearly to the users of your code: freedom inside a fence.

Guardrail 5: Cost g uards for e mbedding c alls

Embedding calls are not “free.” They do the following:

  • Create network traffic
  • Consume LLM tokens
  • Cause latency

We need two cost controls:

  • Caching query embeddings using embeddings.sf_get_query_embedding (we already introduced this earlier – perfect to reuse here)
  • Rate limiting/throttling tool calls at the MCP server layer or via a simple database counter

Inside the database, a minimal (and effective) “don’t spam embeddings” rule is as follows:

  1. Cap p_k.
  2. Cache query embeddings.
  3. Avoid generating embeddings if the query is too short or empty.

Here’s an example check:

IF length(btrim(p_question)) < 3 THEN
RAISE EXCEPTION 'Query too short to embed safely';
END IF;

Prefer checking the cache rather than generating new embeddings every time.

SELECT embeddings.sf_get_query_embedding(p_question) INTO qvec;

Guardrail 6: Always r eturn e vidence r ows (and k eep t hem s mall)

A production assistant should never return only prose. It should return the following:

  • Evidence (rows, as JSON)
  • Plus narration built strictly from that evidence

You’re already doing this with the following:

  • api.sf_chat(...) returns assistant_text + rows
  • api.sf_dynamic_chat(...) returns assistant_text + rows + sql_used

That’s the right design because it minimizes hallucinations as the AI assistant “speaks from receipts.” To keep receipts safe, do the following:

  • Cap the number of rows
  • Limit the fields that are accessible to the assistant
  • Avoid PII fields in views exposed to the assistant (or mask them)

When we put it all together to create the production-ready MCP execution, it will handle a request as follows:

  1. Route it (api.sf_route_chat).
  2. Execute under the mcp_assistant role.
  3. Enforce timeouts and row limits.
  4. Validate dynamic SQL if used.
  5. Log tool usage, SQL used, and row count (optional but strongly recommended).
  6. Narrate only from the returned rows.

At that point, your database isn’t just AI-enabled, it is AI-governed, and governance is what keeps the magic alive.

MCP tool contracts and safe views: Turning “function calls” into a reliable interface

Section titled “MCP tool contracts and safe views: Turning “function calls” into a reliable interface”

By now, we’ve built something that feels magical: you ask a question, and PostgreSQL answers like an assistant. But production doesn’t run on magic. It runs on interfaces – clear inputs, clear outputs, and boundaries that never blur. That is the real value MCP brings: it pushes us to treat “tools” not as clever hacks, but as contracts.

In this chapter, those contracts are already taking shape. Each tool returns a predictable structure: a human answer plus evidence rows. That’s not cosmetic – it’s a safety mechanism. When the assistant is forced to “speak from receipts,” hallucinations shrink and trust grows. For example, api.sf_chat(p_question, p_k) returns assistant_text and rows jsonb, where assistant_text is derived only from the rows we provide. Likewise, api.sf_dynamic_chat(...) (from earlier sections) returns the same evidence bundle plus sql_used, so every answer has a clear trail.

The next production step is subtle but essential: don’t let tools query raw tables directly. Even if we restrict to SELECT, raw tables tend to grow sharp edges over time: new columns appear, fields become sensitive, and joins pull in more than intended. Instead, we build a small “safe surface area” of views in the API schema and require our chatbot tools to use only those views. Think of it as a curated storefront for your data: the assistant can browse what is on display, but it can’t wander into the warehouse.

For our e-commerce schema, the safe views are straightforward. We expose only the columns the assistant truly needs for answering product questions, and we keep pricing current by default. Here is a practical example view consistent with the tables you are using (product.product, product.category, product.brand, product.product_variant, product.product_variant_price):

CREATE OR REPLACE VIEW api.product_search_vw AS
SELECT
p.id AS product_id,
p.label AS product_name,
c.label AS category,
b.label AS brand,
p.shortdescription AS shortdescription,
p.longdescription AS longdescription,
pv.id AS product_variant_id,
pv.attributes AS attributes,
pvp.price AS price
FROM product.product p
JOIN product.category c
ON c.id = p.category_id
JOIN product.brand b
ON b.id = p.brand_id
JOIN product.product_variant pv
ON pv.product_id = p.id
JOIN product.product_variant_price pvp
ON pvp.product_variant_id = pv.id
AND pvp.current = true;

Now your tools can evolve safely. Instead of joining five tables inside every function, you can query the view. More importantly, you now have a single choke point where you can decide: what is safe to expose to the assistant? If, later, you add customer data or order history, you don’t “accidentally” leak it through a join. You intentionally add a new view with masked columns, or you don’t add it at all.

This view-driven approach pairs cleanly with MCP’s philosophy. MCP doesn’t merely “let the model call tools.” It expects tools to have stable behavior and stable schemas. In practice, that means the following:

  • Inputs are typed and bounded (p_k capped, row_limit capped)
  • Outputs are structured (assistant text + evidence rows)
  • Data access is intentional (safe views, not raw tables)
  • Behavior is predictable (ordering rules, consistent aliases, consistent limits)

Once you adopt this discipline, your Postgres assistant stops being a demo and starts being an interface you can build on.

Operational checklists and the extension path

Section titled “Operational checklists and the extension path”

A production chatbot isn’t a single feature. It is a living system with three ongoing responsibilities: correctness, performance, and safety. The easiest way to make that real for your users is a checklist – because in production, checklists are how you keep promises.

Operational checklist: Running the AI chatbot successfully

Section titled “Operational checklist: Running the AI chatbot successfully”

C orrectness:

  • The assistant must only answer using evidence rows returned from SQL.
  • If the rows are empty, the assistant should say that it found nothing, no improvisation.
  • Keep response shapes stable (assistant_text, rows, and sql_used for dynamic SQL).
  • Stability matters because clients integrate against that shape.
  • Standardize column names and ordering in views.
  • Make the database return results in a predictable form every time.

P erformance:

  • Enforce row caps in every tool path.
  • A chatbot is not an analytics export job.
  • Use timeouts (statement_timeout) for tool execution roles.
  • Bad prompts should become fast failures, not slow outages.
  • Index what your tools actually touch:
    • embeddings.product_embedding should have the pgvector index (HNSW or IVFFlat)
      • Job/queue tables (if used) should have status/time indexes
      • Views should rely on underlying table indexes

Safety:

  • Execute tools under a dedicated read-only role (least privilege) – no write access, no schema changes, and no access to unrelated schemas
  • Validate dynamic SQL (SELECT -only, no semicolons, no dangerous keywords, only approved schemas/views)
  • Prefer querying api.*_vw views rather than raw tables, so you control exposure as the schema evolves

Observability:

  • Always return tool_used. Routing decisions become debuggable.
  • For dynamic SQL, always return sql_used. Every answer has an audit trail.
  • Log tool calls with: timestamp, tool name, question, row_count, latency, and error text (if any). These logs become your “flight recorder” when something feels off.

Security hygiene:

  • Rotate the OpenAI API key regularly and avoid hardcoding it in functions.
  • Your approach of storing the key in session-scoped settings is a reasonable baseline for demos; in production, you typically load keys from a secrets manager into the app tier, then pass them via safe configuration or a controlled proxy.
  • Consider network egress controls if the database is calling external APIs.
  • Many production teams prefer embedding generation in the app tier or a worker tier, with the database storing the AI vectors, because databases are precious and external network calls introduce operational risk.

Extension path: What you can build beyond this

Section titled “Extension path: What you can build beyond this”

If you want to take this further, the next step is to put the assistant behind an application runtime that enforces policy consistently. In a typical deployment, the user’s question flows from the application UI to an MCP server in the app tier. That MCP server selects the appropriate tool from a tool registry (for example, api.sf_chat for semantic retrieval or your dynamic SQL tool for structured queries), enforces guardrails such as timeouts and row caps, and then calls PostgreSQL using a restricted role. PostgreSQL returns structured results (evidence rows and assistant narrative), and the MCP server logs the tool call (tool used, SQL used if applicable, row count, latency) before returning a final response to the user.

We are not implementing the MCP server or a full tool registry in this book; that belongs to application architecture and platform engineering, and it varies by runtime. What we have done is the most important prerequisite: we designed our database functions to behave like well-formed tools: predictable inputs, predictable outputs, evidence-first answers, and a view-based data surface area. That means readers can adopt MCP later without reworking everything. They’ll already have a database that speaks in contracts, not improvisation – and that’s what makes production systems last.

In this chapter, we took our database assistant from “it works” to “it holds up.”

We built a practical chatbot workflow on top of the same PostgreSQL and pgvector foundation you’ve been developing throughout the book: embeddings stored alongside relational truth, similarity search performed with standard SQL, and responses grounded in evidence rows rather than free-form guesswork. Using api.sf_similar_items, we turned natural language into a query embedding with api.openai_embed, retrieved the closest products from embeddings.product_embedding, and returned structured results that can be safely consumed by both humans and applications. We then added an interpretation layer with api.sf_answer_with_openai, which converts returned rows into a readable, user-friendly response, while staying explicitly constrained to what the database actually produced.

From there, we focused on the production shape of the system. We treated database functions as tools with contracts: stable inputs, stable outputs, predictable limits, and a clear audit trail. We introduced the idea of a curated API surface using api.*_vw views so the assistant queries only what you intentionally expose, rather than roaming through raw tables as schemas evolve. We reinforced the essential production disciplines – correctness, performance, safety, observability, and security hygiene – so the assistant remains fast, bounded, and debuggable under real usage.

Finally, we framed how these ideas align naturally with MCP thinking: tools are not “clever calls,” they are governed interfaces. Without turning the chapter into an MCP implementation guide, we established the mental model: PostgreSQL provides trusted retrieval and structured evidence, while higher layers can orchestrate tool selection and policy. The result is a chatbot architecture that preserves the strengths of PostgreSQL – determinism, governance, and composability – while adding a meaning-aware conversational interface that remains grounded in data and operationally reliable.

In the next chapter, we will zoom out to connect the dots across the entire journey. You’ll revisit the core ideas of transactional, analytical, and AI workloads – and see how PostgreSQL ties them together into one unified platform.