MCP - 优化 Agent 调用 MCP tools提示词(九)

news/2025/10/28 14:02:49/文章来源:https://www.cnblogs.com/rslai/p/19171636

在这篇 MCP - AI智能体调用 MCP Serverr - Streamable HTTP(七) 文章中,虽然可以实现 MCP tools 的调用,但测试下来效果不好。

例如:有如下tools代码,其中提供 3个tools

  1. search_flights_between_countries: 查询两个国家之间的国际航班信息及票价
  2. search_international_multi_city: 国际机票查询服务
  3. search_domestic_multi_city: 中国(国内)机票查询服务
# -*- coding: utf-8 -*-
"""
航班查询
"""
from base.tool_registry import mcp_tool@mcp_tool()
def search_flights_between_countries(departure_country: str="中国", arrival_country: str="美国", departure_date: str="2026/02/10",max_duration: int=0,max_total_price: int=0,sort_by: list[str]=[],limit: int=0
):"""查询两个国家之间的国际航班信息及票价提供指定日期内从出发国家到目的国家的航班搜索服务,返回包含航班详情、价格、时间等信息的结构化数据。支持全球主要国家和城市的航班查询。Args:departure_country (str): 出发国家名称arrival_country (str): 到达国家名称departure_date (str): 出发日期,格式为 YYYY-MM-DDmax_duration (int): 最大飞行时长,单位:小时,默认值为 24小时max_total_price (int): 机票最大总价格,单位:元,默认值为 5000元sort_by (list[str]): 排序规则字段,默认值为 ['total_price', 'duration'] 默认先按总价格排序,再按持续时间排序limit (int): 返回最优的记录条数,默认为20条Returns:str: 机票查询结果"""msg = f"查询两个国家之间的国际航班信息及票价: {departure_country} -> {arrival_country}, 日期: {departure_date}, 时长小于 {max_duration}小时, 总价小于 {max_total_price}元, 排序规则: {sort_by}, 返回: {limit}条"print(f"{msg}")return f"{msg}"@mcp_tool()
def search_international_multi_city(departure_list: list[str]=["北京"],arrival_list: list[str]=["上海"],departure_date: str="2026/02/10",max_duration: int=0,max_total_price: int=0,sort_by: list[str]=[],limit: int=0
):"""国际机票查询服务提供国内多个出发地到多个目的地的组合航班查询,支持单程多城市航线搜索。适用于复杂的国内旅行规划,如多城市环线旅行或不同出发地的团体订票。Args:departure_list (list[str]): 出发城市列表,例如:["北京", "上海"]arrival_list (list[str]): 目的城市列表,例如:["广州", "深圳"]departure_date (str): 出发日期,格式为 YYYY-MM-DDmax_duration (int): 最大飞行时长,单位:小时,默认值为 24小时max_total_price (int): 机票最大总价格,单位:元,默认值为 5000元sort_by (list[str]): 排序规则字段,默认值为 ['total_price', 'duration'] 默认先按总价格排序,再按持续时间排序limit (int): 返回最优的记录条数,默认为20条Returns:str: 机票查询结果"""msg = f"国际机票查询服务: {departure_list} -> {arrival_list}, 日期: {departure_date}, 时长小于 {max_duration}小时, 总价小于 {max_total_price}元, 排序规则: {sort_by}, 返回: {limit}条"print(f"{msg}")return f"{msg}"@mcp_tool()
def search_domestic_multi_city(departure_list: list[str]=["北京"],arrival_list: list[str]=["上海"],departure_date: str="2026/02/10",max_duration: int=0,max_total_price: int=0,sort_by: list[str]=[],limit: int=0
):"""中国(国内)机票查询服务提供国内多个出发地到多个目的地的组合航班查询,支持单程多城市航线搜索。适用于复杂的国内旅行规划,如多城市环线旅行或不同出发地的团体订票。Args:departure_list (list[str]): 出发城市列表,例如:["北京", "上海"]arrival_list (list[str]): 目的城市列表,例如:["广州", "深圳"]departure_date (str): 出发日期,格式为 YYYY-MM-DDmax_duration (int): 最大飞行时长,单位:小时,默认值为 24小时max_total_price (int): 机票最大总价格,单位:元,默认值为 5000元sort_by (list[str]): 排序规则字段,默认值为 ['total_price', 'duration'] 默认先按总价格排序,再按持续时间排序limit (int): 返回最优的记录条数,默认为20条Returns:str: 机票查询结果"""msg = f"中国(国内)机票查询服务: {departure_list} -> {arrival_list}, 日期: {departure_date}, 时长小于 {max_duration}小时, 总价小于 {max_total_price}元, 排序规则: {sort_by}, 返回: {limit}条"print(f"{msg}")return f"{msg}"

