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

观察旧命令、同名技能和 MCP 提示进入实际请求

PYTHONClaude Code 2.1.325、Python 3.12、Git Bash、临时项目与回环测试服务。check_slash_mcp.py
check_slash_mcp.py115 行
"""Compare local legacy commands and skills through a real Claude Code request."""
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory
from threading import Thread
from lab_gateway import TOKEN, stream


SKILL = """---
name: terminal-audit
description: Review a station transcript with the given topic and severity.
disable-model-invocation: true
---

SKILL_VERSION_51
ALL=$ARGUMENTS
TOPIC=$ARGUMENTS[0]
SEVERITY=$1
"""
LEGACY = """---
description: Generate a local audit note.
allowed-tools: Bash(printf *)
---

LEGACY_VERSION_13
ALL=$ARGUMENTS
TOPIC=$0
SEVERITY=$1
Bash output:
!`printf 'BASH_%s' DONE`
@materials/trial.md
"""
ANCHOR = "FILE_CONTENT_68"

def exercise(exe,bash):
    observed=[]
    class Handler(BaseHTTPRequestHandler):
        def log_message(self,*_):
            pass

        def do_POST(self):
            if self.headers.get("Authorization")!="Bearer "+TOKEN or self.path.split("?",1)[0]!="/v1/messages":
                self.send_error(403)
                return
            body=json.loads(self.rfile.read(int(self.headers["Content-Length"])))
            chunks=[b.get("text","") for m in body["messages"] for b in m["content"]
                    if isinstance(m["content"],list) and b["type"]=="text"]
            chosen=next((x for x in chunks if "VERSION_" in x),"")
            values=dict(line.split("=",1) for line in chosen.splitlines() if line.split("=",1)[0] in
                        ("ALL","TOPIC","SEVERITY","BASH","INPUT"))
            packet="\n".join(chunks)
            observed.append(dict(skill="SKILL_VERSION_51" in packet,legacy="LEGACY_VERSION_13" in packet,
                                 bash="BASH_DONE" in packet,file=ANCHOR in packet,values=values,
                                 prompt="PROMPT_STATION_North_LEVEL_high" in packet,
                                 tool_registered=any(t.get("name")=="mcp__station__lookup_zone" for t in (body.get("tools") or [])),
                                 literal_alias="/station:audit_note" in packet))
            raw=stream(body["model"])
            self.send_response(200)
            self.send_header("Content-Type","text/event-stream")
            self.send_header("Content-Length",str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)

    with TemporaryDirectory(prefix="mbsky-slash-") as directory,ThreadingHTTPServer(("127.0.0.1",0),Handler) as server:
        root=Path(directory)
        work=root/"work"
        commands=work/".claude/commands"
        skills=work/".claude/skills/terminal-audit"
        commands.mkdir(parents=True)
        skills.mkdir(parents=True)
        (work/"materials").mkdir()
        (work/"materials/trial.md").write_text(ANCHOR+"\n",encoding="utf-8")
        (commands/"legacy-audit.md").write_text(LEGACY,encoding="utf-8")
        (commands/"terminal-audit.md").write_text(LEGACY,encoding="utf-8")
        (skills/"SKILL.md").write_text(SKILL,encoding="utf-8")
        env={k:os.environ[k] for k in ("SYSTEMROOT","WINDIR","PATH","TEMP","TMP","COMSPEC","PROGRAMFILES") if k in os.environ}
        env.update(CLAUDE_CONFIG_DIR=str(root/"profile"),CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1",
                   DISABLE_AUTOUPDATER="1",DISABLE_TELEMETRY="1",DISABLE_ERROR_REPORTING="1",
                   CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL="1",CLAUDE_CODE_GIT_BASH_PATH=str(bash),
                   ANTHROPIC_BASE_URL=f"http://127.0.0.1:{server.server_port}",ANTHROPIC_AUTH_TOKEN=TOKEN,
                   ANTHROPIC_MODEL="sample-pro",API_TIMEOUT_MS="4500",ENABLE_TOOL_SEARCH="false",
                   HTTP_PROXY="http://127.0.0.1:1",HTTPS_PROXY="http://127.0.0.1:1",NO_PROXY="localhost,127.0.0.1")
        config=root/"mcp.json"
        config.write_text(json.dumps({"mcpServers":{"station":{"type":"stdio","command":sys.executable,
          "args":["-B",str(Path(__file__).with_name("station_prompts.py"))]}}}),encoding="utf-8")
        worker=Thread(target=server.serve_forever,daemon=True)
        worker.start()
        invocations=[]
        try:
            for prompt in ('/legacy-audit "Gate A" urgent','/terminal-audit "Gate A" urgent',"/mcp__station__audit_note North high",
                           "/station:audit_note North high"):
                p=subprocess.run([str(exe),"-p","--mcp-config",str(config),"--strict-mcp-config","--output-format","json",prompt],
                                 cwd=work,env=env,input=b"",capture_output=True,timeout=22)
                assert p.returncode==0,(p.stdout,p.stderr)
                result=json.loads(p.stdout)
                assert result["result"]=="index ready",result
                invocations.append(dict(prompt=prompt,result=result["result"]))
        finally:
            server.shutdown()
            worker.join(5)
    return dict(requests=observed,invocations=invocations)


if __name__=="__main__":
    p=argparse.ArgumentParser()
    p.add_argument("claude",type=Path)
    p.add_argument("bash",type=Path)
    args=p.parse_args()
    print(json.dumps(exercise(args.claude.resolve(strict=True),args.bash.resolve(strict=True)),ensure_ascii=False))
本例需在 Claude Code 2.1.325、Python 3.12、Git Bash、临时项目与回环测试服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Claude Code 2.1.325、Python 3.12、Git Bash、临时项目与回环测试服务。

入口文件:projects/claude-code-slash-commands/check_slash_mcp.py

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

下载课程关联工程包:Claude Code

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

下载课程关联工程包:Claude Code

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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