"""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
本地运行步骤快速上手
- 点击上方“保存源码”保存为
integrations_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a109.zip