Home / Articles

Building Autonomous ColdFusion AI Agents and MCP (Part 5)

ColdFusion AI agents with Gemini tool calling, an MCP server endpoint and AlloyDB secure views for NL2SQL, shown in a brewery ops demo on Google Cloud.

Publisher: REACTAPP.TOP6 min read1358 words

This article is published in English.

Sources: Building Autonomous ColdFusion AI Agents & Model Context Protocol (MCP)

Modernizing ColdFusion on Google Cloud - Part 5 of 5

The earlier articles in this series showed how Adobe ColdFusion apps can use Google Cloud native services:

  • Part 1: move off a managed VM onto Cloud Run, automate builds with Cloud Build and secure access with IAM Workload Identity.
  • Part 2: AlloyDB for PostgreSQL for high-throughput ACID work alongside vector embeddings for semantic search.
  • Part 3: passwordless JDBC to BigQuery and GQL for Customer360-style property graphs.
  • Part 4: Vertex AI AutoML predictions on live batch data (in the brewery demo, fermenting beer).

This installment gives the brewery a "brain": autonomous agents that reason, query live state, evaluate batch risk and expose tools as an MCP server.

Agentic ColdFusion

Early AI features often meant the user typed a prompt, the app sent it to an LLM and the answer came back from training weights alone. That helps with text, but it cannot answer operational questions such as:

  • What are the current temperature and pressure in a specific vat?
  • How much pale malt has been consumed in the last 30 minutes?
  • Can the warehouse cover the Citra hops needed for a fifty-barrel Citra Sunset IPA run?

An agentic workflow separates reasoning from data retrieval. The model acts as an orchestrator: it reads intent, picks tools or queries, inspects the results and synthesizes a fact-based answer.

CF-Brews explores two complementary patterns:

  1. Native ColdFusion tool orchestration and MCP: expose a CFC (BrewMasterTools.cfc) to Gemini for deterministic tool routing and AlloyDB queries.
  2. Secure NL2SQL: translate questions into SQL, then constrain them through AlloyDB Parameterized Secure Views (PSVs).

Native tool calling

Business rules live in a CFC. In api/v1/tools/BrewMasterTools.cfc the main operations are:

  • checkInventory(recipeName, volumeGallons): whether warehouse stock meets the recipe's needs.
  • getRecipeDetails(recipeName): target ABV, temperature thresholds and ingredient ratios.
  • checkBatchRisk(style): inspect active fermenting vats and alert on temperature or pressure drift.

checkInventory joins recipes, ingredients and inventory, scales amounts by volume and reports what is missing:

component {
   /**
    * Determines if there are enough ingredients in stock to brew a specific volume.
    */
   public struct function checkInventory(required string recipeName, numeric volumeGallons = 1) {
       var response = { "can_brew": false, "recipe_found": false, "missing_ingredients": [] };
       var sql = "
           SELECT
               r.recipe_name,
               i.name AS item_name,
               (ri.amount_per_gallon * :volume) AS required_amount,
               i.quantity_on_hand AS current_stock,
               i.unit
           FROM Recipes r
           INNER JOIN RecipeIngredients ri ON r.recipe_id = ri.recipe_id
           INNER JOIN Inventory i ON ri.inventory_item_id = i.item_id
           WHERE LOWER(r.recipe_name) = LOWER(:recipe)
       ";
       var ingredients = queryExecute(sql, {
           recipe = { value = arguments.recipeName, cfsqltype = "cf_sql_varchar" },
           volume = { value = arguments.volumeGallons, cfsqltype = "cf_sql_numeric" }
       });
       if (ingredients.recordCount == 0) {
           response.message = "Recipe '#arguments.recipeName#' not found.";
           return response;
       }
       response.recipe_found = true;
       var canBrew = true;
       var missingList = [];
       for (var row in ingredients) {
           if (row.current_stock < row.required_amount) {
               canBrew = false;
               arrayAppend(missingList, {
                   "item": row.item_name,
                   "required": row.required_amount,
                   "in_stock": row.current_stock,
                   "missing_amount": row.required_amount - row.current_stock,
                   "unit": row.unit
               });
           }
       }
       response.can_brew = canBrew;
       response.missing_ingredients = missingList;
       response.message = canBrew ? "Sufficient inventory available." : "Insufficient stock.";

       return response;
   }
}

Deterministic tool orchestration

ColdFusion's ChatModel() drives a three-step loop with Gemini:

  1. Intent routing: the prompt goes out with system instructions that list the tools. Gemini returns structured JSON if an action is needed.
  2. Execution: ColdFusion parses the JSON and invokes the CFC method against AlloyDB.
  3. Synthesis: tool output goes back into ChatModel() for a grounded natural-language reply.
<cfscript>
    // api/v1/agent/mcp-chat.cfm
    userPrompt = trim(deserializeJson(toString(getHttpRequestData().content)).prompt);

    // 1. Initialize native ChatModel with zero temperature for deterministic routing
    chatModel = ChatModel({
        "provider": "gemini",
        "modelName": "gemini-2.5-flash",
        "apiKey": trim(application.AI_STUDIO_API_KEY),
        "temperature": 0.0
    });

    // 2. Instruct model on available tools
    systemInstruction = 'You are the Brewmaster AI Assistant. Available tools:
