使用agentscope访问注册在nacos的A2Aagent和MCP服务

news/2026/1/20 1:39:29/文章来源:https://www.cnblogs.com/peacemaple/p/19504216

参考资料

  • https://doc.agentscope.io/zh_CN/tutorial/task_a2a.html

  • https://strandsagents.com/latest/documentation/docs/user-guide/concepts/multi-agent/agent-to-agent/

部署litellm代理平台

为了便于测试和控制在本地部署一个litellm代理bedrock平台,配置如下

  • postgres数据库配之后可以开启litellm的UI管理界面,并通过虚拟key的方式管理用户
  • UI界面可以进行模型注册,观察token消耗,注册MCP和A2A等
services:litellm:image: 000000000000.dkr.ecr.cn-north-1.amazonaws.com.cn/litellm:v1.80.11.rc.1container_name: litellmports:- "4000:4000"environment:- DATABASE_URL=postgresql://litellm:ncxzGlA=@postgres:5432/litellm- LITELLM_MASTER_KEY=OFgmU5MB1zxrhZyq1gVDCyguU=- STORE_MODEL_IN_DB=True- LITELLM_DROP_PARAMS=Truedepends_on:- postgresrestart: alwayspostgres:image: 000000000000.dkr.ecr.cn-north-1.amazonaws.com.cn/postgres:13container_name: litellm-postgresports:- "5432:5432"environment:- POSTGRES_DB=litellm- POSTGRES_USER=litellm- POSTGRES_PASSWORD=ncuV7j7v1RSxSI7XG1G5xzGlA=- PGDATA=/var/lib/postgresql/data/pgdatavolumes:- postgres-data:/var/lib/postgresql/datarestart: alwaysvolumes:postgres-data:driver: local

部署完成图示

image-20260119225424291

strands实现A2A服务

Agent-to-Agent 协议是一个开放标准,定义了 AI 代理如何发现、通信和协作。Strands Agents 支持 Agent-to-Agent (A2A) 协议。实现一个简单的A2A服务如下

from strands import Agent
from strands.multiagent.a2a import A2AServer
from strands.models.litellm import LiteLLMModel
from strands import toollitemodel= LiteLLMModel(model_id="qwen3-vl",client_args={"api_key": "sk-uzpq0u0n5FN14HorW45hUw","base_url": "http://localhost:4000","use_litellm_proxy": True},
)@tool(name="get_weather",description="Retrieves weather forecast for a specified location",
)
def weather_forecast(city: str, days: int = 3) -> str:"""Get weather forecast for a city.Args:city: The name of the citydays: Number of days for the forecast"""return f"Weather forecast for {city} for the next {days} days..."# Create a Strands agent
strands_agent = Agent(model=litemodel,name="Weather Agent",description="A weather agent that can retrieve weather forecasts.",tools=[weather_forecast],callback_handler=None,
)# Create A2A server (streaming enabled by default)
a2a_server = A2AServer(agent=strands_agent)
a2a_server.serve(host="0.0.0.0", port=9000)

客户端首先会检查/.well-known/agent-card.json查看agent的skill

{"capabilities": {"streaming": true},"defaultInputModes": ["text"],"defaultOutputModes": ["text"],"description": "A weather agent that can retrieve weather forecasts.","name": "Weather Agent","preferredTransport": "JSONRPC","protocolVersion": "0.3.0","skills": [{"description": "Retrieves weather forecast for a specified location","id": "get_weather","name": "get_weather","tags": []}],"url": "http://127.0.0.1:9000/","version": "0.0.1"
}

然后实际上通过如下方法访问代理。A2A 协议支持的 JSON-RPC 关键的方法有:

  • message/send - 发送消息
  • message/stream - 流式发送消息
  • tasks/get - 获取任务
  • tasks/cancel - 取消任务
  • 其他
curl -X POST http://127.0.0.1:9000/ \-H "Content-Type: application/json" \-d '{"jsonrpc": "2.0","method": "message/send","params": {"message": {"kind": "message","message_id": "msg-001","role": "user","parts": [{"kind": "text","text": "What is the weather in Beijing?"}]}},"id": 1}'

运行nacos并注册A2A服务

  • https://nacos.io/docs/latest/quickstart/quick-start/

Nacos 是一款开源的动态服务发现、配置管理和服务管理平台,在 3.1.0 版本中引入了 Agent 注册中心功能,支持 A2A 智能体的分布式注册、发现和版本管理。

使用如下配置部署nacos

