github.com/ludayuan/Lu… 鲁大猿的视频知识库
Agent 工具调用:从工具声明到执行反馈
适用范围:应用使用 OpenAI Responses 的自定义 function 工具,并自行通过 MCP 客户端连接工具服务。MCP 字段参照 2025-06-18 规范。以下是单次调用的教学推演,不是实时抓包;平台托管工具和其他模型接口可能采用不同封装。
核心问题:模型给出工具名称和参数之后,程序怎样执行,并让模型利用结果回答用户?
模型产生结构化调用要求;应用解析、路由并组织执行;工具服务检查输入和访问条件,产生结果;应用把对应反馈加入后续模型输入,模型再生成答复。理解它需要始终区分三个对象:工具规则、本次参数值、执行产生的结果。
1. 先确定要完成什么
用一个文件读取接口跟踪技术过程。任务中的已知输入是逻辑路径 /workspace/notes.txt,希望取得文件开头 20 行。假设服务已注册 read_text_file,且应用已建立可用连接。这些都是教学条件,不表示读者电脑上存在该路径。
成功需要同时满足三件事:服务确实取得允许读取的文本;执行反馈对应回原来的模型调用;模型获得反馈后组织答复,应用把它呈现给用户。仅生成一个看起来正确的 JSON,尚未满足其中任何一个执行条件。
2. 为什么还需要应用和协议
模型接口返回的名称和参数首先是一份数据。要读文件,还需要知道哪个实现接收它、输入是否有效、路径是否允许访问,以及调用失败时怎样返回错误。
最直接的实现是应用直接调用本地函数,或调用封装外部 API 的代码。若工具由独立服务提供,应用和服务还需要共同约定发现、调用和响应的格式;MCP 承担这一段通信。它不替代模型生成调用要求的机制,也不等于读取文件的代码。
直接接入、MCP 接入、平台内置是理解接入方式的几个入口,彼此并非互斥且穷尽的分类;同一种能力可以通过不同方式提供。
3. 用相同的值走完最小推演
把 head 从 20 改成 5,会改变请求值及期望读取范围;不会把参数规则中的 number 改成 5。如果只是把 JSON 文本解析成对象,却没有调用处理函数,读取次数仍然为零。
4. 谁负责什么
图 4-1|应用连接模型与工具服务。 MCP 客户端在应用内。模型接口与服务的消息分别由应用处理;图中的往返关系不表示请求一出现就获得了访问权限。
开发者负责关联工具说明和执行函数。模型参考任务和说明生成选择及参数。应用或 SDK 负责解析封装、记录来源、关联请求和反馈。服务检查实际输入与运行权限并执行;最终用户答复由模型生成、应用呈现。
5. 一次完整调用的先后顺序
图 5-1|单次工具调用的闭环。 为解释主体路径省略并行调用、连接初始化和传输细节。继续调用不是无限循环的保证;实际应用还需要自己的完成、失败或中止条件。
协议层错误与工具执行错误要区分。前者可使用协议错误响应;后者可以在工具结果中通过 isError 表达。不能把失败反馈转换为“已经读取成功”。
6. 看清字段和它们所属的对象
工具声明是规则
MCP 的 name 标识工具,description 描述用途,inputSchema 约束输入。规则中的 properties 列出属性,type 规定类型,required 列出必填属性。
本例工具的 path 是字符串,head 是可选的数字参数;完整参考接口还支持可选的 tail,且 head 与 tail 不能同时使用。本例只跟踪前两个字段。
应用适配到 Responses 时,在 tools 中放入 type: "function"、名称、用途和 parameters。这里的 parameters 仍然是规则。接口支持的 JSON Schema 范围及严格模式要求需要兼容处理,不能对所有服务的 schema 盲目复制。
type: "function" 描述工具类别,规则内的 type: "string" 描述参数类型;它们位于不同层级。tool_choice: "required" 要求模型调用工具,而 schema 的 required: ["path"] 要求调用输入包含路径,也不是同一个约束。
模型生成的是新的调用数据
以下片段表示 Responses 调用项的关键字段:
{
"type": "function_call",
"name": "fs__read_text_file",
"arguments": "{"path":"/workspace/notes.txt","head":20}",
"call_id": "call_demo_1"
}
arguments 在这里是 JSON 文本。应用先解析它,才能按 path 和 head 取值。fs__ 是此教学应用选择的别名前缀,用于区分不同服务的入口;MCP 不规定所有工具必须使用这个前缀。应用使用已有映射找到文件服务与原始名称 read_text_file。
具体参数值必须有任务或已有信息作为依据。规则说明“路径是字符串”,不会自动提供模型尚不知道的路径。必要信息缺失时应补充获取或询问;这是一项正确处理要求,不是模型永不猜错的保证。
MCP 请求把参数对象送给服务
{
"jsonrpc": "2.0",
"id": "rpc_demo_41",
"method": "tools/call",
"params": {
"name": "read_text_file",
"arguments": {"path": "/workspace/notes.txt", "head": 20}
}
}
params 是请求参数容器,里面的 arguments 才是工具输入对象。路径与行数没有改变。服务根据名称找到处理函数,验证输入、检查访问范围,然后读取。
模型的 call_id 与 MCP 的 id 属于两个关联域。应用要保留“哪次模型调用对应哪次服务请求”的关系;可以通过任务对象或 SDK 调用上下文管理,不要求一定建立全局映射表,更不要求编号取相同字符串。
执行结果是新增数据
MCP 响应带对应的 id,结果可放在 result.content,也可提供 structuredContent。应用取得反馈后,整理模型可接收的形式:
{
"type": "function_call_output",
"call_id": "call_demo_1",
"output": "此处是实际读取到的文本,或明确的错误说明"
}
这段文本是内容位置的示意,不是执行实测输出。结果封装不重新运行工具。应用把工具结果及相应调用记录加入后续输入,保留用户任务和必要上下文;模型这时才拿到执行证据。
放回完整 Responses 请求与响应里看
“完整”指本例选用的完整 JSON 消息体,附件没有省略号;它不表示列出了 API 的所有可选字段,也不包含 HTTP 头、流式事件或连接初始化。全部消息为教学构造,编号、created_at: 0 和文本占位都不是实测;usage: null 表示未提供计量数据。
沿同一次任务,模型接口侧有四份报文:
第一次请求发往 POST /v1/responses。model 选择模型;本例用支持 Responses 与 function calling 的 gpt-4.1 说明结构,不要求所有应用都选它。input 和 tools 是同一级数组:前者携带任务与已有信息,后者列出可供选择的能力。tool_choice 也是根字段,用来控制选择方式,不放在 parameters 内,也不作为参数传给文件函数。
沿 tools → 第一个元素 → parameters → properties → path → type 向下读,才会找到 "string"。它表示路径的类型规则;实际路径是在另一份消息中的 arguments 里出现的。strict: false 明确本例未启用严格模式;描述中的互斥要求和输入规则仍需要程序执行检查,不能因为写了 schema 就推断模型输出一定有效。
第一次响应外层有 id、object、created_at、status、model、output 等字段。output 是数组,本例唯一一项的 type 为 function_call。其中的 name、arguments、call_id 才是应用要处理的调用信息。status: "completed" 表示这里的生成状态已经完成,不能据此判断文件函数已执行。
三个编号各管一件事:响应根 id 标识响应;调用项自己的 id 标识该输出项;call_id 供后续工具反馈对应原调用。MCP 的 id 又属于应用与服务的通信,见 mcp_request.json 与 mcp_response.json。应用负责保存它们之间的对应关系。
第二次请求采用显式回传上下文:保留原用户输入,接上第一次响应的输出项,再追加 function_call_output。本例 input[0] 是任务,input[1] 是原调用,input[2] 是新反馈;编号只适用于这个最小示例。真实程序应遍历输出项,按类型处理,并保留所用模型所需的上下文,不能认定任何响应的第零项必定是工具调用,也不能丢弃其他必要输出项。
注意同名 output 的类型不同:响应根 output 是输出项数组;本例工具反馈对象的 output 是文本字符串。这份文本来自工具返回结果,包装反馈不会重新执行工具。
第二次响应中的输出项现在是 type: "message"、role: "assistant"。向下进入 content 数组,可以找到 type: "output_text" 的文本块,真正答复文本在该块的 text 字段。附件路径为 output[0].content[0].text,这个具体下标同样只是本例位置。SDK 的便利访问属性不应当作原始 JSON 的根字段。
7. 用本地核对确认表示变化
附件 verify_fields.py 与 field_fragments.json 使用 Python 3 标准库即可运行:
python3 examples/verify_fields.py
核对对象是声明、调用和反馈的教学片段。脚本不调用模型、不连接 MCP、不读取示意路径。它实际验证:规则保持规则;模型参数为文本而 MCP 参数为对象;解析前后值相等;MCP 请求/响应配对;模型调用/反馈配对;反馈内容来自同一份结果。
完整往返附件为 responses_roundtrip.json,对应的 verify_roundtrip.py 可用 python3 examples/verify_roundtrip.py 核对:工具声明保留、两轮上下文连续、两个调用编号各自配对,以及原始工具文本进入反馈。脚本额外尝试错误编号、丢失原调用、把参数文本改成对象三种破坏,要求检查能够拒绝它们。
运行附件可复核数据结构的关系;真实接口连通、路径访问、模型选择与最终答复不在这个本地核对的验证范围内。
8. 收益、代价与失败边界
把声明和执行分开,模型可以根据任务选择能力,程序可以集中处理路由和检查。通过协议接入服务,可复用服务提供的工具说明与调用入口;代价是多了一段通信、适配和错误处理。
已有固定程序能直接完成的处理,不必为了使用 Agent 就让模型决定每一步。MCP 是否合适取决于接入需求;它不是每个工具都必须具备的外壳。
常见错误包括:把声明当作执行代码;把规则当成实际参数;解析成功就标成读取成功;把格式正确当作拥有权限;混用两个编号;只写入服务日志却没有把结果加入模型输入;把原始工具数据直接说成最终回答。
对照链路定位时,依次检查模型响应、解析结果、路由目标、服务检查、实际反馈、关联标识和后续模型输入。不要仅凭末尾回答听起来合理,就推断中间工具一定执行过。
9. 改变条件后怎样推演
- 把 head 从 20 改成 5,哪些对象应该改变? 本次参数及期望结果范围改变,schema 中的类型不变。读取仍需权限及文件存在等条件。
- 应用收到 MCP 返回值,却未再次请求模型,会怎样? 应用已有反馈,但模型没有通过这条后续输入获得它;不能据此称模型已结合执行结果回答。
- 两个服务都提供 read_text_file,怎样区分? 应用保存服务来源,可给模型侧工具入口采用不同别名,收到请求后映射回服务与原名;参数值不需要因为别名转换而改变。
- schema 校验通过,读取仍失败,是否矛盾? 不矛盾。输入结构与资源权限、文件存在性是不同检查,失败应作为反馈继续处理。
10. 技术速查
注册工具 → 发现声明与来源 → 适配 tools 并准备 input → 模型选择与填参 → 应用解析与路由 → MCP 请求 → 服务检查并执行 → 结果先回应用 → 对应回 call_id → 新反馈进入模型 → 应用呈现回答。
- inputSchema / parameters:怎么填写的规则。
- 模型 arguments:本次值,在选定接口中以 JSON 文本表示。
- MCP params.arguments:解析后的参数对象。
- content / output:执行后的反馈,必须保留成功或失败的事实。
- MCP id 与模型 call_id:各自配对,通过应用关联。
规则持续存在,值在调用中传递,执行产生新结果。三类对象的身份不能在解释或实现中混为一谈。
本文由 AI图鉴自动抓取并翻译,版权归原作者所有;如需查看原文请点下方链接。
Video knowledge of Lu's great apes Library
Agent tool call: From tool statements to implementation feedback
Scope of application: Apply the Custom Function tool using Open AI Responses and service via the MCP client connection tool. MCP field refers to 2025-06-18. The following is a single call for a teaching exercise, not a real-time grab package; the platform hosting tool and other model interfaces may have different envelopes.
Core issues: After the model gives the name and parameters of the tool, how does the program work and allows the model to use the results to answer the user?
Models generate structured call requirements; apply resolution, route and organize implementation; tool service check input and access conditions to produce results; apply feedback to follow-up model input and model generate responses. It is understood that it needs to always distinguish between three objects: the rules of the instrument, the value of this parameter, and the results of implementation.
1. Determine what is to be accomplished
A file reading interface tracks technical processes. The known input in the task is the logical path /workspace/notes.txt. Assumes that the service is registered read text file and that the application has established the available connection. These are teaching conditions and do not mean that the path exists on the reader's computer.
Success requires three things at the same time: the service does obtain a text that is accessible; the implementation feedback corresponds to the original model call; and the model receives feedback from the organization, which should be presented to the user. Only one of the apparently correct JSON has not yet met any of the conditions for implementation.
2. Why are applications and protocols still needed?
The name and parameter returned by the model interface is first a data. To read the document, it is also necessary to know which achieves its acceptance, whether the input is valid, whether the path allows access and how the error is returned when the call fails.
The most immediate realization is the application of a direct call to a local function, or a code to encapsulate an external API. Where tools are provided by stand-alone services, applications and services also require commonly agreed formats for discovery, call and response; MCP undertakes this communication. It does not replace model mechanisms for generating call requirements, nor does it amount to a code for reading documents.
Direct access, MCP access, platform interior are several entry points to understand access, not mutually exclusive and exhaustive classifications; the same capability can be provided in different ways.
3. Minimum promotion with the same value
Change the head from 20 to 5, which changes the request value and the desired reading range; it does not change the number from the parameter rule to 5. If the JSON text is parsed to an object without calling a processing function, the number of readings remains zero.
Who is responsible for what?
Figure 4-1: Application of connectivity models and tool services. MCP client in application. Messages of the model interface and service are processed separately by the application; the routing in the diagram does not imply access to permission upon request.
Developer is responsible for the description and execution of the associated tool. Model reference tasks and descriptions generate options and parameters. Applying or SDK is responsible for decrypting the envelope, recording the source, associated requests and feedback. Services check for actual input and operation of permission and implement it; end-user responses are modeled and applied.
5. Order of a full call
Figure 5-1 tool call closed ring. Saves parallel calls, initialization of connections and transmission details for the interpretation of the main path. Continued calls are not guarantees of an unlimited cycle; practical application also requires its own conditions of completion, failure or suspension.
The protocol layer error is distinguished from the tool execution error. The former can use protocol error response; the latter can be expressed in the result of the tool is Error. Failure feedback cannot be converted to “read successful”.
6. Identify field and what they belong to.
Tool declaration is the rule
The MCP name identification tool, description describes the use, input Schema binding input. The rules list properties, type specifies the type, required lists the required properties.
The path of this example tool is a string, the head is an optional numerical parameter; the full reference interface also supports optional tail, and the head and tail cannot be used simultaneously. This case is followed only by the first two fields.
When applying fit to Reponses, insert type: "function", name, use and parameters in tables. Here's the parameters still the rule. The JSON Schema range and strict mode requirements supported by the interface need to be compatible and cannot be blindly replicated for all services.
type: "funct" describes the tool category, type: "string" describes the parameter type in the rule; they are at different levels. Tol chaice: "required" requires a model to call a tool, while schema's request: ["path"] requires the call input to include a path and is not the same constraint.
Models generate new call data.
The following video shows the key field of the Responses call:
{
"type": "function_call",
"name": "fs__read_text_file",
"arguments": "{"path":"/workspace/notes.txt","head":20}",
"call_id": "call_demo_1"
}
Arguments here are JSON text. Apply to path and head to pax first. fs is an alias prefix selected for this teaching application to distinguish between services; MCP does not require all tools to use this prefix. Apply to find file service with original name using an existing map.
Specific parameter values must be based on tasks or available information. The rule states that the path is a string and does not automatically provide a path that the model does not yet know. The absence of the necessary information should be supplemented by access or enquiry; this is a correct processing requirement and is not a guarantee that the model will never be miscalculated.
MCP Request to Send Parameter Object to Service
{
"jsonrpc": "2.0",
"id": "rpc_demo_41",
"method": "tools/call",
"params": {
"name": "read_text_file",
"arguments": {"path": "/workspace/notes.txt", "head": 20}
}
}
Params is the requested parameter container in which the tools enter objects. Paths and lines have not changed. The service finds a processing function by name to verify the input, check access range and then read it.
The call id of the model and the id of the MCP belong to two related fields. Apply the relationship " which model calls which service request "; context management can be called through the task object or SDK, without requiring that a global map be created, let alone a numbering of the same string.
Implementation results add new data
MCP response with corresponding id, the result can be found in result.content, or provided with structured Content. When feedback is obtained, the form the model can receive is organized:
{
"type": "function_call_output",
"call_id": "call_demo_1",
"output": "Here is the text actually read, or a clear error statement."
}
This text is an indication of the location of the content, not the execution of the measured output. The result is not to rerun the tool. The application adds the results of the tool and the corresponding call records to the subsequent input, preserves the user ' s assignment and the necessary context; the model is then presented with the execution evidence.
Put back complete Responses requests and responses Look.
"Complete" means the full JSON body selected for this example, with no omitted number in the annex; it does not indicate that all options field are listed for API, nor does it contain initialization of HTTP headers, flow events or connections. All messages are teaching structures, numbered, numbered at: 0 and text location are not measured; usage: full means no measurement data are provided.
Following the same mission, there were four submissions on the side of the model interface:
First request sent to POST/v1/responses. Model selects the model; this example describes the structure with gpt-4.1 supporting Responsions and funcing calling, and does not require all applications to select it. Input and tables are the same array: the former carries tasks and available information, while the latter lists alternative capabilities. Tool choice is also a root field to control selections, not placed in parameters, and not passed to file functions as parameters.
"string" will be found only after reading down the first element along ols. It indicates the type of rules for the path; the actual path appears in another message in arguments. strect: false makes it clear that the strict mode is not enabled in this case; the requirement for cross-crowding and input rules in the description still require program execution inspection, and cannot be inferred from the validity of model output by writing schema.
The first response to the outer layer is id, object, created at, status, model, output etc. field. Output is an array, type of the only item in this case is funcing call. The name, anrguments, call id is the only call information to be used to process. status: "completed" means that the generation status here is complete and cannot be judged as having performed the file function.
Each of the three numbers addresses one thing: responding to the root id identifier response; calling the entry itself id to identify the output item; and call id to provide feedback on the call. MCP id is also an application and service communication, see mcp request.json and mcp response.json. The application is responsible for preserving the correspondence between them.
The second request is sent back to context in a visible form: retain the original user input, reset the output entry for the first response, and add the file call output. This example input[0] is the task, input[1] is the original call, input[2] is the new feedback; numbering only applies to this minimum example. The true program should run through the output item, treat it by type and retain the context required for the model used. It cannot be assumed that the zero of any response must be tool call, nor can other necessary outputs be discarded.
Note that the type of output by the same name is different: responding root output is an output entry array; the output of the feedback object for this tool is a text string. This text is derived from the return of the tool and the packaging feedback will not re-enforce the tool.
The output in the second response is now type: "message", roll: "assist". Go down to the center array and you can find the text block of type: "output text" that really answers text in the box. The attachment path is output [0].content[0].text, which is the same subscript as this case. The easy access attributes of SDK should not be the original JSON root field.
7. Identification of changes with local checks
Attachments verify fields.py and field fragments.json can run using the Python 3 Standard Library:
python3 examples/verify_fields.py
The content of this section is checked against statements, calls and feedback. Scripts do not call models, do not connect MCP, and do not read indicative paths. It actually validates: rules are maintained; model parameters are text and MCP parameters are objects; pre- and post-reconciled values are equal; MCP requests/response pairs are matched; models are called/reciprocated; feedback is derived from the same results.
The complete return to and from the attachment is respons roundtrip.json, which corresponds to verifiy roundtrip.py can be checked by python3 examples/verify roundtrip.py: tool declaration retention, two rounds of context continuous, two call numbers paired, and original tool text for feedback. Scripts try extra wrong numbering, lose original call, change parameter text to object three types of damage, and require inspection to be able to reject them.
Operating annexes review the relationship between the data structure; real interface connectivity, path access, model selection and final response are outside the scope of this local check.
8. Gains, costs and failures
Separate declarations and implementations, models can select capabilities according to tasks, and procedures can focus on route and inspection. Access to services by agreement, tool description of reusable service provision and access; the cost is an additional communication, fit and error handling.
There are fixed programs that can be done directly, and there is no need to let the model decide every step for the use of Agent. MCP suitability depends on access needs; it is not the shell that every tool must have.
Common errors include: using the declaration as an executive code; treating the rule as a practical parameter; deconstructing it as a reading success; correctly considering the format as having permission; mixing the two numbers; simply writing in the service log without adding the results to the model input; and referring the original tool data directly to the final answer.
Check model responses, resolution results, route targets, service checks, actual feedback, linkage markers and subsequent model input in order of chain location. Rather than relying on the final answer to sound reasonable, it is assumed that intermediate tools have been implemented.
9. How to proceed after changing conditions
- Change the head from 20 to 5, which objects should change? This parameter and the range of expected results have changed and the type in schema remains unchanged. Reading still requires conditions such as permission and the existence of documents.
- What if the application received the MCP return value without requesting the model again? The application has received feedback, but the model did not obtain it through this follow-up input; it cannot be assumed that the model has been answered in conjunction with the implementation results.
- Both services offer read text file, how do we distinguish? Applying a preservation service source, different aliases can be used for the model side tool portal to map back the service and the original name upon receipt of the request; parameter values do not need to be changed by an alias conversion.
- Is there a contradiction between schema's approval and the failure to read? Input structure is different from resource permission, document availability is different and failure should continue as feedback.
10. Technical survey
The registration tool found that the declaration and source fit tools and prepared the input → model selection and filling application parsing and → MCP requests → service check and execute → results first respond to call id → new feedback into model application presentation.
- inputSchema/parameters: How to fill out the rules.
- Models: This value, expressed in JSON text in the selected interface.
- MCP params.arguments: deconstructed parameter objects.
- Contact/output: post-implementation feedback must preserve the fact of success or failure.
- MCP id and model call id: each pair, by application.
Rules persist, values are transferred through call and implementation produces new results. The identity of the three categories of objects cannot be confused in interpretation or realization.
Auto-fetched and translated by AI Atlas. All rights belong to the original author.