蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

查询 A7 库位并检查不同角色能否调用同一服务

PYTHONWindows、Git、Python 3.12、OpenCode V1.19.5 和本机回环测试服务。mcp_stock_lab.py
mcp_stock_lab.py88 行
"""Observe actual OpenCode MCP tool calls using a local process and a loopback URL."""
from hashlib import file_digest
from http.server import ThreadingHTTPServer
import json
import os
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
from threading import Thread

from cli_sessions import profile,server
from first_use import request
from rules_lab import initialize
from stock_mcp_server import HTTPFixture
from tool_policy import ScriptedModel,prompt,result_part


def check(exe):
    with (TemporaryDirectory(prefix="mbsky-opencode-mcp-") as tmp,
          ThreadingHTTPServer(("127.0.0.1",0),ScriptedModel) as mock,
          ThreadingHTTPServer(("127.0.0.1",0),HTTPFixture) as remote):
        root=Path(tmp)
        env=profile(root)
        env.update(HOME=str(root),USERPROFILE=str(root),GIT_CONFIG_GLOBAL=os.devnull,
                   GIT_CONFIG_NOSYSTEM="1",OPENCODE_DISABLE_LSP_DOWNLOAD="true",
                   MBSKY_STOCK_AUTH="warehouse-test-value")
        mock.jobs={}
        remote.methods=[]
        workers=[Thread(target=x.serve_forever,daemon=True) for x in (mock,remote)]
        for worker in workers:worker.start()
        output={}
        try:
            work=root/"stock warehouse"
            initialize(work,env,mock)
            path=work/"opencode.json"
            config=json.loads(path.read_bytes())
            config["provider"]["openai"]["models"]["tool-fixture"]=dict(
                name="MCP fixture",tool_call=True,limit=dict(context=32768,output=4096))
            config.update(model="openai/tool-fixture",small_model="openai/tool-fixture",permission={"*":"deny","selected_*":"allow","httpstock_*":"allow"})
            config["agent"]={"stockreview":{"description":"Stock reviewer","mode":"primary",
                "permission":{"selected_*":"deny"}},
                "stockallow":{"description":"Targeted access","mode":"primary","permission":{"optin_*":"allow"}}}
            fixture=Path(__file__).with_name("stock_mcp_server.py")
            started=work/"enabled.start";disabled=work/"disabled.start";optin=work/"optin.start"
            local=dict(type="local",command=[sys.executable,"-B","-u",str(fixture),str(started)],
                       environment={"MBSKY_STOCK_MCP":"stdio-sample"},timeout=5000)
            config["mcp"]={"selected":local,
                "off":dict(local,enabled=False,command=[*local["command"][:-1],str(disabled)]),
                "optin":dict(local,command=[*local["command"][:-1],str(optin)]),
                "httpstock":dict(type="remote",url=f"http://127.0.0.1:{remote.server_port}/mcp",
                                headers={"Authorization":"Bearer {env:MBSKY_STOCK_AUTH}"},oauth=False,timeout=5000)}
            path.write_text(json.dumps(config),encoding="utf8")
            with server(exe,work,env) as origin:
                version=request(origin,"/global/health")["version"]
                states=request(origin,"/mcp")
                output["states"]={name:item["status"] for name,item in states.items()}
                output["process_markers"]=[started.exists(),disabled.exists()]
                for name,func in (("local_lookup","selected_lookup"),("remote_lookup","httpstock_lookup"),
                                  ("role_cannot_use","selected_lookup"),("build_cannot_use","optin_lookup"),("opted_in","optin_lookup")):
                    mock.jobs[name]=(func,{"shelf":"A7"})
                    sid=request(origin,"/session",dict(title=name))["id"]
                    if name in ("role_cannot_use","opted_in"):
                        agent="stockreview" if name=="role_cannot_use" else "stockallow"
                        request(origin,f"/session/{sid}/message",
                            dict(agent=agent,model=dict(providerID="openai",modelID="tool-fixture"),
                                 parts=[dict(type="text",text="tool-case:"+name)]))
                    else:
                        prompt(origin,sid,name)
                    tool=result_part(origin,sid,name)
                    state=tool["state"]
                    value=state.get("output","")
                    output[name]=dict(status=state["status"],tool=tool["tool"],
                        expected_local_content="stdio-sample A7 quantity=17" in value,
                        expected_remote_content="http-sample A7 quantity=17" in value,
                        rejected=state["status"]=="error" and any(x in state.get("error","").lower() for x in ("reject","denied","permission")))
                output["stdio_calls"]={n:f.read_text(encoding="utf8").splitlines().count("lookup") for n,f in (("selected",started),("optin",optin))}
                output["http_methods"]={method:all(valid for name,valid in remote.methods if name==method)
                                         for method in sorted({name for name,_ in remote.methods})}
        finally:
            for service in (mock,remote):service.shutdown()
            for worker in workers:worker.join(timeout=4)
    with exe.open("rb") as stream:digest=file_digest(stream,"sha256").hexdigest()
    return dict(version=version,python_version=sys.version.split()[0],binary_sha256=digest,actual=output)


if __name__=="__main__":
    print(json.dumps(check(Path(sys.argv[1]).resolve()),ensure_ascii=False))
本例需在 Windows、Git、Python 3.12、OpenCode V1.19.5 和本机回环测试服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Git、Python 3.12、OpenCode V1.19.5 和本机回环测试服务。

入口文件:projects/opencode-mcp/mcp_stock_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 mcp_stock_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Git、Python 3.12、OpenCode V1.19.5 和本机回环测试服务。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:OpenCode

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a249.zip

下载课程关联工程包:OpenCode

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a236.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习