蓝色天空网mbsky.com · 知识 · 实践 · 创造AI Agent(智能体) · 本地阅读预览
教程 / AI / 智能开发 / AI Agent(智能体)

连接界面、MCP 和外部 API

用实际浏览器操作、本机 MCP stdio 和 HTTP 服务验证工具输入、权限与失败处理。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先选择可核验的接口

智能体可通过受控工具操作本地文件、查询数据或与用户界面交互。先明确目标、当前身份、允许动作及成功条件。应用已有稳定接口时,可直接调用该接口并检查结构化响应。只提供图形界面时,可通过观察和操作完成任务。

REST 用 HTTP 方法和资源地址表达操作。GraphQL 根据模式选择字段,需要检查响应中的数据和错误。gRPC 根据服务与消息契约发起远程调用,可支持不同流式方式。协议选择取决于现有服务、权限、性能和客户端需求。

观察控件后再提交动作

界面工具通常按截屏、识别、决策、执行与验证的顺序工作。观察器应记录页面版本、控件边界、可见性和可用状态。执行器只接收允许的鼠标、键盘与滚动动作。执行后等待能证明状态变化的条件,再观察新界面。总动作数和等待时间都应有上限。

本站练习在 Edge 真实页面读取控件边界,使用坐标点击、输入、按 Enter 和滚轮。空白表单中保存按钮被禁用。输入 Harbor check 后点击,页面版本从 0 变为 1。用键盘提交 Dock ready 后变为 2,滚轮使明细区实际滚动。下方为第二次提交后的本站截图。

本站表单用键盘第二次提交后显示已保存 Dock ready
本站本机表单实跑。第二次提交后显示 Dock ready,滚轮已移动明细区域。

本机验证用 DOM 定位再使用真实指针动作,截图保留作为可视证据。使用视觉模型时,还要检验坐标系、设备像素比、遮挡、缩放和界面变化。桌面软件、实际账号和有副作用的操作需要另设权限与确认条件。

区分 MCP 工具调用与资源读取

宿主创建客户端并管理会话。客户端和服务端初始化协商版本与能力,再使用 tools/list 发现工具并通过 tools/call 调用。资源走单独的读取接口。文件写入可由具备权限的工具实现,资源接口本身不提供通用写操作。

本站用 MCP 1.30.0 及 stdio 验证 read_file 的必填路径与可选编码。默认 UTF-8,另有 UTF-16 示例。write_file 需要路径和内容。只读会话拒绝写入,显式本机授权后写入临时文件,并核对实际字节。文件越界或无效编码返回错误。

若 list_directory 的路径可省略,调用时要为它提供默认值。本站程序省略路径时列出练习根目录,指定 reports 时列出子目录,拒绝上级、普通文件或缺失目录。该检查使用临时目录,并区分真实远程鉴权和并发文件安全。

构造 REST 请求并核对返回

客户端从受控配置读取可信基础地址,限制允许的端点,分别设置查询参数和 JSON 请求体。本站 GET 查询固定城市 Harbor,预报天数默认 3,可传 1 至 5 的整数。布尔值、未批准的城市和超范围天数在发请求前被拒绝。

GET 用于读取,POST 按接口定义提交,PUT 可替换目标资源,DELETE 请求移除目标。本站在真实本地服务发送四种方法,检查实际请求和读回状态。PUT 相同内容两次结果一致。DELETE 两次后读取返回 404。HTTP 状态允许因处理过程不同而变化。

响应先检查状态与类型,再按接口解析。204 没有响应内容。200 若返回 HTML,不能按 JSON 解析。连接与读取超时应单独设置,不在错误信息中输出密钥、授权头或完整敏感内容。

限制重试、限流和缓存范围

本站只对固定 GET 的 503 分支测试有上限的退避,依次记录 1 秒、2 秒的拟定等待并验证三次实际请求。非幂等 POST 的 503 不自动重试。429 读取 Retry-After 后返回给调用方,本例未追加请求。

读取缓存以城市和天数组合为键,十秒内复用,到期后重新读取。练习用可控时钟核对三次实际请求。远端多用户应用需把身份、权限和版本纳入缓存设计,并按服务策略处理限流和失效。真实延迟、远端认证及缓存持久化另验。

观察真实 HTTP 请求及界面状态更新