services:nacos:image: 000000000000.dkr.ecr.cn-north-1.amazonaws.com.cn/nacos-server:v3.1.1container_name: nacos-standaloneenvironment:- MODE=standalone- PREFER_HOST_MODE=hostname- NACOS_AUTH_IDENTITY_KEY=serverIdentity- NACOS_AUTH_IDENTITY_VALUE=security- NACOS_AUTH_TOKEN=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg= # 服务端使用此 Token 来验证客户端的身份ports:- "8080:8080" # Nacos 的控制台端口- "8848:8848" # Nacos 的主服务端口,用于服务注册、发现和配置管理的 API 调用- "9848:9848" # Nacos 客户端和服务端之间的 gRPC 通信(服务注册和发现的 RPC 通信)volumes:- nacos-data:/home/nacos/datarestart: unless-stoppedvolumes:nacos-data:

可见新版本的功能如下

image-20260119234634077

Nacos中的Agent (AgentCard) 匹配A2A协议中的AgentCard定义。在Nacos中,一个Agent(AgentCard)仅能处于一个命名空间下,通过不同的命名空间进行资源隔离。

实现自动注册MCP服务

使用Nacos MCP Wrapper Python自动注册mcp示例如下

from mcp.server.fastmcp import FastMCP
from datetime import datetime
from nacos_mcp_wrapper.server.nacos_mcp import NacosMCP
from nacos_mcp_wrapper.server.nacos_settings import NacosSettingsnacos_settings = NacosSettings()
nacos_settings.SERVER_ADDR = "default.test.com:8848"
nacos_settings.NAMESPACE = "public"  # Nacos 命名空间ID
nacos_settings.USERNAME = "nacos" 
nacos_settings.PASSWORD = "nacos"mcp = NacosMCP("time-server", nacos_settings=nacos_settings, version="1.0.1", stateless_http=True, host="0.0.0.0", port=18001)@mcp.tool()
def get_time():"""获取当前时间"""current_time = datetime.now().strftime("%H:%M:%S")return {"time": current_time}@mcp.tool()
def get_date():"""获取当前日期"""current_date = datetime.now().strftime("%Y-%m-%d")return {"date": current_date}if __name__ == "__main__":mcp.run(transport="streamable-http")

启动的时候报错显示找不到从而注册,正常现象最终能够注册成功

image-20260120002319663

通过http请求获取agent详情如下

curl -X GET '127.0.0.1:8848/nacos/v3/admin/ai/a2a?namespaceId=public&agentName=weather-agent'{"code":0,"message":"success","data":{"protocolVersion":"0.2.9","name":"weather-agent","description":"Retrieves weather forecast for a specified location","version":"1.0.0","iconUrl":null,"capabilities":{"streaming":false,"pushNotifications":false,"stateTransitionHistory":false,"extensions":null},"skills":[{"id":null,"name":"weather_forecast","description":"A weather agent that can retrieve weather forecasts.","tags":null,"examples":null,"inputModes":null,"outputModes":null}],"url":"http://default.test.com:9000/","preferredTransport":"JSONRPC","additionalInterfaces":null,"provider":null,"documentationUrl":null,"securitySchemes":null,"security":null,"defaultInputModes":["text"],"defaultOutputModes":["text"],"supportsAuthenticatedExtendedCard":null,"registrationType":"URL","latestVersion":true}}

agentscope使用在nacos注册的服务

使用

from a2a.types import AgentCard
from v2.nacos import ClientConfigfrom agentscope.a2a import NacosAgentCardResolver
from agentscope.agent import A2AAgent, UserAgent
from agentscope.message import Msg, TextBlock
from agentscope.tool import ToolResponseasync def main() -> None:# 1. 从 Nacos 获取 Agent Cardagent_card = await NacosAgentCardResolver(remote_agent_name="weather-agent",nacos_client_config=ClientConfig(server_addresses="http://localhost:8848",),).get_agent_card()print(f"获取到 Agent Card: {agent_card.name}")# 2. 创建 A2A 代理agent = A2AAgent(agent_card=agent_card)# 3. 访问 A2A 代理msg = Msg(name="user",content="what is the weather in beijing?",role="user",)res = await agent(msg)print(res.content)if __name__ == "__main__":import asyncioasyncio.run(main())

调用结果

image-20260120005359870

使用agentcsope router反代mcp服务

Nacos MCP Router 有两种工作模式:

  1. router模式:默认模式,通过MCP Server推荐、安装及代理其他MCP Server的功能,帮助用户更方便的使用MCP Server服务。
  2. prroxy模式:使用环境变量MODE=proxy指定,通过简单配置可以把sse、stdio协议MCP Server转换为streamableHTTP协议MCP Server。

此处使用router模式,Nacos MCP Router 作为一个标准MCP Server,提供MCP Server推荐、分发、安装及代理其他MCP Server的功能。

