Agent+MCP:开发范式与“最佳”实践

学习链接:https://www.datawhale.cn/learn/content/220/5057

MCP 改变了什么

  • 工具构建过程
    1.将工具逻辑封装为函数
    2.面向智能体构建提示(Prompt)
    • 内容:介绍工具用处,如何使用,以及注意事项

  • MCP
    • 分发逻辑
    • 对现有的工具(地图API,模型服务),提供了新的发布渠道
    • 使用,构建新工具(复杂软件,专业工具)的难度降低
    • 发展速度

Tips:用好mcp有时候需要对query进行改写
在这里插入图片描述

MCP 质量控制

软件开发的SDK不是同样有这些问题吗?
不同点
• 对大模型和智能体,我们有更高的期待
• 自动、自主完成工具的认知、学习和使用,探索并了解工具的边界
• 长期,更少的人为干预
• 伴随 MCP 的兴起,更多复杂的工具出现,加剧了 MCP 质量控制的需求

作业

Tips:

  1. 查看AgentScope 对 MCP的用法:https://doc.agentscope.io/zh_CN/tutorial/task_mcp.html
  2. 查看AgentScope 对工具的用法:https://doc.agentscope.io/zh_CN/tutorial/task_tool.html
    这俩看了基本能使用MCP创建更复杂的工具函数,从而对MCP工具更个性化甚至更精准的使用。
    下面是对比:
    老师课上示例代码:直接让agent调用高德原来的mcp,答案飘到了上海
# -*- coding: utf-8 -*-
"""Example for stateful MCP client."""
import asyncio
import os

from agentscope.agent import ReActAgent, UserAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.mcp import HttpStatelessClient
from agentscope.model import DashScopeChatModel
from agentscope.tool import Toolkit


async def main() -> None:
    """Create a stateful MCP client and use it to chat with the model."""

    # 创建高德 MCP client
    client = HttpStatelessClient(
        name="amap",
        transport="streamable_http",
        url=f"https://mcp.amap.com/mcp?key={os.environ['GAODE_API_KEY']}",
    )

    # 注册工具
    toolkit = Toolkit()
    await toolkit.register_mcp_client(client)

    # 创建智能体
    agent = ReActAgent(
        name="Friday",
        sys_prompt="You are a helpful assistant named Friday.",
        model=DashScopeChatModel(
            model_name="qwen3-max-preview",
            api_key=os.environ["DASHSCOPE_API_KEY"],
        ),
        formatter=DashScopeChatFormatter(),
        toolkit=toolkit,
    )

    # 创建用户输入的代理
    user = UserAgent(name="user")

    # 通过消息的显式传递构建对话逻辑
    msg = None
    while True:
        msg = await agent(msg)
        msg = await user(msg)
        if msg.get_text_content() == "exit":
            break


asyncio.run(main())

# Query:
# - 搜索阿里云谷园区附近的咖啡厅

输出

