"""Exercise Python and Node Agent SDK clients against a deterministic local service."""
import argparse
import asyncio
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from importlib.metadata import version
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory
from threading import Thread
from claude_agent_sdk import (
AssistantMessage, ClaudeAgentOptions, CLINotFoundError,
HookMatcher, ResultMessage, TextBlock, ToolUseBlock, query,
)
from lab_gateway import TOKEN, stream
from lab_tool_response import tool_reply
BUGGY = "def interval_total(items):\n return sum(items) / len(items)\n\ndef display_tag(record):\n return record['tag'].strip()\n"
SAFE_AVERAGE = " return sum(items) / len(items) if items else None"
SAFE_TAG = " return record['tag'].strip() if record and record.get('tag') else None"
def isolated_env(root, port):
values = {k:os.environ[k] for k in ("SYSTEMROOT","WINDIR","PATH","TEMP","TMP","COMSPEC","PROGRAMFILES") if k in os.environ}
values.update(CLAUDE_CONFIG_DIR=str(root/"profile"), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1",
DISABLE_TELEMETRY="1",DISABLE_AUTOUPDATER="1",DISABLE_ERROR_REPORTING="1",
CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL="1",ANTHROPIC_AUTH_TOKEN=TOKEN,
ANTHROPIC_BASE_URL=f"http://127.0.0.1:{port}",API_TIMEOUT_MS="5000",
HTTP_PROXY="http://127.0.0.1:1",HTTPS_PROXY="http://127.0.0.1:1",ALL_PROXY="http://127.0.0.1:1",NO_PROXY="localhost,127.0.0.1")
return values
async def exercise(cli, sdk):
requests = []
calls = []
plan = []
current_case = None
class Fixture(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_POST(self):
if self.headers.get("Authorization")!="Bearer "+TOKEN or self.path.split("?")[0]!="/v1/messages":
self.send_error(403)
return
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
number = sum(row["case"]==current_case for row in requests)
tool_results = [c for m in body["messages"] if isinstance(m["content"], list)
for c in m["content"] if c["type"]=="tool_result"]
details = dict(case=current_case, model=body["model"], tool_errors=[c.get("is_error",False) for c in tool_results],
last_tool_result=json.dumps(tool_results[-1]["content"]) if tool_results else "",
scoped_prompt="MB_SKY_SHOW_LOCATION" in json.dumps(body.get("system",[])),
project_context="WAREHOUSE_POLICY_418" in json.dumps(body))
requests.append(details)
if number < len(plan):
name, parameters = plan[number]
payload = tool_reply(body["model"],name,parameters).replace(b"toolu_lab",f"toolu_lab_{number}".encode())
else:
payload = stream(body["model"])
self.send_response(200)
self.send_header("Content-Type","text/event-stream")
self.send_header("Content-Length",str(len(payload)))
self.end_headers()
self.wfile.write(payload)
with TemporaryDirectory(prefix="mbsky-sdk-case-") as tmp, ThreadingHTTPServer(("127.0.0.1",0),Fixture) as server:
root=Path(tmp)
work=root/"warehouse"
work.mkdir()
(work/"CLAUDE.md").write_bytes(b"WAREHOUSE_POLICY_418 Audit only stock data.\n")
source=work/"depot_totals.py"
source.write_bytes(BUGGY.encode())
guard=work/"protected.txt"
guard.write_bytes(b"unchanged\n")
env=isolated_env(root,server.server_port)
for key in list(os.environ):
if key.startswith(("ANTHROPIC_","CLAUDE_CODE_","CLAUDE_CONFIG_DIR")):
del os.environ[key]
def evaluate():
scope={}
exec(compile(source.read_bytes(),str(source),"exec"),scope)
return [scope["interval_total"]([6,8]),scope["interval_total"]([]),
scope["display_tag"]({"tag":" crate "}),scope["display_tag"](None)]
async def watch(input_data, _tool_use_id, _context):
label=input_data["tool_name"]
if label in {"Read","Edit"}:
name=Path(input_data["tool_input"]["file_path"]).name
calls.append([input_data["hook_event_name"],label,name])
if label=="Edit" and name=="protected.txt":
return {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny",
"permissionDecisionReason":"workshop protects this path"}}
return {}
async def ask(label,prompt,actions,tools,with_hooks=False,cli_path=cli,project=False):
nonlocal current_case
current_case=label
plan[:]=actions
options=ClaudeAgentOptions(env=env,cwd=str(work),tools=tools,allowed_tools=tools,model="sample-pro",
setting_sources=["project"] if project else [],cli_path=cli_path,max_turns=8,permission_mode="acceptEdits",
hooks={"PreToolUse":[HookMatcher(matcher="Read|Edit",hooks=[watch])]} if with_hooks else None,
strict_mcp_config=True,
system_prompt={"type":"preset","preset":"claude_code"} if project else "MB_SKY_SHOW_LOCATION Use the local rehearsal files.")
messages=[]
observed_tools=[]
answer=None
async for message in query(prompt=prompt,options=options):
messages.append(type(message).__name__)
if isinstance(message,AssistantMessage):
observed_tools.extend(block.name for block in message.content if isinstance(block,ToolUseBlock))
elif isinstance(message,ResultMessage):
answer=[message.subtype,message.is_error,message.result]
return dict(messages=messages,tools=observed_tools,answer=answer)
t=Thread(target=server.serve_forever,daemon=True)
t.start()
try:
before=[]
scope={}
exec(compile(source.read_bytes(),str(source),"exec"),scope)
for name, data in (("interval_total",[]),("display_tag",None)):
try:
scope[name](data)
except (ZeroDivisionError,TypeError) as error:
before.append(type(error).__name__)
py=await ask("py_list","List depot_ files in the training directory.",
[("Glob",{"pattern":"depot_*.py","path":str(work)})],["Glob"])
edit=await ask("py_fix","Read the training module and handle its two absent-input cases.",
[("Read",{"file_path":str(source)}),
("Edit",{"file_path":str(source),"old_string":" return sum(items) / len(items)","new_string":SAFE_AVERAGE}),
("Edit",{"file_path":str(source),"old_string":" return record['tag'].strip()","new_string":SAFE_TAG})],
["Read","Edit"],True)
denial=await ask("py_deny","Try the protected synthetic file.",
[("Read",{"file_path":str(guard)}),
("Edit",{"file_path":str(guard),"old_string":"unchanged","new_string":"modified"})],
["Read","Edit"],True)
await ask("project_context","Summarize the project rehearsal rules.",[],[],project=True)
try:
await ask("missing","Simulate a missing CLI.",[],[],cli_path=str(root/"none.exe"))
except CLINotFoundError as error:
missing=type(error).__name__
typescript=None
if sdk is not None:
import shutil
node=shutil.which("node")
entry=Path(__file__).with_name("query_typescript.mjs")
current_case="ts_list"
plan[:]=[("Glob",{"pattern":"depot_*.py","path":str(work)})]
result=subprocess.run([node,str(entry),str(sdk),str(work)],cwd=work,env=env,
capture_output=True,encoding="utf8",timeout=30)
assert result.returncode==0,(result.stdout,result.stderr)
typescript=dict(observed=json.loads(result.stdout),version=subprocess.run([node,"--version"],
capture_output=True,encoding="utf8",timeout=8,check=True).stdout.strip(),
sdk_version=json.loads((sdk.parent/"package.json").read_bytes())["version"])
return dict(python_sdk=version("claude-agent-sdk"),py=py,repair=edit,denial=denial,before=before,after=evaluate(),
hook_calls=calls,protected=guard.read_text(encoding="utf8"),
missing_cli=missing,typescript=typescript,requests=requests)
finally:
server.shutdown()
t.join(5)
if __name__=="__main__":
args=argparse.ArgumentParser()
args.add_argument("--claude",type=Path)
args.add_argument("--node-sdk",type=Path,help="Path to the installed @anthropic-ai/claude-agent-sdk/sdk.mjs")
opts=args.parse_args()
print(json.dumps(asyncio.run(exercise(str(opts.claude.resolve()) if opts.claude else None,
opts.node_sdk.resolve() if opts.node_sdk else None)),ensure_ascii=False))
本例需在 Python SDK 0.2.182、TypeScript SDK 0.3.325、Claude Code 2.1.325、Python 3.12 与 Node 24。模型响应由本机服务固定提供。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Python SDK 0.2.182、TypeScript SDK 0.3.325、Claude Code 2.1.325、Python 3.12 与 Node 24。模型响应由本机服务固定提供。
入口文件:projects/claude-code-agent-sdk/exercise_agent_sdk.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
exercise_agent_sdk.py,或下载右侧课程工程包。 - 确认本地已准备 Python SDK 0.2.182、TypeScript SDK 0.3.325、Claude Code 2.1.325、Python 3.12 与 Node 24。模型响应由本机服务固定提供。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3117.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3114.zip