python · 阅读源码
"""Run a bounded Requests client against a real loopback HTTP service."""
from collections import Counter
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from threading import Thread
from urllib.parse import parse_qs, urlsplit

import requests

from lab_tools import run_exercise


def fixture(counter):
    records={}
    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            url=urlsplit(self.path)
            route=url.path
            counter["GET",route]+=1
            if route=="/forecast/Harbor":
                days=int(parse_qs(url.query)["days"][0])
                self.send_json(200,{"days":days,"fixture":"forecast"})
            elif route=="/weather/Harbor":
                self.send_json(200,{"place":"Harbor","fixture":"clear"})
            elif route=="/record/fixture" and route in records:
                self.send_json(200,records[route])
            elif route=="/retry":
                self.send_json(503 if counter["GET",route]<3 else 200,{"fixture":"retry"})
            elif route=="/limited":
                self.send_json(429,{"fixture":"limited"},{"Retry-After":"4"})
            elif route=="/empty":
                self.send_json(204)
            elif route=="/html":
                self.send_response(200)
                self.send_header("Content-Type","text/html")
                self.end_headers()
                self.wfile.write(b"<p>not JSON</p>")
            else:
                self.send_json(404,{"fixture":"missing"})

        def do_POST(self):
            counter["POST",self.path]+=1
            data=json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            counter["body",data["record"]]+=1
            self.send_json(503,{"fixture":"post failed"})

        def do_PUT(self):
            counter["PUT",self.path]+=1
            data=json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            records[self.path]=data
            self.send_json(200,data)

        def do_DELETE(self):
            counter["DELETE",self.path]+=1
            records.pop(self.path,None)
            self.send_json(204)

        def send_json(self,status,data=None,headers=None):
            self.send_response(status)
            self.send_header("Content-Type","application/json")
            for key,value in (headers or {}).items():
                self.send_header(key,value)
            self.end_headers()
            if data is not None:
                self.wfile.write(json.dumps(data).encode())

        def log_message(self,*args):
            pass

    return Handler


class Client:
    def __init__(self,origin,session,clock,wait):
        self.origin=origin
        self.session=session
        self.clock=clock
        self.wait=wait
        self.cache={}

    def request(self,method,endpoint,*,params=None,body=None):
        if endpoint not in {"/forecast/Harbor","/weather/Harbor","/retry","/limited","/empty","/html","/missing","/write","/record/fixture"}:
            raise ValueError("endpoint not allowed")
        attempts=3 if method=="GET" else 1
        for attempt in range(attempts):
            with self.session.request(method,self.origin+endpoint,params=params,json=body,timeout=(1,2),
                                      allow_redirects=False) as response:
                if response.status_code==503 and attempt+1<attempts:
                    self.wait(2**attempt)
                    continue
                if response.status_code==429:
                    return {"status":429,"retry_after":response.headers.get("Retry-After")}
                response.raise_for_status()
                if response.status_code==204:
                    return None
                if response.headers.get("Content-Type","").split(";",1)[0]!="application/json":
                    raise ValueError("expected application/json")
                return response.json()

    def forecast(self,city,days=3):
        if city!="Harbor" or type(days) is not int or not 1<=days<=5:
            raise ValueError("invalid city or days")
        key=(city,days)
        cached=self.cache.get(key)
        now=self.clock()
        if cached is not None and now<cached[0]:
            return cached[1].copy()
        value=self.request("GET","/forecast/Harbor",params={"days":days})
        self.cache[key]=(now+10,value.copy())
        return value