user: 搜索阿里云谷园区附近的咖啡厅
Friday: {
    "type": "tool_use",
    "id": "call_48333f6981e641219808a8",
    "name": "maps_geo",
    "input": {
        "address": "阿里云谷园区"
    }
}
system: {
    "type": "tool_result",
    "id": "call_48333f6981e641219808a8",
    "name": "maps_geo",
    "output": [
        {
            "type": "text",
            "text": "{\"results\":[{\"country\":\"中国\",\"province\":\"上海市\",\"city\":\"上海市\",\"citycode\":\"021\",\"district\":\"闵行区\",\"street\":[],\"number\":[],\"adcode\":\"310112\",\"location\":\"121.328647,31.197435\",\"level\":\"兴趣点\"}]}"
        }
    ]
}
Friday: {
    "type": "tool_use",
    "id": "call_139434bc46e54b9b91afe2",
    "name": "maps_around_search",
    "input": {
        "keywords": "咖啡厅",
        "location": "121.328647,31.197435",
        "radius": "1000"
    }
}
system: {
    "type": "tool_result",
    "id": "call_139434bc46e54b9b91afe2",
    "name": "maps_around_search",
    "output": [
        {
            "type": "text",
            "text": "{\"pois\":[{\"id\":\"B0GRO76AFB\",\"name\":\"星巴克(上海 虹桥机场T2禁区店)\",\"address\":\"申达一路1号上海虹桥机场2号航站楼出发禁区D40-29店铺\",\"typecode\":\"050501\",\"photo\":\"http://store.is.autonavi.com/showpic/ec3440dbf3d8f9de23da5c7a0cf58ad7\"},{\"id\":\"B0K60U5N4A\",\"name\":\"M Stand(虹桥机场T2航站楼店)\",\"address\":\"申达一路1号虹桥国际机场2号航站楼7号门 往左直走100米\",\"typecode\":\"050500\",\"photo\":\"https://aos-comment.amap.com/B0K60U5N4A/comment/C99DEBAE_9CC4_4A6B_9E09_B689F0DB258B_L0_001_1500_200_1758773067478_03651902.jpg\"},{\"id\":\"B0J0HHVYCT\",\"name\":\"瑞幸咖啡(虹桥机场T2出发层北区店)\",\"address\":\"申达路1号上海虹桥国际机场2号航站楼出发禁区内一层d45-3a室\",\"typecode\":\"050500\",\"photo\":\"https://store.is.autonavi.com/showpic/c287706810a95e84ab635a931ccf264d?operate=original\"},{\"id\":\"B0FFFRMBU6\",\"name\":\"星巴克(上海虹桥机场T2出发店)\",\"address\":\"虹桥机场T2航站 楼出发公众区C6-7\",\"typecode\":\"050501\",\"photo\":\"http://store.is.autonavi.com/showpic/ec3440dbf3d8f9de23da5c7a0cf58ad7\"},{\"id\":\"B00155QN4Z\",\"name\":\"星巴克(虹桥机场T2到达店)\",\"address\":\"虹桥机场T2航站楼到达区1层\",\"typecode\":\"050501\",\"photo\":\"https://aos-comment.amap.com/B00155QN4Z/comment/158ae169758450e505e0309c5684e323_2048_2048_80.jpg\"},{\"id\":\"B0HKVS6R65\",\"name\":\"%Arabica(上海虹桥机场T2店)\",\"address\":\"虹桥路2550号虹桥综合交 通枢纽2F层\",\"typecode\":\"050500\",\"photo\":\"https://aos-comment.amap.com/B0HKVS6R65/comment/3635edb2029fa241fbe7ab8631533161_2048_2048_80.jpg\"},{\"id\":\"B0FFFE8WSD\",\"name\":\"云庭咖啡厅\",\"address\":\"申达三路181号上海中航泊悦酒店2层\",\"typecode\":\"050500\",\"photo\":\"http://store.is.autonavi.com/showpic/96efe4e0d6d3a4bed05af69d1836977d\"},{\"id\":\"B0FFM3NN9V\",\"name\":\"luckin coffee 瑞幸咖啡(上海虹桥国际机场2号航站楼店)\",\"address\":\"虹桥路2550 号虹桥综合交通枢纽M1层\",\"typecode\":\"050500\",\"photo\":\"http://store.is.autonavi.com/showpic/a8f54533e65d9d5fd7b9449e58de1773\"},{\"id\":\"B0KKRZVJ5R\",\"name\":\"nowwa挪瓦咖啡(上海虹桥枢纽美食街店)\",\"address\":\"申昆路1500号( 虹桥2号航站楼地铁站出入口步行350米)\",\"typecode\":\"050500\",\"photo\":\"https://store.is.autonavi.com/showpic/b2ff52345e1e6c9146214811c8365885?operate=original\"},{\"id\":\"B0FFMGIMMR\",\"name\":\"星巴克(虹桥火车站出发区店)\",\"address\":\"虹桥出发层2F-北13F-C4\",\"typecode\":\"050501\",\"photo\":\"http://store.is.autonavi.com/showpic/ec3440dbf3d8f9de23da5c7a0cf58ad7\"},{\"id\":\"B0FFHB4EJ6\",\"name\":\"可趣咖啡(虹桥综合交通枢纽)\",\"address\":\"虹桥路2550号虹桥综合交通枢纽F3层\",\"typecode\":\"050500\",\"photo\":null},{\"id\":\"B0JKF14ITN\",\"name\":\"luckin coffee 瑞幸咖啡(宇培·东朔空间店)\",\"address\":\"宇培幸 福港湾北门东100米\",\"typecode\":\"050500\",\"photo\":\"https://store.is.autonavi.com/showpic/c287706810a95e84ab635a931ccf264d?operate=original\"}]}"       
        }
    ]
}
Friday: 在阿里云谷园区附近,我找到了一些咖啡厅供您选择:

1. **星巴克(上海虹桥机场T2禁区店)**
   - 地址:申达一路1号上海虹桥机场2号航站楼出发禁区D40-29店铺
   ![](http://store.is.autonavi.com/showpic/ec3440dbf3d8f9de23da5c7a0cf58ad7)

2. **M Stand(虹桥机场T2航站楼店)**
   - 地址:申达一路1号虹桥国际机场2号航站楼7号门往左直走100米
   ![](https://aos-comment.amap.com/B0K60U5N4A/comment/C99DEBAE_9CC4_4A6B_9E09_B689F0DB258B_L0_001_1500_200_1758773067478_03651902.jpg)

3. **瑞幸咖啡(虹桥机场T2出发层北区店)**
   - 地址:申达路1号上海虹桥国际机场2号航站楼出发禁区内一层d45-3a室
   ![](https://store.is.autonavi.com/showpic/c287706810a95e84ab635a931ccf264d?operate=original)

4. **星巴克(上海虹桥机场T2出发店)**
   - 地址:虹桥机场T2航站楼出发公众区C6-7
   ![](http://store.is.autonavi.com/showpic/ec3440dbf3d8f9de23da5c7a0cf58ad7)

5. **%Arabica(上海虹桥机场T2店)**
   - 地址:虹桥路2550号虹桥综合交通枢纽2F层
   ![](https://aos-comment.amap.com/B0HKVS6R65/comment/3635edb2029fa241fbe7ab8631533161_2048_2048_80.jpg)

6. **云庭咖啡厅**
   - 地址:申达三路181号上海中航泊悦酒店2层
   ![](http://store.is.autonavi.com/showpic/96efe4e0d6d3a4bed05af69d1836977d)

7. **nowwa挪瓦咖啡(上海虹桥枢纽美食街店)**
   - 地址:申昆路1500号(虹桥2号航站楼地铁站出入口步行350米)
   ![](https://store.is.autonavi.com/showpic/b2ff52345e1e6c9146214811c8365885?operate=original)

以及其他几家咖啡馆。希望这些建议对您有所帮助!如果需要更多信息,请告诉我。

现在用AgentScope提供的函数级别管理改写相当于对maps_text_search 进行了调整,使得输入更详细

# -*- coding: utf-8 -*-
"""Example for stateful MCP client."""
import asyncio
import os
import json
from agentscope.agent import ReActAgent, UserAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.mcp import HttpStatelessClient
from agentscope.model import DashScopeChatModel
from agentscope.tool import ToolResponse, Toolkit, execute_python_code
from agentscope.message import TextBlock


async def main() -> None:
    """Create a stateful MCP client and use it to chat with the model."""

    # 创建高德 MCP client
    client = HttpStatelessClient(
        name="amap",
        transport="streamable_http",
        url=f"https://mcp.amap.com/mcp?key={os.environ.get('GAODE_API_KEY', '')}",
    )

    # 注册工具
    toolkit = Toolkit()
    # await toolkit.register_mcp_client(client)

    async def advance_map_search(keyword: str, city: str) -> ToolResponse:
        """map_search_tool include maps_geo\maps_text_search\maps_around_search

        Args:
            keyword (str):
                关键词,必须详细最好包含地区相关信息
            city (str):
                城市
        """
        maps_text_search = await client.get_callable_function(func_name="maps_text_search", wrap_tool_result=True,)

        res1 = await maps_text_search(
            keywords=keyword,
            city=city
        )

        return ToolResponse(
            content=[
                TextBlock(
                    type="text",
                    text=f"{res1}",
                ),
            ],
        )

    toolkit.register_tool_function(advance_map_search)
    # 创建智能体
    agent = ReActAgent(
        name="Friday",
        sys_prompt="You are a helpful assistant named Friday.",
        model=DashScopeChatModel(
            model_name="qwen-max",
            api_key=os.environ.get("DASHSCOPE_API_KEY", ""),
        ),
        formatter=DashScopeChatFormatter(),
        toolkit=toolkit,
    )

    # 创建用户输入的代理
    user = UserAgent(name="user")

    # 通过消息的显式传递构建对话逻辑
    msg = None
    while True:
        msg = await agent(msg)
        msg = await user(msg)
        if msg.get_text_content() == "exit":
            break


asyncio.run(main())

# Query:
# - 搜索阿里云谷园区附近的咖啡厅

输出

Friday: 您好!请问有什么可以帮助您的?
User Input: 搜索阿里云谷园区附近的咖啡厅
user: 搜索阿里云谷园区附近的咖啡厅
Friday: {
    "type": "tool_use",
    "id": "call_70310295d97e4becac3789",
    "name": "advance_map_search",
    "input": {
        "city": "杭州市",
        "keyword": "阿里云谷园区附近的咖啡厅"
    }
}
system: {
    "type": "tool_result",
    "id": "call_70310295d97e4becac3789",
    "name": "advance_map_search",
    "output": [
        {
            "type": "text",
            "text": "ToolResponse(content=[{'type': 'text', 'text': '{\"suggestion\":{\"keywords\":\"\",\"ciytes\":{\"suggestion\":[]}},\"pois\":[{\"id\":\"B0JDZHJIAF\",\"name\":\"瑞幸咖啡(阿里云谷园区店)\",\"address\":\"灯彩街1008号阿里巴巴云谷园区2号楼一层报告厅大堂\",\"typecode\":\"050500\",\"photo\":\"https://store.is.autonavi.com/showpic/c287706810a95e84ab635a931ccf264d?operate=original\"},{\"id\":\"B0LGMZAJ1F\",\"name\":\"Tims天好咖啡(阿里巴巴云谷园区店)\",\"address\":\"阿里巴巴云谷园区5号楼1层\",\"typecode\":\"050500\",\"photo\":\"http://store.is.autonavi.com/query_pic?id=st1a318338-7770-4717-a3c2-d24271293e86&user=search&operate=original\"},{\"id\":\"B0J1VC8GGI\",\"name\":\"瑞幸咖啡(阿里云谷园区店)\",\"address\":\"灯彩街1008号阿里巴巴云谷园区2号楼一层报告厅大堂\",\"typecode\":\"050500\",\"photo\":\"https://store.is.autonavi.com/showpic/c287706810a95e84ab635a931ccf264d?operate=original\"},{\"id\":\"B0J0YMOWSU\",\"name\":\"库迪咖啡(阿里云谷店)\",\"address\":\"三墩镇灯彩街1008号阿里巴巴云谷园区10号楼1层\",\"typecode\":\"050500\",\"photo\":\"https://store.is.autonavi.com/showpic/7b0db620ddccbe9ff42ce59100617216?operate=original?operate=original?operate=original?operate=original\"},{\"id\":\"B0I3FCOQL4\",\"name\":\"COSTA COFFEE(杭州阿里云总部店)\",\"address\":\"阿里云云谷园区A1楼1层D3号铺\",\"typecode\":\"050500\",\"photo\":\"http://store.is.autonavi.com/showpic/be340612f86f33e11dc224aa548f8a1c\"},{\"id\":\"B0I1UC1IAG\",\"name\":\"Tims天好咖啡(阿里云谷店)\",\"address\":\"三墩镇灯彩街与荆大路交叉口\",\"typecode\":\"050500\",\"photo\":\"http://store.is.autonavi.com/showpic/f1d1625100d62085f914f565bf55ef60\"},{\"id\":\"B0JALUBDY1\",\"name\":\"Manner Coffee(阿里巴巴云谷园区店)\",\"address\":\"阿里巴巴云谷园区1号楼D区1层(霸王茶姬旁)\",\"typecode\":\"050500\",\"photo\":\"http://store.is.autonavi.com/showpic/79b7f6c3f20acaba15aa5d9ecde5b367\"},{\"id\":\"B0I0PNWR81\",\"name\":\"古茗(西湖阿里云谷店)\",\"address\":\"三墩镇灯彩街与荆大线交叉路口阿里云谷园区1号楼地上一层A1-6号商铺\",\"typecode\":\"050700\",\"photo\":\"https://img.alicdn.com/imgextra/i2/O1CN013xzjdi1RsXLRp0pfX_!!6000000002167-2-tps-3333-3333.png\"},{\"id\":\"B0JK1CH0N8\",\"name\":\"赛百味 SUBWAY(阿里巴巴云谷园区店)\",\"address\":\"三墩镇灯彩街1008号云谷园区1号楼2层B-1号商铺\",\"typecode\":\"050300\",\"photo\":\"https://store.is.autonavi.com/showpic/ceffb538cf9b711a5549e39ac1ce6389?operate=original\"},{\"id\":\"B0I125ARCY\",\"name\":\"星巴克(杭州阿里云谷园区9号楼)\",\"address\":\"三墩镇双桥社区张成斗12号云谷园区9号楼地上第一层的1号铺位\",\"typecode\":\"050501\",\"photo\":\"http://store.is.autonavi.com/showpic/9cf637f3ee467f0b127e436d2b463e42\"},{\"id\":\"B0I2K5G0GO\",\"name\":\"星巴克(杭州阿里云谷园区1号楼)\",\"address\":\"三墩镇双桥社区张成斗12号云谷园区1号楼地上第一层的B-1号铺位\",\"typecode\":\"050501\",\"photo\":\"http://store.is.autonavi.com/showpic/9cf637f3ee467f0b127e436d2b463e42\"}]}'}], metadata=None, stream=False, is_last=True, is_interrupted=False, id='2025-09-30 00:40:06.337_eb7e0a')"
        }
    ]
}
}
Friday: 以下是阿里云谷园区附近的一些咖啡厅信息:

1. 瑞幸咖啡(阿里云谷园区店)
   - 地址:灯彩街1008号阿里巴巴云谷园区2号楼一层报告厅大堂
   ![](https://store.is.autonavi.com/showpic/c287706810a95e84ab635a931ccf264d?operate=original)

2. Tims天好咖啡(阿里巴巴云谷园区店)
   - 地址:阿里巴巴云谷园区5号楼1层
   ![](http://store.is.autonavi.com/query_pic?id=st1a318338-7770-4717-a3c2-d24271293e86&user=search&operate=original)

3. 库迪咖啡(阿里云谷店)
   - 地址:三墩镇灯彩街1008号阿里巴巴云谷园区10号楼1层
   ![](https://store.is.autonavi.com/showpic/7b0db620ddccbe9ff42ce59100617216?operate=original?operate=original?operate=original?operate=original)

4. COSTA COFFEE(杭州阿里云总部店)
   - 地址:阿里云云谷园区A1楼1层D3号铺
   ![](http://store.is.autonavi.com/showpic/be340612f86f33e11dc224aa548f8a1c)

5. Manner Coffee(阿里巴巴云谷园区店)
   - 地址:阿里巴巴云谷园区1号楼D区1层(霸王茶姬旁)
   ![](http://store.is.autonavi.com/showpic/79b7f6c3f20acaba15aa5d9ecde5b367)

6. 星巴克(杭州阿里云谷园区9号楼)
   - 地址:三墩镇双桥社区张成斗12号云谷园区9号楼地上第一层的1号铺位
   ![](http://store.is.autonavi.com/showpic/9cf637f3ee467f0b127e436d2b463e42)

您可以根据自己的喜好选择合适的咖啡厅。
User Input: exit
6. 星巴克(杭州阿里云谷园区9号楼)
   - 地址:三墩镇双桥社区张成斗12号云谷园区9号楼地上第一层的1号铺位
   ![](http://store.is.autonavi.com/showpic/9cf637f3ee467f0b127e436d2b463e42)

您可以根据自己的喜好选择合适的咖啡厅。
Logo

更多推荐