掘金 人工智能 07月19日 23:08
使用GoHumanLoop提升模型上下文MCP服务人机协同能力
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文详细介绍了如何利用GoHumanLoop库增强MCP(模型上下文协议)服务的人机协同能力。通过结合GoHumanLoop的`require_approval`和`require_info`等装饰器,可以轻松地为MCP服务中的工具方法添加人类审批或信息收集环节,从而确保高风险决策的安全性与准确性。文章通过代码示例展示了如何将GoHumanLoop集成到FastMCP框架中,并提供了使用终端或飞书作为人机交互渠道的实践方法,最后通过LangChain Agent调用这些工具,直观地展示了人机协同工作的流程和效果。

🤖 **MCP与GoHumanLoop的人机协同目标一致**:两者都致力于构建“Human-in-the-loop”(HITL)系统,通过引入人类干预来提升AI系统的安全性、可靠性和可控性。Elicitation通过JSON Schema引导用户输入结构化数据,而GoHumanLoop则提供中断机制,允许AI在关键节点暂停以等待人工审核或补充信息,共同实现闭环人机协作。

🛡️ **双重安全控制机制确保敏感信息保护**:Elicitation内置规则禁止请求敏感数据,并支持响应状态验证(如decline/cancel)。GoHumanLoop进一步强化了安全防护,强制要求所有工具调用都需经过人工审批,并提供标准化的恢复接口,实现了入口拦截和过程管控的双重安全保障,有效防止敏感操作。

🔄 **标准化的人机交互范式与跨平台支持**:Elicitation定义了accept/decline/cancel的三态响应模型,而GoHumanLoop则实现了类似的审批状态管理,并能够跨平台适配(如企业微信、飞书、终端等),支持多轮对话和异步交互。这种标准化的交互协议使得AI Agent在需要人类协助时,能够以清晰、可控的方式进行沟通,提高整体效率。

💻 **GoHumanLoop在MCP服务中的便捷集成**:通过使用`HumanloopAdapter`提供的`require_approval`或`require_info`装饰器,可以非常方便地将GoHumanLoop的功能集成到FastMCP框架的服务中。无论是通过终端进行审批,还是通过飞书等平台获取信息,都能轻松实现,为AI Agent的实际应用提供了极大的灵活性和效率提升。

一. 前言

Hi,大家好,继续我们GoHumanLoop系列,前面介绍如何使用GoHumanLoop将Agent链接到第三方平台流程管理中,如邮箱企业微信飞书等,今天我们介绍一下如何在构建MCP服务时,通过GoHumanLoop提升MCP服务人机协同能力,针对高风险高决策的请求增加人类协同操作,确保整个Agent工作流按照人类预期开展。

这是 GoHumanLoop系列的第六篇文章,之前文章如下:

感兴趣的朋友可以阅读往期文章,进一步了解GoHumanLoop

本期我将给大家介绍MCPGoHumanLoop如何搭配使用,我们上车吧~ 🚗

二. 当前MCP人机交互分析 - Elicitation

人机协同 — Elicitation Flow 是MCP 2025-06-18中新增的功能。模型上下文协议(MCP)为服务器在交互过程中通过客户端请求用户额外信息提供了一种标准化方式。这种流程允许客户端在保持对用户交互和数据共享控制的同时,使服务器能够动态收集必要的信息。 服务器使用JSON模式从用户处请求结构化数据,以验证响应。

    客户端发送工具请求工具(通过 LLM)返回一个 — 询问缺失或不明确的输入 elicitationRequest客户端提示用户并收集其他输入客户端发送包含用户提供信息的请求 continueElicitation工具继续处理新信息并返回最终结果

此工作流程支持实际应用,例如:

Elicitation 需要依赖AI应用实现人机交互,从用户获取信息并返回给MCP服务端,然后服务端继续执行。

为了信任、安全与保障:

    服务器不得使用引诱方式请求敏感信息。

AI应用遵循的标准:

    提供用户界面,明确显示哪个服务器正在请求信息允许用户在发送前查看和修改他们的回复尊重用户隐私,并提供明确的拒绝和取消选项

三. GoHumanLoop 和 Elicitation对别分析

GoHumanLoop:是一个Python库,使AI Agent能够在关键阶段动态请求人类输入(批准/反馈/对话)。

核心功能:

通过连接自主代理和人类判断,确保负责任的AI部署。

两者核心共同点

    人机协同目标
    两者均聚焦于构建"Human-in-the-loop"(HITL)系统,通过人类干预提升AI系统的安全性与可靠性。例如:

      Elicitation允许服务器通过JSON Schema请求用户结构化输入(如邮箱、年龄等)GoHumanLoop提供interrupt机制,在LangGraph等框架中强制AI暂停并等待人工审核

    安全控制机制

      均强调敏感信息保护:Elicitation明确禁止请求敏感数据,GoHumanLoop要求工具调用需经过人工审批响应验证机制:Elicitation支持decline/cancel状态处理,GoHumanLoop提供create_resume_command等标准化接口

    标准化交互范式

      Elicitation定义了accept/decline/cancel三态响应模型GoHumanLoop实现类似的审批状态管理,支持多轮对话和跨平台适配

对比分析