def exercise(checks,_root):
    expect=checks.expect
    count=Counter()
    with ThreadingHTTPServer(("127.0.0.1",0),fixture(count)) as server, requests.Session() as session:
        session.trust_env=False
        thread=Thread(target=server.serve_forever,daemon=True)
        thread.start()
        try:
            now=[100]
            waits=[]
            client=Client(f"http://127.0.0.1:{server.server_port}",session,lambda:now[0],waits.append)
            first=client.forecast("Harbor")
            repeat=client.forecast("Harbor")
            distinct=client.forecast("Harbor",2)
            now[0]+=10
            expired=client.forecast("Harbor")
            expect("integration_rest_forecast",["default","repeat","two days","at expiry"],
                   "Observe actual query parameters and cache by argument until TTL expires",
                   [[3,3,2,3],3],[[r["days"] for r in (first,repeat,distinct,expired)],count["GET","/forecast/Harbor"]])
            weather=client.request("GET","/weather/Harbor")
            expect("integration_rest_weather","Harbor","Read the fixed payload over loopback",
                   {"place":"Harbor","fixture":"clear"},weather)
            errors=[]
            for city,days in (("../write",3),("Harbor",True),("Harbor",6)):
                try:
                    client.forecast(city,days)
                except ValueError as error:
                    errors.append(str(error))
            expect("integration_rest_parameters",["bad city","boolean days","days 6"],
                   "Reject invalid inputs before they can issue another request",
                   [["invalid city or days"]*3,3],[errors,count["GET","/forecast/Harbor"]])

            reply=client.request("GET","/retry")
            expect("integration_rest_backoff","two 503 responses followed by 200",
                   "Observe three real requests and the scheduled delays without waiting",
                   [{"fixture":"retry"},3,[1,2]],[reply,count["GET","/retry"],waits.copy()])
            limited=client.request("GET","/limited")
            expect("integration_rest_retry_after","429 with Retry-After 4",
                   "Return the server hint without retrying or bypassing the rate limit",
                   [{"status":429,"retry_after":"4"},1],[limited,count["GET","/limited"]])

            errors=[]
            for method,endpoint,body in (("POST","/write",{"record":"fixture"}),("GET","/missing",None)):
                try:
                    client.request(method,endpoint,body=body)
                except requests.HTTPError as error:
                    errors.append(error.response.status_code)
            expect("integration_rest_post_no_retry",["POST 503","GET 404"],
                   "Check one POST body received and no retry for a non-idempotent request",
                   [[503,404],1,1,1],[errors,count["POST","/write"],count["body","fixture"],count["GET","/missing"]])

            kind=None
            try:
                client.request("GET","/html")
            except ValueError as error:
                kind=str(error)
            expect("integration_rest_response_types",["204","200 HTML"],
                   "Distinguish empty response from a successful status carrying an invalid media type",
                   [None,"expected application/json"],[client.request("GET","/empty"),kind])
            path="/record/fixture"
            written=client.request("PUT",path,body={"record":"updated"})
            replaced=client.request("PUT",path,body={"record":"updated"})
            fetched=client.request("GET",path)
            removed=[client.request("DELETE",path),client.request("DELETE",path)]
            try:
                client.request("GET",path)
            except requests.HTTPError as error:
                absent=error.response.status_code
            else:
                absent=None
            expect("integration_rest_put_delete",["PUT twice","read","DELETE twice","read"],
                   "Verify repeated method outcomes and missing state in the real fixture service",
                   [[{"record":"updated"}]*3,[None,None],404,2,2],
                   [[written,replaced,fetched],removed,absent,count["PUT",path],count["DELETE",path]])
            expect("integration_requests_version","runtime","Read installed library version","2.34.2",requests.__version__)
        finally:
            server.shutdown()
            thread.join(timeout=5)


if __name__=="__main__":
    run_exercise(exercise)
预期结果 · 待实际运行核验
  • 本机验证四种 HTTP 方法、503 重试和 429 停止,浏览器表单可用鼠标或键盘更新版本。
观察真实 HTTP 请求及界面状态更新

所需环境:Windows CPython 3.12.14、Requests 2.34.2、MCP 1.30.0 与 Edge,本机练习。

当前源码 SHA256:d32fea0a41bae69a96aab775bbce613915789fa3fd5a81bd77a5a08ba18ca0a2

运行本机接口和界面练习

ZIP 内含真实本机 HTTP 服务、MCP 文件工具与浏览器表单。

下载本站工具集成练习

所需环境:Windows CPython 3.12.14、Requests 2.34.2、MCP 1.30.0 与 Edge,本机练习。

ZIP SHA256:ee22646437837d7fa56e422355ef8649b245c70bbd4733b0745826aee197d264

常见错误与边界

  • 资源 URI 的读取和有副作用的工具调用需要不同权限。
  • 调用成功还须检查内容类型、结果字段与状态变化。

练习与解答

在本地页面先用鼠标填写并保存一条记录,再用 Enter 保存另一条。运行 rest_lab.py 和 listing_lab.py 核对边界。

展开参考解答

页面状态更新两次。超范围预报参数在发请求前被拒绝。目录工具省略参数时列根目录。

规范与官方依据