在咱们写的Agent中输入 帮我查找 中国 到 美国的 机票,时间 2025/10/01 ,可以看到大模型返回 tool_calls 是空,也就是不调用 MCP tools。

但在 Cherry Studio 中就能看到它可以调用 MCP tools,这是为什么呢?仔细查看后发现 Cherry Studio 使用的提示词跟咱们写的 Agent 不同。

 

问题分析:

一、MCP tools 调用流程

二、自己写的 Agent 智能体的请求

注意:使用抓包前需要修改 .env 配置文件,例如:

其中,url 根据你的情况修改,但注意需要添加 /v1 否则报 404 错误

API_KEY=
BASE_URL=http://172.31.12.15:11434/v1
MODEL=qwen3:4b

使用抓包工具,抓包整理后得到图中右侧部分。可以看到发送了两个请求:

  1. 发送用户输入内容,和 tools 列表
  2. 发送 tools 调用结果 + 1的响应

2.1 第一个请求

2.2 第二个请求

三、cherry studio 的请求

3.1 处理流式传输

由于 cherry studio 配置的是流式传输,所以一个响应拆到了很多包的 content 字段里,抓包后需要手工合并。如下图:

3.2 第一个请求

3.3 第二个请求

3.4 将第一个请求 "role": "system" 中的 "content" 转为文本

可以看出 cherry 的跟自己实现的 agent 提示词不同。