export NACOS_ADDR=127.0.0.1:8848
export NACOS_USERNAME=nacos
export NACOS_PASSWORD=nacos
export TRANSPORT_TYPE=streamable_http
uvx nacos-mcp-router@latest

将MCP Router注册为agent的tool

from mcp.client.streamable_http import streamable_http_client
from strands import Agent
from strands.tools.mcp import MCPClient
from strands.models.litellm import LiteLLMModel
import logginglogging.basicConfig(level=logging.INFO)
streamable_http_mcp_client = MCPClient(lambda: streamable_http_client("http://localhost:8000/mcp")
)litemodel= LiteLLMModel(model_id="qwen3-vl",client_args={"api_key": "sk-uzpq0u0n5FN14HorW45hUw","base_url": "http://localhost:4000","use_litellm_proxy": True},
)strands_agent = Agent(model=litemodel,name="Personal Assistant",description="A personal assistant for the user.",tools=[streamable_http_mcp_client],callback_handler=None,
)resp = strands_agent("What can you do?")
print(resp)

可以查看mcp支持的功能

image-20260120012632908

实际调用,这个提示词要比较有针对性,否则可能找不到nacos中的mcp服务

from mcp.client.streamable_http import streamable_http_client
from strands import Agent
from strands.tools.mcp import MCPClient
from strands.models.litellm import LiteLLMModel
import logginglogging.basicConfig(level=logging.INFO)
streamable_http_mcp_client = MCPClient(lambda: streamable_http_client("http://localhost:8000/mcp")
)litemodel= LiteLLMModel(model_id="qwen3-vl",client_args={"api_key": "sk-uzpq0u0n5FN14HorW45hUw","base_url": "http://localhost:4000","use_litellm_proxy": True},
)strands_agent = Agent(model=litemodel,name="Personal Assistant",description="A personal assistant for the user.",tools=[streamable_http_mcp_client],callback_handler=None,
)resp = strands_agent("Please tell me the time using time-server.")
print(resp)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1186132.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Keil5 Debug怎么使用?通俗解释核心要点功能

Keil5 Debug怎么用?手把手带你玩转嵌入式调试核心技能你有没有过这样的经历:代码烧进STM32,板子一上电,程序却“卡死”了——LED不闪、串口没输出,连个报错都没有。你只能靠猜:“是不是中断没进来&#xff…

SGLang一键部署方案:免环境配置快速启动教程

SGLang一键部署方案:免环境配置快速启动教程 SGLang-v0.5.6 是当前稳定版本,具备完整的推理优化能力与结构化生成支持。本文将围绕该版本,详细介绍如何通过一键部署方式快速启动 SGLang 服务,无需繁琐的环境配置,帮助…

从安装到运行,YOLO11全流程实操记录

从安装到运行,YOLO11全流程实操记录 1. 引言:为什么选择YOLO11? 随着计算机视觉技术的快速发展,实时目标检测在自动驾驶、工业质检、安防监控等场景中扮演着越来越重要的角色。Ultralytics推出的YOLO11作为YOLO系列的最新迭代版…

Hunyuan部署卡在加载?safetensors权重优化教程