1. checkInventory(recipeName, volumeGallons)
2. getRecipeDetails(recipeName)
3. checkBatchRisk(style)

If you need a tool, respond ONLY with JSON: {"tool": "toolName", "arguments": {...}}
Otherwise, answer in plain text.

User question: ' & userPrompt;

    aiReply = chatModel.chat(systemInstruction).message;

    // 3. Detect and execute tool call
    if (left(trim(aiReply), 1) == "{" && right(trim(aiReply), 1) == "}") {
        toolCall = deserializeJson(aiReply);
        tools = new api.v1.tools.BrewMasterTools();

        if (toolCall.tool == "checkInventory") {
            toolResult = tools.checkInventory(toolCall.arguments.recipeName, val(toolCall.arguments.volumeGallons ?: 1));
        } else if (toolCall.tool == "getRecipeDetails") {
            toolResult = tools.getRecipeDetails(toolCall.arguments.recipeName);
        } else if (toolCall.tool == "checkBatchRisk") {
            toolResult = tools.checkBatchRisk(toolCall.arguments.style ?: "");
        }

        // 4. Grounded synthesis
        synthesis = chatModel.chat("Tool '#toolCall.tool#' returned: #serializeJson(toolResult)#. Answer user: #userPrompt#");
        finalText = synthesis.message;
    } else {
        finalText = aiReply;
    }

    writeOutput(serializeJson({ "success": true, "text": finalText }));
</cfscript>

JSON guardrails

Models such as Gemini can constrain sampling to a JSON schema so they cannot emit characters that break the structure. Production code should still treat output as fallible:

  • Wrap deserializeJson() in try/catch.
  • Set temperature to 0.0 for more deterministic tool selection.
  • On deserialization failure or type mismatches, catch the exception and either ask the model to retry or return a clear fallback to the user.

ColdFusion as an MCP server

Model Context Protocol, open-sourced by Anthropic, is the common way to expose data and tools to external AI clients. An MCP client inside an AI app speaks two-way with an MCP server. ColdFusion 2025 Update 8 added MCPServer().

During onApplicationStart in Application.cfc, register a remote wrapper around the tools CFC:

// Application.cfc
public boolean function onApplicationStart() {
    application.cfbrews_dsn = this.datasource;

    // Initialize Native ColdFusion MCP Server
    try {
        var mcpConfig = {
            "serverInfo": { "name": "BrewMaster-Tools", "version": "1.0.0" },
            "capabilities": { "tools": true },
            "tools": [ { "cfc": "api.v1.tools.NativeBrewMasterTools" } ]
        };
        application.mcpServer = MCPServer(mcpConfig);
    } catch (any e) {
        writeLog(file="cfbrews_error", text="MCP Init Error: " & e.message);
    }
    return true;
}

The endpoint api/v1/agent/mcp-server.cfm delegates requests to the runtime:

<cfscript>
    if (structKeyExists(application, "mcpServer")) {
        application.mcpServer.handleRequest();
    } else {
        cfheader(statusCode=503);
        writeOutput(serializeJson({ "error": "MCP Server not initialized" }));
    }
</cfscript>

NL2SQL with PSVs

A second assistant, the Database Operations Assistant at /api/v1/ops/natural-query.cfm, routes generated SQL through Parameterized Secure Views. PSVs blunt prompt-injection in SQL Gemini produces and enforce zero-trust so returned rows are only what the connecting user may see. Under the hood, natural-query.cfm calls AlloyDB's in-database ai.generate() to turn English into a read-only SELECT against those views:

-- Enforcing tenant/scope boundaries at the database layer
CREATE OR REPLACE VIEW brews.secure_vatsensorreadings AS
SELECT r.*
FROM brews.vatsensorreadings r
JOIN brews.vats v ON r.vat_id = v.vat_id
WHERE CURRENT_USER = 'postgres'
   OR v.name IN ('Vat A', 'Vat B');

ColdFusion runs the query against the view, then uses Gemini via ChatModel() to summarize the JSON rows into readable prose.

Why tool calling beats a static chatbot here

A dashboard can show vat temperature. A static chatbot can explain what ABV means. Neither can decide, from a free-form question, that inventory must be checked before a batch starts, run that check against AlloyDB and answer with the missing kilograms of hops. Tool calling gives the model a short list of trustworthy actions and keeps the SQL and business rules inside ColdFusion components you already review and test.

MCP extends that same surface to other clients. Once BrewMasterTools is registered as an MCP server, an external agent can discover the same inventory, recipe and risk tools without a custom integration per client. That is the point of the protocol: one tool surface, many consumers.

Series wrap-up

Across five articles the themes were:

  1. Compute and runtime: Cloud Run for scale-to-zero and fast boots.
  2. Operational database: AlloyDB columnar caching and vector search.
  3. Analytical scale: BigQuery GQL with Simba JDBC and passwordless IAM.
  4. Machine learning: real-time batch failure predictions via Vertex AI.
  5. Agentic workflows: MCP hosting, secure NL2SQL with PSVs and autonomous tool execution.

Source

  • Backend repository
  • Frontend repository