首页 / 文章

构建自主型 ColdFusion AI 智能体与 MCP(第5部分)

具备Gemini工具调用功能的ColdFusion AI智能体、MCP服务器端点以及用于NL2SQL的AlloyDB安全视图,已在Google Cloud的啤酒厂运营演示中展示。

发布者:REACTAPP.TOP阅读约 6 分钟1358 词

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

在 Google Cloud 上实现 ColdFusion 的现代化——第 5 部分(共 5 部分)

本系列之前的文章介绍了 Adobe ColdFusion 应用如何利用 Google Cloud 的原生服务:

  • 第 1 部分:从托管虚拟机迁移到 Cloud Run,使用 Cloud Build 实现自动化构建,并通过 IAM Workload Identity 确保访问安全。
  • 第 2 部分:使用 AlloyDB for PostgreSQL 处理高吞吐量的 ACID 类型任务,同时结合向量嵌入技术实现语义搜索。
  • 第 3 部分:通过无密码 JDBC 连接 BigQuery 和 GQL,构建类似 Customer360 的属性图结构。
  • 第 4 部分:利用 Vertex AI AutoML 对实时批量数据(如啤酒酿造过程中的数据)进行预测。

本部分为这家啤酒厂配备了“大脑”:能够进行推理、查询实时状态、评估批次风险,并以 MCP 服务器的形式提供相关工具的自主代理。

代理型 ColdFusion

早期的人工智能功能通常要求用户输入提示语,应用将其发送给大型语言模型,然后仅依靠训练权重返回答案。这种方式适用于处理文本类问题,但无法回答诸如以下操作类问题:

  • 某个特定反应罐当前的温度和压力是多少?
  • 过去30分钟内消耗了多少淡麦芽?
  • 仓库是否有足够的Citra啤酒花来生产50桶的Citra Sunset IPA?

代理式工作流将推理与数据检索分开。模型充当协调者:它理解用户意图,选择相应的工具或查询方式,检查结果后综合出基于事实的答案。

CF-Brews探索了两种互补的模式:

  1. 原生ColdFusion工具协调与MCP:将CFC文件(BrewMasterTools.cfc)提供给Gemini,以实现确定的工具路由和AlloyDB查询。
  • 安全的NL2SQL转换:将问题转换为SQL语句,然后通过AlloyDB的参数化安全视图(PSV)对其进行限制。
  • 原生工具调用

    业务规则存储在CFC中。在api/v1/tools/BrewMasterTools.cfc中,主要操作包括:

    • checkInventory(recipeName, volumeGallons):检查仓库库存是否满足配方需求。
    • getRecipeDetails(recipeName):获取目标酒精浓度、温度阈值以及原料比例。
    • checkBatchRisk(style):监控正在发酵的罐体,一旦温度或压力出现异常即发出警报。

    checkInventory功能会结合配方、原料和库存信息,按体积比例计算所需数量,并报告缺失的物品:

    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;
       }
    }
    

    确定性工具编排

    ColdFusion的ChatModel()驱动与Gemini之间的三步循环:

    1. 意图路由:将提示语连同列出可用工具的系统指令一起发送给Gemini;如果需要执行操作,Gemini会返回结构化的JSON数据。
    2. 执行:ColdFusion解析该JSON数据,并调用针对AlloyDB的CFC方法。
    3. 合成:工具的输出结果会被送回ChatModel(),从而生成基于事实的自然语言回复。
    <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规范限制

    像Gemini这样的模型可以将采样过程约束在JSON模式之下,从而避免生成破坏结构的字符。但实际应用中的代码仍应将输出视为可能出错的数据:

    • 用try/catch结构包裹deserializeJson()函数。
    • 将温度参数设置为0.0,以获得更确定的工具选择结果。
    • 在反序列化失败或类型不匹配时,捕获异常,要么让模型重新尝试,要么向用户返回明确的替代方案。

    ColdFusion作为MCP服务器

    由Anthropic开源的模型上下文协议是向外部AI客户端提供数据和工具的常用方式。AI应用中的MCP客户端会与MCP服务器进行双向通信。ColdFusion 2025更新8版本新增了MCPServer()函数。

    在 Application.cfc 的 onApplicationStart 方法中,为这些工具 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;
    }
    

    端点 api/v1/agent/mcp-server.cfm 会将请求转发给运行时:

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

    结合参数化安全视图的NL2SQL

    另一个辅助工具是位于/api/v1/ops/natural-query.cfm的数据库操作助手,它通过参数化安全视图来处理生成的SQL语句。这些参数化安全视图能够有效防止SQL注入攻击,SQL Gemini在生成结果时遵循零信任原则,确保返回的行数据仅限于连接用户有权查看的内容。在底层,natural-query.cfm会调用AlloyDB数据库内的ai.generate()函数,将英文查询转换为针对这些视图的只读SELECT语句:

    -- 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首先针对视图执行查询,然后通过ChatModel()调用Gemini,将JSON格式的行数据汇总为易于理解的文字。

    为何此处工具调用优于静态聊天机器人

    控制面板可以显示发酵罐的温度,静态聊天机器人可以解释ABV的含义。但二者都无法根据自由输入的问题判断在开始生产批次前是否需要检查库存,也无法连接到AlloyDB进行核查并给出缺失的啤酒花重量。而工具调用能为模型提供一份简短的可靠操作列表,同时将SQL语句和业务规则保留在你已经审核过并测试过的ColdFusion组件中。

    MCP将同一接口扩展至其他客户端。一旦BrewMasterTools注册为MCP服务器,外部代理即可无需针对每个客户端进行定制化集成就能使用相同的库存、配方和风险管理工具。这正是该协议的宗旨:一个工具接口,多个使用方。

    系列总结

    在五篇文章中,主要探讨的主题包括:

    1. 计算与运行时:利用Cloud Run实现零扩展规模及快速启动。
    2. 操作型数据库:AlloyDB的列式缓存与向量搜索功能。
    3. 分析处理能力:BigQuery GQL结合Simba JDBC以及无密码IAM机制。
    4. 机器学习:通过Vertex AI实现实时批量故障预测。
    5. 智能工作流:MCP托管、带PSV的安全NL2SQL转换以及自主工具执行功能。

    参考资料

    • 后端代码库
    • 前端代码库