In this environment you have access to a set of tools you can use to answer the user's question. You can use one or more tools per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.## Tool Use FormattingTool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:<tool_use><name>{tool_name}</name><arguments>{json_arguments}</arguments>
</tool_use>The tool name should be the exact name of the tool you are using, and the arguments should be a JSON object containing the parameters required by that tool. For example:
<tool_use><name>python_interpreter</name><arguments>{\"code\": \"5 + 3 + 1294.678\"}</arguments>
</tool_use>The user will respond with the result of the tool use, which should be formatted as follows:<tool_use_result><name>{tool_name}</name><result>{result}</result>
</tool_use_result>The result should be a string, which can represent a file or any other output type. You can use this result as input for the next action.
For example, if the result of the tool use is an image file, you can use it in the next action like this:<tool_use><name>image_transformer</name><arguments>{\"image\": \"image_1.jpg\"}</arguments>
</tool_use>Always adhere to this format for the tool use to ensure proper parsing and execution.## Tool Use ExamplesHere are a few examples using notional tools:
---
User: Generate an image of the oldest person in this document.Assistant: I can use the document_qa tool to find out who the oldest person is in the document.
<tool_use><name>document_qa</name><arguments>{\"document\": \"document.pdf\", \"question\": \"Who is the oldest person mentioned?\"}</arguments>
</tool_use>User: <tool_use_result><name>document_qa</name><result>John Doe, a 55 year old lumberjack living in Newfoundland.</result>
</tool_use_result>Assistant: I can use the image_generator tool to create a portrait of John Doe.
<tool_use><name>image_generator</name><arguments>{\"prompt\": \"A portrait of John Doe, a 55-year-old man living in Canada.\"}</arguments>
</tool_use>User: <tool_use_result><name>image_generator</name><result>image.png</result>
</tool_use_result>Assistant: the image is generated as image.png---
User: \"What is the result of the following operation: 5 + 3 + 1294.678?\"Assistant: I can use the python_interpreter tool to calculate the result of the operation.
<tool_use><name>python_interpreter</name><arguments>{\"code\": \"5 + 3 + 1294.678\"}</arguments>
</tool_use>User: <tool_use_result><name>python_interpreter</name><result>1302.678</result>
</tool_use_result>Assistant: The result of the operation is 1302.678.---
User: \"Which city has the highest population , Guangzhou or Shanghai?\"Assistant: I can use the search tool to find the population of Guangzhou.
<tool_use><name>search</name><arguments>{\"query\": \"Population Guangzhou\"}</arguments>
</tool_use>User: <tool_use_result><name>search</name><result>Guangzhou has a population of 15 million inhabitants as of 2021.</result>
</tool_use_result>Assistant: I can use the search tool to find the population of Shanghai.
<tool_use><name>search</name><arguments>{\"query\": \"Population Shanghai\"}</arguments>
</tool_use>User: <tool_use_result><name>search</name><result>26 million (2019)</result>
</tool_use_result>
Assistant: The population of Shanghai is 26 million, while Guangzhou has a population of 15 million. Therefore, Shanghai has the highest population.## Tool Use Available Tools
Above example were using notional tools that might not exist for you. You only have access to these tools:
<tools><tool><name>server-add_numbers</name><description>Add two numbers together\n\nArgs:\n    a (int): parameter 1\n    b (int): parameter 2\n\nReturns:\n    The sum of individuals</description><arguments>\n    {\"type\":\"object\",\"properties\":{\"a\":{\"title\":\"A\",\"type\":\"integer\"},\"b\":{\"title\":\"B\",\"type\":\"integer\"}},\"required\":[\"a\",\"b\"]}\n  </arguments>
</tool></tools>## Tool Use Rules
Here are the rules you should always follow to solve your task:
1. Always use the right arguments for the tools. Never use variable names as the action arguments, use the value instead.
2. Call a tool only when needed: do not call the search agent if you do not need information, try to solve the task yourself.
3. If no tool call is needed, just answer the question directly.
4. Never re-do a tool call that you previously did with the exact same parameters.
5. For tool use, MARK SURE use XML tag format as shown in the examples above. Do not use any other format.# User InstructionsResponse in user query language.
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000. 

但 cherry 的提示词也不能直接使用,需要再调整才能改善自己写的 agent 工具调用的效果:

  1. cherry 将 tools 列表放在了content;
  2. cherry 提示词中要求工具调用返回的结构不同,如果使用 cherry 提示词需要修改。

四、使用 cherry 提示词

4.1 代码中添加提示词

将以上 3.4 的提示词添加到代码中,然后将 tools 段替换为以下内容 {available_tools} ,添加后如下图:

4.2 添加 available_tools_xml 并修改 messages

代码如下:

        # 获取工具列表 - XML 格式(用在 系统提示词 中)available_tools_xml = [f"\n  <tool>\n    <name>{tool.name}</name>\n    <description>{tool.description}</description>\n    <arguments>{tool.inputSchema}</arguments>\n  </tool>\n"for tool in self.tools]# 待发给 AI 的消息messages = [{"role": "system", "content": system_prompt.replace("{available_tools}", "".join(available_tools_xml))}, {"role": "user", "content": query}]

diff 如下:

4.3 测试结果

修改前

帮我查询 中国 到 澳大利亚 的机票,时间 2026/2/10,并以markdown表格的形式显示出来 ✅
[Calling tool search_flights_between_countries {'departure_country': '中国', 'arrival_country': '澳大利亚', 'departure_date': '2026-02-10'}]帮我查询 北京 到 上海 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ❌ 没有找到工具,直接回复让我去自己搜索帮我查询 北京 到 纽约 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ❌ 没有找到工具,直接回复让我去自己搜索帮我查询 北京、上海 到 纽约、墨尔本 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ❌ 没有找到工具,直接回复让我去自己搜索帮我查询 北京、上海 到 南京 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ✅
[Calling tool search_domestic_multi_city with args {'departure_list': ['北京', '上海'], 'arrival_list': ['南京'], 'departure_date': '2025-10-10', 'limit': 20}]

修改 cherry 提示词后:

帮我查询 中国 到 澳大利亚 的机票,时间 2026/2/10,并以markdown表格的形式显示出来 ✅
[Calling tool search_flights_between_countries {'departure_country': '中国', 'arrival_country': '澳大利亚', 'departure_date': '2026-02-10'}]帮我查询 北京 到 上海 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ✅
[Calling tool search_domestic_multi_city {'departure_list': ['北京'], 'arrival_list': ['上海'], 'departure_date': '2025-10-10', 'limit': 20}]帮我查询 北京 到 纽约 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ❌ 应该调用国际城市查询,但调用国家查询
[Calling tool search_flights_between_countries with args {'departure_country': '中国', 'arrival_country': '美国', 'departure_date': '2025-10-10'}]帮我查询 北京、上海 到 纽约、墨尔本 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ✅
[Calling tool search_international_multi_city {'departure_list': ['北京', '上海'], 'arrival_list': ['纽约', '墨尔本'], 'departure_date': '2025-10-10', 'max_duration': 24, 'max_total_price': 5000, 'sort_by': ['total_price', 'duration'], 'limit': 20}]帮我查询 北京、上海 到 南京 的机票,时间 2025/10/10,并以markdown表格的形式显示出来 ✅
[Calling tool search_domestic_multi_city {'departure_list': ['北京', '上海'], 'arrival_list': ['南京'], 'departure_date': '2025-10-10', 'limit': 20}] 

4.4 问题

以上的处理方法有一个问题,就是传了两份 tools 列表。可以如下图,注释请求中的tools。

但这样返回就会改成如下格式,需要再修改代码处理,这里就不展示了。

<tool_use>
<name>search_flights_between_countries</name> 
<arguments>{"departure_country": "中国","arrival_country": "美国","departure_date": "2025-10-10"
}</arguments>
</tool_use>
 
 

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

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

相关文章

2025年10月精华液推荐产品榜:五款口碑精华深度对比分析

作为护肤品消费中的重要一环,精华液因其高浓度活性成分和针对性功效,成为许多消费者护肤流程中的核心步骤。选择一款合适的精华液,不仅需要考虑个人肤质、护肤诉求,还要综合成分安全性、品牌技术实力与市场口碑等多…

人工智能能力成长金字塔(从通识到前沿)

人工智能能力成长金字塔(从通识到前沿) 这个模型分为六个层级,从底层的基础认知逐步上升到顶层的尖端创新。 Level 1: 认知启蒙层 - AI通识与体验 核心目标: 破除神秘感,理解AI是什么,并能上手使用主流工具。核…

2025年10月祛斑产品推荐:专业评测榜单及用户真实反馈汇总

随着皮肤健康管理意识的提升,祛斑产品已成为护肤市场的重要品类。根据国家食品药品监督管理总局发布的化妆品功效宣称评价规范,祛斑类产品需通过严格的人体功效评价试验。2025年行业数据显示,亚洲消费者对美白淡斑产…

2025年10月精华液推荐产品排行榜:五款热门精华液深度对比分析

随着护肤意识的提升,精华液已成为日常护肤流程中不可或缺的一环。2025年护肤品市场呈现成分透明化与功效精准化趋势,消费者更加关注产品的实际成分、临床验证数据及肤质适配性。国家药监局备案信息显示,美白类精华液…

算法中的 C++ 入门及 STL

算法中的 C++ 入门及 STL C++ 入门 常用头文件头文件 说明与适用场景#include<bits/stdc++.h> 万能头:包含所有常用头文件,算法竞赛中推荐使用(无需逐个引入,节省时间)。缺点:与 using namespace std; 同时…

DevOps平台:数字化转型浪潮中的企业研发效能引擎

DevOps平台:数字化转型浪潮中的企业研发效能引擎 在数字化转型加速推进的今天,DevOps平台正成为企业技术战略中不可或缺的基础设施。随着云原生技术的普及和敏捷开发理念的深入人心,企业对于高效、稳定的软件交付流…

今年口碑好的新加坡留学品牌

摘要 新加坡留学行业近年来持续增长,得益于其优质的教育资源和国际化的环境,吸引大量国际学生。随着2025年教育政策的优化,留学品牌竞争加剧,选择可靠的服务商成为关键。本文基于行业数据和用户口碑,整理出2025年…

MCP - AI智能体调用 MCP Serverr - Streamable HTTP(七)

前文展示的是 AI 智能体调用 stdio 的 MCP Server,这里展示调用 Streamable HTTP的 MCP Server。 一、在 test 目录中添加 agent_http.py 文件 并添加如下代码:import asyncio import os from openai import OpenAI …

2025年唐卡装饰权威深度解析:家装业新格局与品质承诺

本文将从企业发展与行业地位这一核心维度出发,为读者提供一个有针对性的客观参考。唐卡装饰作为家装行业的代表性企业,其成长路径与市场定位对理解行业格局具有重要参考价值。 重庆唐卡装饰2009年成立,历时16年得到…

MCP - Cherry Studio调用 MCP Serverr - Streamable HTTP(八)

当然,类似 Cherry Studio、TRAE 等工具,也可以使用咱们写的 MCP Server 中的 tools。 1、下载、安装 Cherry Studio 自行下载安装 Cherry Studio 2、在 Cherry Studio 配置 2.1 设置 -> 添加2.2 设置 MCP Server …

git 回滚具体某个Id版本

1、git reset --hard 具体Id具体Id如: 2、创建一个分支 3、$ git push -f origin 具体分支

2025年市面上氟碳铝单板品牌、市面上氟碳铝单板公司、口碑好的氟碳铝单板产品、可靠的氟碳铝单板品牌、热门的氟碳铝单板公司综合排名

文章摘要 氟碳铝单板行业在2025年持续蓬勃发展,得益于建筑装饰市场对高性能材料的需求增长,市面上品牌竞争激烈。本文基于行业数据、用户评价和综合实力,整理出氟碳铝单板品牌排行榜前十名,涵盖品牌、公司、产品及…

MCP - AI智能体调用 MCP Serverr - Stdio(六)

之前展示的都是手写一个 client,然后手工调用 MCP tools。没有使用到任何大模型,下文将展示如何通过大模型调用 MCP tools。 同样调用 MCP Server 有两种方式:第一,stdio。第二,Streamable HTTP。后文展示的是通过…

2025年唐卡装饰权威深度解析:规模化自营体系如何重塑家装行业信任基础

本文将从资源体系与供应链能力这一核心维度出发,为读者剖析唐卡装饰在规模化运营背景下的核心竞争力与潜在挑战,提供一个有针对性的客观参考。家装市场普遍存在价格不透明、质量参差不齐、服务链条断裂等行业痛点,消…

2025年唐卡装饰权威深度解析:家装行业格局与品质承诺

本文将从企业资源体系与供应链能力这一核心维度出发,为读者提供一个有针对性的客观参考。家装行业历来因供应链冗长、品控难度大而饱受诟病,唐卡装饰通过构建自营资源体系,试图在规模化运营中实现质量可控与效率提升…

国产项目管理工具崛起:Gitee如何以本土化优势赋能中国企业数字化转型

国产项目管理工具崛起:Gitee如何以本土化优势赋能中国企业数字化转型 在全球数字化转型浪潮席卷各行各业的当下,项目管理工具已成为企业提升运营效率的关键基础设施。在这一领域,中国科技企业的快速发展正推动着本土…

MCP - 使用 fastmcp 编写 Client 调用 MCP Serverr - Stdio(五)

在 MCP - 使用 fastmcp 编写 Client 调用 MCP Serverr - Streamable HTTP (三) 中讲解了如何写 MCP Serverr - Streamable HTTP 的 Client 。 下文将介绍如何写 MCP Serverr - Stdio 的 Client 。 1、server.py 文件…

C#基础06-函数异常 - 指南

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …