Model Context ProtocolDialogflow ESPostgreSQLRailway + Neon

    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.

    Dialogflow MCP Server architectureFour kinds of MCP client (Claude Code; Claude Desktop or claude.ai through a custom connector; Cursor and custom agents; and a planned agent backend for the portfolio live demo) call the server over HTTPS with a Bearer token using Streamable HTTP at /mcp. The Railway edge terminates TLS and forwards plain HTTP to the mcp-server container (Docker, uvicorn, FastMCP, one replica in Railway's US East region, next to Neon). Inside it, step 1 checks the Host and Origin headers against an allowlist (421 or 403), step 2 compares the token with the user and admin tokens in constant time (401 otherwise) and sets the role. Customer tools, usable by either role, are detect_intent, get_menu, get_food_item_details, track_order and complete_order. Admin tools, usable only with the admin token, are update_order_status, get_recent_orders and get_conversation_logs. The server calls Dialogflow ES (the SA Food Ordering agent, webhook off, intents new.order, order.add, order_remove, order.complete and track.order) over gRPC, and Neon Postgres in AWS us-east-1 over TLS through a psycopg 3 connection pool, with the tables food_items, orders, order_items and conversation_logs.MCP CLIENTSClaude Codehttp transport + headerClaude Desktopor claude.ai, custom connectorCursor, custom agentsany MCP clientAgent backendportfolio live demo (planned)HTTPS · Streamable HTTP · POST /mcpAuthorization: Bearer <token>Railway edgeTLS ends hereplain HTTP inmcp-server · Railway US EastDocker · uvicorn · FastMCP1 · Host / Origin allowlist421 / 403 before any token work2 · Bearer auth, constant timerole = user | admin, else 401Customer tools (user or admin)detect_intentget_menuget_food_item_detailstrack_order (PII removed for user)complete_orderAdmin tools (admin token only)update_order_statusget_recent_ordersget_conversation_logsrefuse per request for user rolegRPCDialogflow ES“SA Food Ordering” agentwebhook off (static replies)new.orderorder.addorder_removeorder.completetrack.orderTLSNeon PostgresAWS us-east-1psycopg 3 pool (max 5)food_itemsordersorder_itemsconversation_logs
    Figure 1. MCP clients reach one remote server over HTTPS. Railway terminates TLS; the server checks Host/Origin, then the Bearer token, then dispatches to customer or admin tools, which call Dialogflow ES and Neon Postgres.

    Components

    • 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.

    How one ordering turn flows1. The user tells the MCP client: 2 bunny chows and a milk tart. 2. The client calls the detect_intent tool on the MCP server. 3. The server calls Dialogflow ES DetectIntent over gRPC. 4. Dialogflow returns intent order.add with the food_Item and number lists. 5. The server writes the turn to conversation_logs in Postgres; a logging failure never fails the turn. 6. The server returns the reply, intent and parameters. 7. The client tells the user the dishes were added. Later, when the user says that is all, the same path detects order.complete. 8. The client calls complete_order with the items. 9. The server opens a transaction and resolves dishes and prices. 10. It inserts the order and its line items and commits. 11. The server returns the order id, lines and total in rand. 12. The client tells the user the order was placed with a total of R200.00.UserMCP client (LLM)MCP serverDialogflow ESNeon Postgres“2 bunny chows and a milk tart”tools/call detect_intent(text)DetectIntent (gRPC)order.add · food_Item[] · number[]INSERT conversation_logs (never fails the turn)reply · intent · parameters“Added. Anything else?”tools/call complete_order(items…)BEGIN · resolve dishes and pricesINSERT orders + order_items · COMMITorder_id · lines · total (ZAR)“Order placed. Total R200.00”“that’s all” → same path, intent order.complete
    Figure 2. One ordering conversation. Every 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_id on 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_order looks 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
    # 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
      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
      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.

    Database schemaTable food_items: id (primary key), name (unique), description, price (non-negative), category, is_available, created_at. Table orders: order_id (primary key), customer_name, customer_phone, total_price (non-negative), order_status (one of in progress, preparing, out for delivery, delivered, cancelled), delivery_address, created_at, updated_at (kept current by a trigger). Table order_items: id (primary key), order_id (foreign key to orders, on delete cascade), item_id (foreign key to food_items, on delete restrict), quantity (above zero), unit_price, total_price, with (order_id, item_id) unique. One order has many order_items, and one food item has many order_items. Table conversation_logs: id, session_id, user_message, bot_response, intent, parameters (jsonb), confidence, created_at; it has no foreign keys and is keyed by session_id.food_itemsid PKserialname UKvarchar(100)descriptiontextpricenumeric(8,2) ≥ 0categoryvarchar(50)is_availablebooleancreated_attimestamptzorder_itemsid PKserialorder_id FKint → ordersitem_id FKint → food_itemsquantityint > 0unit_pricenumeric(8,2) ≥ 0total_pricenumeric(10,2) ≥ 0UNIQUE(order_id, item_id)ordersorder_id PKserialcustomer_namevarchar(120)customer_phonevarchar(25)total_pricenumeric(10,2) ≥ 0order_statusCHECK (5 values)delivery_addresstextcreated_attimestamptzupdated_attrigger-maintainedconversation_logsid PKserialsession_idvarchar(120)user_messagetextbot_responsetextintentvarchar(120)parametersjsonbconfidencerealcreated_attimestamptz1 → manyRESTRICT1 → manyCASCADENo foreign keys: one row per turn, grouped by session_id.Written by detect_intent; read by the admin tool get_conversation_logs.
    Figure 3. Schema from 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
    # 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
    # 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 _OrderAborted inside 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 Decimal from 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:

    1. 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.
    2. Host and Origin allowlist. Unknown hosts get 421 and unknown browser origins 403, before any token work. This blocks DNS-rebinding attacks.
    3. Two Bearer tokens. The header is compared with the user token and the admin token in constant time, always both. No match gets 401.
    4. A role on every request. The middleware stores user or admin on that request only; tools check it each time they run.
    src/diaglogflowmcp/remote_server.py
    # 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
      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
    # 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 denied

    Secrets

    • 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
    // .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. /health is 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.
    operations (bash)
    # 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 --stdin

    09 • 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.

    scripts/dialogflow_agent.py
    # 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.sql before 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
    # .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 .env files 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.

    1. 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.

    2. 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.

    3. 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.

    4. 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.

    5. 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.

    6. 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.

    7. 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.

    8. 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

    terminal
    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:

    .mcp.json
    {
      "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.

    View on GitHub(opens in a new tab)

    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.