维度Elicitation(MCP协议)GoHumanLoop(Python库)共同目标
1. 协同目标通过 JSON Schema 引导用户输入结构化数据(邮箱、年龄等)通过 interrupt 机制强制暂停AI流程,等待人工介入(如 LangGraph)构建闭环人机协作: • 人类补充关键信息或审核决策 • 确保AI行为可控、结果可靠
2. 安全控制• 禁止请求敏感数据(内置规则) • 支持响应状态验证(decline/cancel)• 强制人工审批所有工具调用 • 提供标准化恢复接口(create_resume_command双重防护敏感操作: • 入口拦截(禁止敏感请求) • 过程管控(人工审批关键动作)
3. 交互范式定义三态响应模型: accept/decline/cancel实现审批状态管理: 支持跨平台适配(邮箱、企业微信、飞书)标准化人机协议: • 明确交互状态机 • 兼容复杂流程(多轮、异步)

如GoHumanLoop可以灵活的针对各类方法、工具等提供异步的人机交互流程,不依赖于客户端APP的人机交互实现。(如上图所示),可以提高整个Agent功能在人机交互上面实现的效率,尤其是需要长时间运行的Agent和依赖审批的高危操作。

四. MCP服务使用GoHumanLoop

在MCP服务上使用GoHumanLoop很简单,只需要使用对应装饰器适配对应工具方法即可,我们采用fastmcp实现一个 MCP服务,如下代码所示

# /// script# requires-python = ">=3.10"# dependencies = [# "gohumanloop>=0.0.12",# "fastmcp>=2.6.0"]# ///from fastmcp import FastMCP, Clientfrom gohumanloop import DefaultHumanLoopManager, HumanloopAdapter, TerminalProvider# 设置环境变量# 创建 GoHumanLoopManager 实例manager = DefaultHumanLoopManager(    TerminalProvider(name="TerminalProvider"))adapter = HumanloopAdapter(    manager=manager,    default_timeout=600,  # 默认超时时间为10分钟)mcp = FastMCP(name="CalculatorServer")@mcp.tool()@adapter.require_approval()async def add(a: int, b: int,) -> int:    """Adds two integer numbers together."""    return a + b@mcp.tool()@adapter.require_approval()async def multiply(a: int, b: int) -> int:    """Multiply two numbers"""    return a * b@mcp.tool(exclude_args=["huamninfo"])@adapter.require_info(ret_key="huamninfo")async def feedback(add_result: int, huamninfo: dict={}) -> str:    """Gets feedback from human response.    Args:        add_result: The result from previous addition operation    Returns:        The human response string    """    print(f"Get Human Response: {huamninfo}")    info = huamninfo["response"]    return infoif __name__ == "__main__":    # This runs the server, defaulting to STDIO transport    mcp.run(transport="streamable-http", port=3000)

通过HumanloopAdapter实现的装饰器require_approval,封装到对应工具方法即可,如addmultiply,以上HumanloopAdapter的请求提供者TerminalProvider是指使用终端作为审批信息输入渠道。

我们再看一个例子

from mcp.server.fastmcp import FastMCPfrom gohumanloop import DefaultHumanLoopManager, HumanloopAdapter, APIProvider,  get_secret_from_envimport os#设置环境变量os.environ["GOHUMANLOOP_API_KEY"] = "46cf87c5-9d08-4027-b72a-f0a91f27298b"# 创建 GoHumanLoopManager 实例manager = DefaultHumanLoopManager(    APIProvider(        name="ApiProvider",        api_base_url="http://127.0.0.1:9800/api", # 换成自己飞书应用的URL        api_key=get_secret_from_env("GOHUMANLOOP_API_KEY"),        default_platform="feishu"    ))# 创建 LangGraphAdapter 实例adapter = HumanloopAdapter(    manager=manager,    default_timeout=600,  # 默认超时时间为10分钟)mcp = FastMCP("Weather")@mcp.tool()@adapter.require_info()async def get_weather(location: str, info_result:dict={}) -> str:    current_date = info_result["response"]    """Get weather for location."""    return f"It's always sunny in {location} on {current_date}"if __name__ == "__main__":    mcp.run(transport="streamable-http")

上面例子HumanloopAdapter采用了APIProvider来进行人机协同,可以将该MCP服务链接到飞书中,可以在飞书中进行操作的信息获取,进而帮助工具完成操作。如上述获取天气信息中,通过info_resuslt获取到用户从飞书中返回的当前日期信息

使用飞书需要对应 API Service,可以参考 github.com/ptonlix/goh… 进行适配使用

我们langchain使用一下以上工具

from langchain_mcp_adapters.client import MultiServerMCPClientfrom langgraph.prebuilt import create_react_agentclient = MultiServerMCPClient(    {        "math": {            "url": "http://localhost:3000/mcp/",            "transport": "streamable_http",        },        "weather": {            # Make sure you start your weather server on port 8000            "url": "http://localhost:8000/mcp/",            "transport": "streamable_http",        }    }<img src=")" alt="" width="50%" />async def main():    tools = await client.get_tools()    agent = create_react_agent("openai:deepseek-chat", tools)    math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})    print(f"Question: what's (3 + 5) x 12? \nMath Response: {math_response['messages'][-1].content}\n")    weather_response = await agent.ainvoke({"messages": "what is the weather in nyc?"})    print(f"Question: what is the weather in nyc?\nWeather Response: {weather_response['messages'][-1].content}\n")if __name__ == "__main__":    import asyncio    asyncio.run(main())

看看实际效果

请求计算问题:

    请求add方法

输入同意,继续进行

    请求multiply方法

输入同意,得出结果

请求天气问题:

    飞书收到获取信息请求

输入当前日期,批准请求

完成Agent工作流,输出信息

五. 总结

以上就是本期介绍如何使用GoHumanLoop提升MCP服务人机协同能力的全部内容了,如果觉得本文对您有帮助的话,别忘了点赞收藏转发, 谢谢~

更多信息欢迎你前往查看相关代码仓库

欢迎您的 Star 🌟🌟🌟~

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

GoHumanLoop MCP 人机协同 AI Agent FastMCP
相关文章