示例工程 60-tool-registry-approval

60-tool-registry-approval/demo-01-registry-validation/registry.ts

typescript · 1.6 KB

type Tool = {
  id: string;
  risk: "read" | "write" | "exec" | "network";
  fields: Array<{ name: string; required: boolean }>;
};

const TOOLS: Tool[] = [
  { id: "read_file", risk: "read", fields: [{ name: "path", required: true }] },
  {
    id: "write_file",
    risk: "write",
    fields: [
      { name: "path", required: true },
      { name: "content", required: true },
    ],
  },
  {
    id: "run_shell",
    risk: "exec",
    fields: [{ name: "command", required: true }],
  },
];

function lookup(id: string): Tool {
  const tool = TOOLS.find((item) => item.id === id);
  if (!tool) throw new Error(`UNKNOWN_TOOL:${id}`);
  return tool;
}

function validate(tool: Tool, args: Record<string, string>): string | null {
  for (const field of tool.fields) {
    if (field.required && !args[field.name]?.trim()) {
      return `MISSING_${field.name.toUpperCase()}`;
    }
  }
  return null;
}

const write = lookup("write_file");
const missing = validate(write, { path: "notes/a.md" });
const good = validate(write, { path: "notes/a.md", content: "hi" });
const readNeedsApproval = lookup("read_file").risk !== "read";
const execNeedsApproval = lookup("run_shell").risk !== "read";

let unknown = "";
try {
  lookup("rm_rf");
} catch (error) {
  unknown = error instanceof Error ? error.message : String(error);
}

const ok =
  TOOLS.length === 3 &&
  missing === "MISSING_CONTENT" &&
  good === null &&
  !readNeedsApproval &&
  execNeedsApproval &&
  unknown === "UNKNOWN_TOOL:rm_rf";

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    tools: TOOLS.map((tool) => tool.id),
    missing,
    good,
    unknown,
  }),
);

export {};