Hunyuan部署卡在加载?safetensors权重优化教程 1. 背景与问题定位 在实际部署 Tencent-Hunyuan/HY-MT1.5-1.8B 翻译模型时,许多开发者反馈:模型加载过程卡顿、内存占用过高、启动时间过长,甚至出现 OOM(Out of Memor…

Rembg批量抠图技巧:200张图云端3小时搞定

Rembg批量抠图技巧:200张图云端3小时搞定 你是不是也遇到过这样的情况?换季了,网店要更新商品图,上百张产品照等着换背景。找外包吧,报价高得吓人;自己用PS一张张抠,头发丝、蕾丝边、透明材质全…

零基础入门:Paraformer-large语音识别模型快速上手步骤详解

零基础入门:Paraformer-large语音识别模型快速上手步骤详解 1. 引言 随着语音技术的快速发展,自动语音识别(ASR)已广泛应用于会议记录、客服系统、内容创作等场景。然而,许多开发者在实际落地时面临环境配置复杂、模…

通义千问3-14B省钱部署方案:单卡双模式,GPU按需使用

通义千问3-14B省钱部署方案:单卡双模式,GPU按需使用 1. 引言:为何选择 Qwen3-14B? 在当前大模型推理成本高企的背景下,如何以最低硬件投入获得接近 30B 级别性能的推理能力,成为中小型团队和独立开发者的…

音频音量过小影响识别?Speech Seaco Paraformer前置放大方案

音频音量过小影响识别?Speech Seaco Paraformer前置放大方案 1. 问题背景与技术挑战 在使用语音识别系统时,音频输入质量直接影响最终的识别准确率。尽管 Speech Seaco Paraformer 模型基于阿里 FunASR 构建,在中文语音识别任务中表现出色&…

阿里通义轻量模型:CosyVoice-300M Lite技术详解

阿里通义轻量模型:CosyVoice-300M Lite技术详解 1. 引言 1.1 背景与挑战 随着语音合成(Text-to-Speech, TTS)技术在智能客服、有声阅读、虚拟助手等场景的广泛应用,对模型部署效率和资源消耗的要求日益提高。传统TTS模型往往依…

门电路基础入门必看:数字逻辑的起点详解

门电路:数字世界的“原子”——从零开始读懂硬件逻辑你有没有想过,为什么按下键盘的一个键,屏幕上就能显示出一个字母?或者,手机里的处理器是如何在一瞬间完成数百万次计算的?答案藏在一个看似简单却无比强…

Qwen3-Reranker-0.6B实战案例:云端10分钟上手,2块钱低成本验证

Qwen3-Reranker-0.6B实战案例:云端10分钟上手,2块钱低成本验证 你是不是也遇到过这样的情况?作为产品经理,看到竞品在搜索结果排序、推荐系统或问答匹配上用了“重排序”技术,用户体验明显提升,心里也开始…

serialport数据封装与解析方法:操作指南与代码示例

串口通信实战:如何优雅地封装与解析数据帧?在嵌入式开发的世界里,serialport(串口)是最古老却也最可靠的通信方式之一。无论是调试日志输出、传感器读取,还是工业PLC控制,你几乎绕不开它。但你有…

通义千问2.5实战指南:从单机部署到集群扩展详解

通义千问2.5实战指南:从单机部署到集群扩展详解 1. 引言 随着大语言模型在自然语言理解、代码生成和结构化数据处理等领域的广泛应用,高效部署与可扩展性成为工程落地的关键挑战。Qwen2.5 系列作为通义千问最新一代模型,覆盖从 0.5B 到 720…

轻量级BERT模型应用:移动端部署实战

轻量级BERT模型应用:移动端部署实战 1. 引言 随着自然语言处理技术的不断演进,BERT(Bidirectional Encoder Representations from Transformers)已成为语义理解任务的核心架构之一。然而,原始BERT模型通常参数庞大、…

OrCAD Capture集成Pspice安装操作指南

从零构建电路仿真环境:OrCAD Capture集成Pspice实战指南 你有没有遇到过这种情况?花了一个小时画好了一个精密的LDO原理图,信心满满地点开“仿真”按钮——结果弹出一条红色警告:“Pspice not available” 或者 “License checko…

OpenCV DNN模型实战对比:AI读脸术与PyTorch方案效率评测

OpenCV DNN模型实战对比:AI读脸术与PyTorch方案效率评测 1. 技术背景与选型动因 在计算机视觉领域,人脸属性分析是一项兼具实用性和挑战性的任务。随着边缘计算和轻量化部署需求的增长,如何在资源受限的环境中实现高效、准确的性别与年龄识…

HunyuanVideo-Foley恐怖氛围:阴森背景音与突发惊吓音效设计

HunyuanVideo-Foley恐怖氛围:阴森背景音与突发惊吓音效设计 1. 技术背景与应用场景 随着AI生成技术在多媒体领域的深入发展,音效自动生成正成为视频制作流程中不可或缺的一环。传统音效设计依赖专业音频工程师手动匹配动作与声音,耗时且成本…

一键智能抠图系统搭建:cv_unet_image-matting环境部署完整指南

一键智能抠图系统搭建:cv_unet_image-matting环境部署完整指南 1. 引言 随着AI图像处理技术的快速发展,自动化图像抠图已成为设计、电商、摄影等领域的刚需。传统手动抠图效率低、成本高,而基于深度学习的智能抠图方案能够实现“一键去背景…

RS422在工业通信中的全双工应用实战案例

RS422为何能在工业通信中“稳坐C位”?一个智能仓储案例讲透全双工实战精髓 在某大型物流中心的深夜运维现场,工程师小李盯着监控屏上跳动的数据流松了口气——过去频繁报警的输送线通信故障,自打换上RS422方案后,已经连续运行37天…

Kibana环境下Elasticsearch基础操作完整指南

从零开始玩转 Elasticsearch:Kibana 环境下的实战操作全解析 你有没有遇到过这样的场景?系统突然报错,日志文件铺天盖地,翻了十分钟还没找到关键线索;或者业务方问“最近三天订单失败率是不是上升了”,你只…