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

从临时配置验证两种 MCP 传输和工具范围

PYTHONWindows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。integrations_lab.py
integrations_lab.py97 行
"""Read a temporary Codex MCP configuration and test a deliberately small tool boundary."""
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import tomllib


CONFIG = """mcp_oauth_callback_port = 8191
mcp_oauth_credentials_store = "file"

[mcp_servers.owned]
command = "python"
args = ["local_tool.py"]
enabled_tools = ["lookup", "write_note", "delete"]
disabled_tools = ["delete"]

[mcp_servers.owned.tools.write_note]
approval_mode = "prompt"

[mcp_servers.remote_fixture]
url = "https://example.invalid/mcp"
bearer_token_env_var = "MB_SKY_FIXTURE_ONLY"
scopes = ["documents:read"]
oauth_resource = "https://example.invalid/mcp"
"""


def main():
    binary = shutil.which("codex.exe") or shutil.which("codex")
    if not binary:
        raise SystemExit("Codex CLI is required on PATH.")
    cases = []

    def check(name, data, operation, expected, actual):
        assert expected == actual, (name, expected, actual)
        cases.append(dict(name="integration_" + name, input=data, operation=operation, expected=expected, actual=actual))

    with TemporaryDirectory(prefix="mbsky-codex-mcp-") as temporary:
        root = Path(temporary)
        config = root / "config.toml"
        config.write_bytes(CONFIG.encode())
        env = dict(os.environ, CODEX_HOME=str(root))

        def cli(*args):
            return subprocess.run([binary, *args], cwd=root, env=env, capture_output=True,
                                  encoding="utf-8", timeout=15, check=True).stdout

        local = json.loads(cli("mcp", "get", "owned", "--json"))
        remote = json.loads(cli("mcp", "get", "remote_fixture", "--json"))
        check("stdio", CONFIG, "Read temporary stdio launcher configuration with the Codex CLI",
              ["stdio", "python", ["local_tool.py"]],
              [local["transport"]["type"], local["transport"]["command"], local["transport"]["args"]])
        check("http", CONFIG, "Read HTTP transport and token variable name without contacting its endpoint",
              ["streamable_http", "https://example.invalid/mcp", "MB_SKY_FIXTURE_ONLY"],
              [remote["transport"][key] for key in ("type", "url", "bearer_token_env_var")])
        check("lists", CONFIG, "Read Codex's stored allow and deny lists",
              [["lookup", "write_note", "delete"], ["delete"]], [local["enabled_tools"], local["disabled_tools"]])

        parsed = tomllib.loads(CONFIG)
        local_cfg = parsed["mcp_servers"]["owned"]
        remote_cfg = parsed["mcp_servers"]["remote_fixture"]
        check("oauth_config", CONFIG, "Read the OAuth fields as TOML without performing authorization",
              [8191, "file", ["documents:read"], "https://example.invalid/mcp"],
              [parsed["mcp_oauth_callback_port"], parsed["mcp_oauth_credentials_store"],
               remote_cfg["scopes"], remote_cfg["oauth_resource"]])

        # This example policy consumes the two observed lists and a caller-supplied approval.
        def permission(tool, confirmed=False):
            if tool not in local["enabled_tools"] or tool in local["disabled_tools"]:
                return "blocked"
            setting = local_cfg["tools"].get(tool, {}).get("approval_mode")
            if setting == "prompt" and not confirmed:
                return "confirmation needed"
            return "allowed"

        for name, tool, approved, expected in (
            ("read", "lookup", False, "allowed"),
            ("deny", "delete", True, "blocked"),
            ("ask", "write_note", False, "confirmation needed"),
            ("allow", "write_note", True, "allowed"),
        ):
            check(name, [tool, approved], "Evaluate the local sample policy with the observed lists",
                  expected, permission(tool, approved))

        version = cli("--version").strip()
    print(json.dumps(dict(version={"python":sys.version.split()[0], "codex":version},
                          codex_sha256=sha256(Path(binary).read_bytes()).hexdigest(), cases=cases)))


if __name__ == "__main__":
    main()
本例需在 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。

入口文件:projects/codex-integrations/integrations_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 integrations_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Codex 教程

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

下载课程关联工程包:Codex 教程

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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