Dialogflow MCP Server & PostgreSQL
Order South African food in natural language, from any AI client.
A remote Model Context Protocol server that turns a Dialogflow ES ordering agent and a PostgreSQL order database into eight typed, role-gated tools. Claude Code, Claude Desktop, Cursor or a custom agent connect over HTTPS with a Bearer token; the server runs on Railway in its US East region, next to its Neon database.
- MCP tools (5 customer, 3 admin)
- 8
- South African dishes, priced in ZAR
- 9
- automated tests
- 280+
- transaction per order
- 1

Nyiko Shabangu
AI Engineer & Systems Architect · Published · Updated · ~14 min read
02 • The problem
Webhook glue versus the MCP contract
Most Dialogflow bots answer through a fulfillment webhook: Dialogflow calls an endpoint you host (often an ngrok tunnel during development) and that endpoint holds the business logic. It works for one chat surface, but every new client is another bespoke integration, and the logic is split between console settings and webhook code.
This project switches the webhook off. Dialogflow does what it is good at, classifying the intent and extracting dishes and quantities, and its replies are static text. The business rules live in PostgreSQL behind an MCP server, and an AI client runs the conversation by calling tools.
Webhook glue
- One custom endpoint per integration
- Logic split between the console and webhook code
- Clients cannot discover what the bot can do
MCP contract
- One server; clients discover the tools with
tools/list - Tool schemas come from typed Python signatures and docstrings
- Any MCP client, one auth model, one place for the rules
03 • Architecture
Architecture
Three systems, one contract. Dialogflow ES understands the language, PostgreSQL holds the menu and orders and enforces the rules in transactions, and the MCP server is the only thing AI clients talk to. No bespoke REST API and no webhook.
Components
| Component | Technology | Responsibility |
|---|---|---|
| MCP server (remote)remote_server.py, server_es.py | Python 3.14, FastMCP, Starlette, uvicorn | Streamable HTTP at /mcp (SSE optional via MCP_TRANSPORT=sse), Bearer auth, Host/Origin allowlist, tool dispatch |
| MCP server (local)server_es.py (ES), server.py (CX) | FastMCP over stdio | Local development and desktop use. The CX server is an experimental, detect_intent-only adapter with no database |
| Auth middlewareBearerAuthASGIMiddleware | Pure ASGI, hmac.compare_digest | Checks Host/Origin first, then the token, and sets the request's role to user or admin. /health is the only public path |
| NLUserver_es.py | Dialogflow ES v2, cached SessionsClient | Intent and parameter extraction; regional endpoint when DF_LOCATION is not global. Webhook off, so replies are the agent's static text |
| Agent definitiondialogflow/agent/, scripts/dialogflow_agent.py | Dialogflow agent exported as JSON | Intents and entities versioned in git, exported and restored through the API |
| Persistencedatabase.py, db/init.sql | psycopg 3 + psycopg_pool (max 5, 10 s timeout) | Menu, orders, order lines and conversation logs. Order placement is one transaction |
| Google credentialsgcp_auth.py | google-auth service account | Key content from GOOGLE_APPLICATION_CREDENTIALS_JSON (for Railway), or Application Default Credentials |
| ContainerDockerfile, .dockerignore | python:3.14-slim, uv 0.12.8, multi-stage | Reproducible image from the locked dependencies, running as a non-root user. The build context excludes secrets |
| Hosting.railway/railway.ts | Railway, configured as code | Dockerfile build, /health check, restart on failure, one replica in Railway's US East region, next to Neon |
| Database hostingAWS us-east-1 | Neon (managed Postgres) | Production database over TLS, using the direct (unpooled) connection string because the server pools itself |
| CI.github/workflows/ci.yml | GitHub Actions | pytest on Python 3.10 and 3.14 against a Postgres service container, plus a Docker image smoke test |
- Component
- MCP server (remote)remote_server.py, server_es.py
- Technology
- Python 3.14, FastMCP, Starlette, uvicorn
- Responsibility
- Streamable HTTP at /mcp (SSE optional via MCP_TRANSPORT=sse), Bearer auth, Host/Origin allowlist, tool dispatch
- Component
- MCP server (local)server_es.py (ES), server.py (CX)
- Technology
- FastMCP over stdio
- Responsibility
- Local development and desktop use. The CX server is an experimental, detect_intent-only adapter with no database
- Component
- Auth middlewareBearerAuthASGIMiddleware
- Technology
- Pure ASGI, hmac.compare_digest
- Responsibility
- Checks Host/Origin first, then the token, and sets the request's role to user or admin. /health is the only public path
- Component
- NLUserver_es.py
- Technology
- Dialogflow ES v2, cached SessionsClient
- Responsibility
- Intent and parameter extraction; regional endpoint when DF_LOCATION is not global. Webhook off, so replies are the agent's static text
- Component
- Agent definitiondialogflow/agent/, scripts/dialogflow_agent.py
- Technology
- Dialogflow agent exported as JSON
- Responsibility
- Intents and entities versioned in git, exported and restored through the API
- Component
- Persistencedatabase.py, db/init.sql
- Technology
- psycopg 3 + psycopg_pool (max 5, 10 s timeout)
- Responsibility
- Menu, orders, order lines and conversation logs. Order placement is one transaction
- Component
- Google credentialsgcp_auth.py
- Technology
- google-auth service account
- Responsibility
- Key content from GOOGLE_APPLICATION_CREDENTIALS_JSON (for Railway), or Application Default Credentials
- Component
- ContainerDockerfile, .dockerignore
- Technology
- python:3.14-slim, uv 0.12.8, multi-stage
- Responsibility
- Reproducible image from the locked dependencies, running as a non-root user. The build context excludes secrets
- Component
- Hosting.railway/railway.ts
- Technology
- Railway, configured as code
- Responsibility
- Dockerfile build, /health check, restart on failure, one replica in Railway's US East region, next to Neon
- Component
- Database hostingAWS us-east-1
- Technology
- Neon (managed Postgres)
- Responsibility
- Production database over TLS, using the direct (unpooled) connection string because the server pools itself
- Component
- CI.github/workflows/ci.yml
- Technology
- GitHub Actions
- Responsibility
- pytest on Python 3.10 and 3.14 against a Postgres service container, plus a Docker image smoke test
04 • Turn flow
How a turn flows
A conversation is a series of tool calls the AI client chooses to make. Dialogflow never places an order; it tells the client what the user meant, and the client calls complete_order when the user is done.
POST /mcp first passes the Host/Origin check and Bearer auth (Figure 1). The LLM client decides when to call complete_order; Dialogflow only classifies.- The client passes the same
session_idon every turn, so Dialogflow keeps the conversation's contexts between calls. - Every turn is written to
conversation_logs, and a logging failure never fails the user's request. - Prices never come from the client:
complete_orderlooks every dish up in the database and computes the totals itself (2 × R85 + R30 = R200.00 in the example).
FastMCP turns a typed Python function into a tool: the signature becomes the input schema and the docstring becomes the description the model reads. This is the real detect_intent, abridged:
# src/diaglogflowmcp/server_es.py (abridged)
mcp = FastMCP("dialogflow-food-ordering-es")
@mcp.tool()
def detect_intent(
text: str,
session_id: str | None = None,
language_code: str = "en",
) -> dict:
"""Send a user message to the Dialogflow ES Food Ordering agent.
...
Logs the conversation turn to the PostgreSQL database."""
sid = session_id or str(uuid.uuid4())
session = _session_path(sid)
client = _sessions_client()
response = client.detect_intent(
request=dialogflow.DetectIntentRequest(
session=session,
query_input=dialogflow.QueryInput(
text=dialogflow.TextInput(
text=text,
language_code=language_code,
),
),
)
)
result = response.query_result
...
intent_name = result.intent.display_name if result.intent else None
confidence = result.intent_detection_confidence
fulfillment = result.fulfillment_text
extracted_params = MessageToDict(result._pb).get("parameters", {})
# Log interaction to PostgreSQL
try:
execute(
"""INSERT INTO conversation_logs
(session_id, user_message, bot_response, intent, parameters, confidence)
VALUES (%s, %s, %s, %s, %s, %s)""",
(
sid,
text,
fulfillment,
intent_name,
json.dumps(extracted_params),
confidence,
),
)
except Exception:
# Don't fail the tool call if database logging encounters an error
logger.warning(
"Failed to log conversation turn for session %s", sid, exc_info=True
)
return {
"session_id": sid,
"fulfillment_text": fulfillment,
"intent": intent_name,
"confidence": confidence,
"parameters": extracted_params,
"contexts": contexts,
"action": result.action or None,
"all_required_params_present": result.all_required_params_present,
}05 • Conversation
Conversational design
The “SA Food Ordering” agent is small on purpose: eight intents (the six below plus the default welcome and fallback), two contexts and one entity. Contexts gate which intents can match. order.add, order_remove and order.complete only match while ongoing-order is active, which new.order sets for five turns.
| Intent | Context in → out | Parameters | What the client does |
|---|---|---|---|
| new.order | none → ongoing-order | none | Start a cart. The reply lists the 9 dishes and asks for a quantity per dish |
| order.add | ongoing-order → ongoing-order | food_Item[], number[] | Add dishes and quantities to the cart |
| order_remove | ongoing-order → ongoing-order | food_Item[] | Remove dishes from the cart |
| order.complete | ongoing-order | none | Call complete_order with the cart |
| track.order | none → ongoing-tracking | number (integer, required) | Call track_order; the agent asks for the order number if it is missing |
| track.order - more | ongoing-tracking | number | Follow-up turn that supplies the order number |
- Intent
- new.order
- Context in → out
- none → ongoing-order
- Parameters
- none
- What the client does
- Start a cart. The reply lists the 9 dishes and asks for a quantity per dish
- Intent
- order.add
- Context in → out
- ongoing-order → ongoing-order
- Parameters
- food_Item[], number[]
- What the client does
- Add dishes and quantities to the cart
- Intent
- order_remove
- Context in → out
- ongoing-order → ongoing-order
- Parameters
- food_Item[]
- What the client does
- Remove dishes from the cart
- Intent
- order.complete
- Context in → out
- ongoing-order
- Parameters
- none
- What the client does
- Call complete_order with the cart
- Intent
- track.order
- Context in → out
- none → ongoing-tracking
- Parameters
- number (integer, required)
- What the client does
- Call track_order; the agent asks for the order number if it is missing
- Intent
- track.order - more
- Context in → out
- ongoing-tracking
- Parameters
- number
- What the client does
- Follow-up turn that supplies the order number
The food_Item entity and the menu
food_Item is a map entity with fuzzy extraction. It holds exactly the nine dishes on the menu, and each canonical value matches food_items.name in the database, so whatever Dialogflow extracts can be passed straight to complete_order. Local synonyms do the rest:
| Dish | Price | Category | Also understood as |
|---|---|---|---|
| Bunny Chow | R85 | Main | bunny, bunnies, curry bunny, quarter bunny |
| Boerewors Roll | R45 | Street Food | boerie, boerie roll, wors roll, boerewors |
| Pap & Chakalaka | R35 | Traditional | pap, chakalaka, pap en chakalaka |
| Bobotie | R75 | Main | boboti, boboties |
| Vetkoek | R30 | Street Food | magwinya, fat cakes, vetkoeke |
| Kota | R40 | Street Food | kotas, skhambane, spatlo |
| Malva Pudding | R35 | Dessert | malva, malva puddings |
| Milk Tart | R30 | Dessert | melktert, milktart, milk tarts |
| Sosaties | R60 | Braai / Grill | sosatie, skewers |
- Dish
- Bunny Chow
- Price
- R85
- Category
- Main
- Also understood as
- bunny, bunnies, curry bunny, quarter bunny
- Dish
- Boerewors Roll
- Price
- R45
- Category
- Street Food
- Also understood as
- boerie, boerie roll, wors roll, boerewors
- Dish
- Pap & Chakalaka
- Price
- R35
- Category
- Traditional
- Also understood as
- pap, chakalaka, pap en chakalaka
- Dish
- Bobotie
- Price
- R75
- Category
- Main
- Also understood as
- boboti, boboties
- Dish
- Vetkoek
- Price
- R30
- Category
- Street Food
- Also understood as
- magwinya, fat cakes, vetkoeke
- Dish
- Kota
- Price
- R40
- Category
- Street Food
- Also understood as
- kotas, skhambane, spatlo
- Dish
- Malva Pudding
- Price
- R35
- Category
- Dessert
- Also understood as
- malva, malva puddings
- Dish
- Milk Tart
- Price
- R30
- Category
- Dessert
- Also understood as
- melktert, milktart, milk tarts
- Dish
- Sosaties
- Price
- R60
- Category
- Braai / Grill
- Also understood as
- sosatie, skewers
06 • Data
Data model and transactions
Four tables. The database, not the model, enforces the rules that matter: prices and totals are never negative, quantities are above zero, an order's status is one of five values, each dish appears once per order, and a trigger keeps updated_at current.
db/init.sql. One order has many line items; a dish can appear on many line items. Deleting an order cascades to its lines; deleting a dish that was ever ordered is refused.complete_order is all or nothing
Placing an order touches two tables. If the order row were committed and a line item then failed (an unknown dish, a dish out of stock, more than 50 of one dish), the database would hold an order with missing lines. So every lookup and insert runs on one connection in one transaction:
# src/diaglogflowmcp/database.py
@contextmanager
def transaction() -> Generator[psycopg.Cursor, None, None]:
"""Yield a cursor bound to ONE connection and ONE transaction.
Everything executed on the cursor is committed together when the block
exits normally, or rolled back together if it raises."""
with get_connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
yield cur# src/diaglogflowmcp/server_es.py (abridged)
@mcp.tool()
def complete_order(
customer_name: str,
customer_phone: str,
items: list[dict],
delivery_address: str = "Counter Collection",
) -> dict:
...
# Item lookups, the order insert and all line-item inserts share ONE
# connection and ONE transaction: any failure rolls everything back.
try:
with transaction() as cur:
...
for entry, qty in zip(items, quantities):
item_row, item_error = _resolve_food_item(run_query, entry["name"])
if item_error:
raise _OrderAborted(item_error)
if not item_row["is_available"]:
raise _OrderAborted(
f"Item '{item_row['name']}' is currently out of stock."
)
...
cur.execute(
"""INSERT INTO orders
(customer_name, customer_phone, total_price, order_status, delivery_address)
VALUES (%s, %s, %s, 'in progress', %s)
RETURNING order_id, total_price, order_status, created_at""",
(customer_name, customer_phone, total_order_price, delivery_address),
)
new_order = cur.fetchone()
...
order_id = new_order["order_id"]
# Insert order line items
for line in order_items_to_insert:
cur.execute(
"""INSERT INTO order_items (order_id, item_id, quantity, unit_price, total_price)
VALUES (%s, %s, %s, %s, %s)""",
(order_id, line["item_id"], line["quantity"], line["unit_price"], line["total_price"]),
)
except _OrderAborted as exc:
return {"error": str(exc)}- Customer fields and quantities (whole numbers, 1 to 50) are validated before the database is touched.
- Raising
_OrderAbortedinside the block rolls back the lookups and any inserts; the client gets a readable error, never a raw database exception. - Repeated dishes are merged into one line, which keeps the
UNIQUE (order_id, item_id)constraint satisfied. - Totals are computed with
Decimalfrom database prices, and a real-Postgres integration test checks that a failed line leaves no order behind.
07 • Security
Security model
The server is on the public internet and holds customer names, phone numbers and addresses, which South Africa's POPIA requires me to safeguard. Every request to /mcp passes the same pipeline:
- TLS at the edge. Railway terminates HTTPS; the container speaks plain HTTP on Railway's private network, so the token never travels in clear text over the internet.
- Host and Origin allowlist. Unknown hosts get 421 and unknown browser origins 403, before any token work. This blocks DNS-rebinding attacks.
- Two Bearer tokens. The header is compared with the user token and the admin token in constant time, always both. No match gets 401.
- A role on every request. The middleware stores
useroradminon that request only; tools check it each time they run.
# src/diaglogflowmcp/remote_server.py, BearerAuthASGIMiddleware (abridged)
if scope["type"] == "http" and scope.get("path", "") not in PUBLIC_PATHS:
if self._security is not None:
error = await self._security.validate_request(
HTTPConnection(scope), is_post=False
)
if error is not None:
await error(scope, receive, send)
return
...
# Compare against both tokens unconditionally (no short-circuit),
# so timing does not reveal which one matched.
is_user = hmac.compare_digest(provided, self._expected)
is_admin = False
if self._expected_admin is not None:
is_admin = hmac.compare_digest(provided, self._expected_admin)
if not (is_user or is_admin):
...
await response(scope, receive, send)
return
role = "admin" if is_admin else self._user_role
# Fresh per-request copy: never mutate a state dict that might be
# shared with other requests. Starlette's Request.state reads it.
scope = {**scope, "state": {**scope.get("state", {}), "mcp_role": role}}
await self.app(scope, receive, send)Tools by role
| Tool | Role | Reads / writes | Notes |
|---|---|---|---|
| detect_intent(text, session_id?, language_code) | user | Dialogflow call; writes conversation_logs | A logging failure is logged and never fails the call |
| get_menu(category?) | user | reads food_items | Available dishes only; the category filter escapes LIKE wildcards |
| get_food_item_details(food_name) | user | reads food_items | Exact case-insensitive match first, then a unique substring match |
| track_order(order_id) | user | reads orders, order_items | Customer name, phone and address removed unless the caller is admin |
| complete_order(customer_name, customer_phone, items, delivery_address) | user | writes orders, order_items | One transaction; 1–50 per dish; prices and totals computed on the server |
| update_order_status(order_id, new_status) | admin | writes orders | in progress, preparing, out for delivery, delivered, cancelled |
| get_recent_orders(limit, status?) | admin | reads orders | limit clamped to 1–100 |
| get_conversation_logs(session_id?, limit) | admin | reads conversation_logs | limit clamped to 1–100 |
- Tool
- detect_intent(text, session_id?, language_code)
- Role
- user
- Reads / writes
- Dialogflow call; writes conversation_logs
- Notes
- A logging failure is logged and never fails the call
- Tool
- get_menu(category?)
- Role
- user
- Reads / writes
- reads food_items
- Notes
- Available dishes only; the category filter escapes LIKE wildcards
- Tool
- get_food_item_details(food_name)
- Role
- user
- Reads / writes
- reads food_items
- Notes
- Exact case-insensitive match first, then a unique substring match
- Tool
- track_order(order_id)
- Role
- user
- Reads / writes
- reads orders, order_items
- Notes
- Customer name, phone and address removed unless the caller is admin
- Tool
- complete_order(customer_name, customer_phone, items, delivery_address)
- Role
- user
- Reads / writes
- writes orders, order_items
- Notes
- One transaction; 1–50 per dish; prices and totals computed on the server
- Tool
- update_order_status(order_id, new_status)
- Role
- admin
- Reads / writes
- writes orders
- Notes
- in progress, preparing, out for delivery, delivered, cancelled
- Tool
- get_recent_orders(limit, status?)
- Role
- admin
- Reads / writes
- reads orders
- Notes
- limit clamped to 1–100
- Tool
- get_conversation_logs(session_id?, limit)
- Role
- admin
- Reads / writes
- reads conversation_logs
- Notes
- limit clamped to 1–100
Admin tools are still listed for user-token clients; they refuse inside the tool. Hiding a name is not a security control, and the check that matters runs on every call. The same per-request check removes customer details from track_order, because order numbers are sequential and anyone with the user token could otherwise walk through them:
# src/diaglogflowmcp/server_es.py (abridged)
_CUSTOMER_PII_FIELDS = ("customer_name", "customer_phone", "delivery_address")
# track_order: user-token callers never see customer PII
if not ADMIN_TOOLS_ENABLED or _admin_denied() is not None:
for field in _CUSTOMER_PII_FIELDS:
order.pop(field, None)
# every admin tool starts with the per-request gate
def update_order_status(order_id: int, new_status: str) -> dict:
...
if (denied := _admin_denied()) is not None:
return deniedSecrets
- Tokens, the database URL and the Google key live only in Railway's variables. The infrastructure file deliberately manages no variables, and values are set through stdin so they never reach shell history.
- The server refuses to start with a token shorter than 16 characters, with identical user and admin tokens, or with an invalid Google key.
- The Google service account has only the Dialogflow API Client role. Exporting or restoring the agent needs a separate admin account.
- Clients hold only a token: no database URL and no Google credential ever leaves the server.
08 • Operations
Production deployment and operations
The server ships as one Docker image: a multi-stage build that installs the locked dependencies with uv and runs as a non-root user. Railway builds that Dockerfile, and the service settings are code in .railway/railway.ts:
// .railway/railway.ts (abridged)
export default defineRailway(() => {
const mcpServer = service("mcp-server", {
build: { buildEnvironment: "V3", builder: "DOCKERFILE", dockerfilePath: "Dockerfile" },
healthcheck: "/health",
healthcheckTimeout: 60,
deploy: { restartPolicyType: "ON_FAILURE", restartPolicyMaxRetries: 5 },
// US East (Virginia): next to Neon aws-us-east-1, so each SQL round trip stays in-region.
replicas: { "us-east-1": 1 },
});
return project("diaglogflowmcp", {
variables: { managed: false },
resources: [mcpServer],
});
});- Region next to the data. The service first ran on Railway's US West region while Neon sits in AWS us-east-1, so every SQL round trip crossed the continent. It now runs in Railway's US East region, next to Neon; latency after the move has not been re-measured yet.
- Neon Postgres. The server uses Neon's direct connection string and its own small pool (5 connections, 10-second wait), so Neon's pooler is not needed.
- Health checks.
/healthis the only public path, so Railway's probe gets a 200 while everything else needs a token. Because the probe stays green without a database or Google key, the server prints a warning at startup for each one that is missing. - Rollback. Redeploy an earlier Railway deployment. Variables are not part of a deployment, so a rollback across a configuration change means changing the variables first.
- Token rotation. Generate a new value, set it on Railway (which redeploys), then update each client. The old token stops working as soon as the new deployment is live.
# Health and auth smoke checks after every deploy
curl https://<your-host>/health # 200, no token needed
curl -X POST https://<your-host>/mcp # 401 without a token
# Rotate a token: generate, then set it through stdin so it never lands in shell history
python -c "import secrets; print(secrets.token_urlsafe(32))"
printf '%s' "$NEW_TOKEN" | railway variable set MCP_AUTH_TOKEN --stdin09 • Agent as code
Agent as code
A Dialogflow agent normally lives only in the Google Cloud console, where a change has no history and no review. Here the whole agent (intents, training phrases, contexts and the entity) is exported to JSON in dialogflow/agent/ and committed. The rule: change it in the console or through the API, then export and commit, so git always matches the live agent.
# Pull the live agent into dialogflow/agent/, then review it like code
uv run python scripts/dialogflow_agent.py export --project <gcp-project> --gcloud
git diff -- dialogflow/agent
# Push dialogflow/agent/ into a project. This REPLACES that project's whole agent.
uv run python scripts/dialogflow_agent.py restore --project <gcp-project> --confirm <gcp-project> --gcloud- Every change to the agent is a reviewable git diff.
- Webhook usernames, passwords and headers are blanked before the export is written, so no credential reaches git.
- Zipped backups of earlier agent versions sit in
dialogflow/backups/, and a restore can rebuild the agent in any project, which is how the staging copy for the eval gate is made.
10 • Testing
Testing and CI
The suite has 280+ automated tests, in three layers.
- Unit tests need no database, network or Google credentials: input validation, item matching, the admin gate, PII removal, startup refusals and session paths.
- Real-Postgres integration tests drop and recreate the schema from
db/init.sqlbefore every test, and cover ordering, tracking, logging and the all-or-nothing rollback. They run only against a throwaway database, never Neon. - Remote probes start the real ASGI app in a subprocess and check the HTTP behaviour: 401 without a token, 421 for an unknown host, and admin refusals for the user token.
The GitHub Actions workflow runs pytest on Python 3.10 and 3.14 against a Postgres 17 service container, and a second job builds the same Dockerfile Railway deploys and smoke-tests it:
# .github/workflows/ci.yml (abridged)
jobs:
test:
name: pytest (Python ${{ matrix.python-version }})
strategy:
matrix:
python-version: ["3.10", "3.14"]
services:
postgres:
image: postgres:17-alpine
...
- name: Run tests
run: uv run pytest -q -rs
docker:
name: Docker image smoke test
...
- name: Build image
run: docker build -t mcp-server:ci .
...
code=$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8000/mcp)
test "$code" = "401"- Secret scan. A local quality gate fails on private-key headers, service-account key JSON, tracked
.envfiles and Postgres URLs with a real password. It prints nothing, so a secret never lands in a log. Moving it into CI is part of the current plan. - In progress: an NLU eval harness. It restores the git-versioned agent into a separate, billing-free staging project, trains it, scores a labelled set of utterances for intent and entity accuracy, and fails a change that drops accuracy by more than 2%.
11 • Decisions
Design decisions
The security work is recorded as architecture decision records. Each one names the decision, why it was made, and whether it is already in the code.
- ADR-001Fail-closed admin gatePlanned
In remote mode the gate refuses when it finds no request role, and admin tools register through one decorator pinned by an inventory test. Why: A silent SDK change, or a new tool that forgets the check, must not hand user tokens admin rights.
- ADR-002PII allowlist in track_orderPlanned
Non-admin callers get only order_id, total_price, order_status, timestamps and line items. Why: Today's blocklist would leak any column added later; POPIA's security-safeguards condition applies.
- ADR-003Constant-time comparison of both tokensIn code
hmac.compare_digest on the raw header against the user and the admin token on every request, with no short-circuit. Why: Timing reveals neither the token nor which one matched.
- ADR-004Unfiltered tools/listIn code
Admin tools stay visible to user-token clients and refuse inside the tool. Why: Hiding names is not a security control, and clients cache the list per session while the role is per request.
- ADR-005Admin settings precedencePartly in code
An admin token implies the admin tools; a contradictory setting refuses to start; a blank MCP_ADMIN_TOOLS counts as unset. Why: An empty .env line should not block startup or silently change who is admin.
- ADR-006CI with real-database testsPartly in code
DB tests are opt-in through TEST_DATABASE_URL, required in CI against a service container, behind a guard that refuses unsafe URLs. Why: The tests drop the schema, so they must never reach Neon or the dev database.
- ADR-007Session bound to its tokenPlanned
Bind each MCP session to the credential that opened it through the SDK's AuthenticatedUser (option 2, approved). Why: Stops another token holder posting into, or deleting, a live session.
- ADR-008Single-line logs in remote modePlanned
Replace the Rich log handler with a plain one-line format on stderr. Why: Wrapped lines break log search in Railway's viewer.
12 • Limitations
Limitations and next steps
What this is not, yet, and what comes next.
Shared tokens, not OAuth
Two shared secrets (user and admin) are not per-person identities, so there is no audit trail of who made a call. Per-user identity through OAuth is the next step for anything beyond a demo.
Session binding is pending
The approved design (ADR-007, option 2) binds each MCP session to the token that opened it. Until it ships, the role is checked on every request, but a token holder who learns a live session id can post into that session.
CI is blocked on the private working repository
The private working repository's GitHub Actions runs end in startup_failure because of an account billing lock, so the gates run locally for now. The workflow itself is unchanged and ready.
Dialogflow ES Trial edition quotas
The agent runs on the free Trial edition: text detect-intent is limited to 180 requests a minute, with HTTP 429 above that. Fine for a demo, not for real traffic. The server has no rate limiting of its own yet.
Free-tier hosting
Railway's free credit is smaller than the idle cost of an always-on service, and Neon's free plan suspends compute after 5 idle minutes, so the first query after a quiet spell is slower.
Evals, then an LLM hybrid
An NLU eval gate is in progress: it restores the git-versioned agent into a separate staging project, trains it, scores a labelled utterance set, and fails a change that drops accuracy by more than 2%. After that, a hybrid where an LLM handles low-confidence and fallback turns.
Backups need written targets
Neon offers point-in-time restore, but the recovery point and recovery time objectives are not written down yet.
13 • Try it
Try it
Connect any MCP client that speaks Streamable HTTP. Replace <your-host> with your own deployment and <YOUR_TOKEN> with its user token; never commit a real token.
Claude Code
claude mcp add --transport http food-ordering https://<your-host>/mcp \
--header "Authorization: Bearer <YOUR_TOKEN>"Or share it with a project through .mcp.json. Claude Code expands ${MCP_AUTH_TOKEN} from your environment, so the file itself holds no secret:
{
"mcpServers": {
"food-ordering": {
"type": "http",
"url": "https://<your-host>/mcp",
"headers": {
"Authorization": "Bearer ${MCP_AUTH_TOKEN}"
}
}
}
}In Claude Desktop or claude.ai, add it as a custom connector with the same /mcp URL and an Authorization header. Connectors are called from Anthropic's cloud, so the server must be reachable from the internet.
Source code
Server, schema, Dockerfile, Railway config, agent export and tests.
Live demo
Order from the nine-dish menu, place the order and track it, all through the production MCP server. Your messages go to this site's own /api proxy and a server-side agent backend, so no MCP token or server address reaches your browser. Messages are logged and demo orders are deleted daily, so please don't enter personal details.
More case studies: API-first vs. tool calling benchmark, Vertex AI RAG server and chatbot architecture.