ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

Agent Tool Registry(ATR)实战指南:用 agent-governance-toolkit 构建类型安全的去中心化 Agent 工具注册表

Agent Tool Registry(ATR)实战指南:用 agent-governance-toolkit 构建类型安全的去中心化 Agent 工具注册表 Agent Tool RegistryATR实战指南用 agent-governance-toolkit 构建类型安全的去中心化 Agent 工具注册表【免费下载链接】agent-governance-toolkitAI Agent Governance Toolkit — Policy enforcement, zero-trust identity, execution sandboxing, and reliability engineering for autonomous AI agents. Covers 10/10 OWASP Agentic Top 10.项目地址: https://gitcode.com/GitHub_Trending/ag/agent-governance-toolkit本文是 Agent OSAI Agent 内核级治理体系中ATR - Agent Tool Registry模块的完整技术指南。ATR 是 Agent OS 生态中负责工具注册、运行时发现与 LLM 函数调用 Schema 生成的基础设施组件Layer 2 Infrastructure位于 agent-governance-python/agent-os/modules/atr 目录。读完本文你将掌握如何用 5 行代码注册一个可被 LLM 调用的工具、如何利用版本约束与标签检索工具、如何把工具导出为 OpenAI Function Calling / Anthropic Tool Use 格式以及如何用 Docker 沙箱安全执行不可信代码。为什么需要 ATRScale by Subtraction大多数 Agent 框架把工具直接硬编码进运行时hardcode tools directly into runtimes这会带来严重的耦合问题新增一个能力就要重启整个系统修改一个函数签名就要更新数十个 Agent靠加法扩展Scale by addition最终导致系统脆弱。ATR 的设计哲学是Scale by Subtraction——把 Agent 逻辑与工具实现之间的依赖减去工具提供方Tool Providers与工具消费方Tool Consumers被彻底解耦Agent 在运行时通过标准化接口动态发现能力而不是在代码里写死工具注册不需要重启基础设施tool registration should not require restarting your infrastructure。从实现上看这种解耦体现在 ATR 的核心约定上注册表只存规格specs不执行调用。Registry的 docstring 明确写道This registry stores tool specifications and their callables but does NOT execute them. Its purely a lookup and discovery mechanism. The actual execution is handled by the Agent Runtime (Control Plane).见 registry.py。执行发生在控制平面Agent Control Plane并配有完整的错误处理与可观测性。安装与依赖原版 ATR 文档给出的安装方式pip install agentmesh-tool-registry若需要使用 Docker 沙箱执行推荐用于不可信代码pip install agentmesh-tool-registry[sandbox]需要特别说明的是当前仓库 pyproject.toml 中实际定义的发行包名为agent-governance-toolkit-tool-registry版本 5.0.0模块导入名仍为atrPython 版本要求3.11核心依赖仅pydantic2.4.0,3.0.0因此整个注册表在纯 Python 环境下非常轻量。sandbox可选依赖对应docker7.0.0,8.0。依赖组内容用途核心必装pydantic2.4.0,3.0.0ToolSpec 等全部 Schema 的强类型校验[sandbox]docker7.0.0,8.0DockerExecutor 沙箱执行[dev]pytest、mypy、ruff、pre-commit开发与测试[docs]mkdocs、mkdocstrings文档构建[hf]huggingface-hub、datasetsHugging Face 集成仓库还为atr提供了 CLI 入口atr atr.cli:main并声明了py.typed标记属于 Typing::Typed 包IDE 与类型检查器可以完整推断 API 类型。快速开始5 行代码注册一个工具注册一个工具只需要一个装饰器import atr atr.register(namecalculator, tags[math]) def add(a: int, b: int) - int: Add two numbers. return a b发现并执行tool atr.get_tool(calculator) schema tool.to_openai_function_schema() # OpenAI-compatible func atr.get_callable(calculator) result func(a5, b3) # Returns 8 # Or use sandboxed execution (recommended for untrusted code) from atr import DockerExecutor docker_exec DockerExecutor() result atr.execute_tool(calculator, {a: 5, b: 3}, executordocker_exec)这里有一个关键细节值得注意atr.register()装饰器返回的是原始函数本身而不是包装后的函数we dont wrap it。decorator.py中的__call__方法在提取签名、构建ToolSpec并完成注册后直接return func见 decorator.py。这意味着原有函数行为完全不变add(5, 3)照常可用注册过程不会执行函数体——测试 test_decorator.py 中专门用计数器函数验证了装饰后调用次数仍为 0注册表通过ToolSpec._callable_func私有属性保存函数引用但只在显式获取/执行时才调用。仓库自带可运行的完整示例 examples/demo.py 与 examples/sandbox_demo.py可以直接作为入门模板。注册表核心 API 深入atr包在__init__.py中暴露了一套面向全局注册表的便捷函数所有实现最终都委托给全局Registry实例见init.py。检索工具get_tool / get_tool_handle / get_callable# 获取 ToolSpec规格不执行 spec atr.get_tool(calculator, version1.0.0) print(spec.metadata.description) # 获取 ToolHandle带全部策略的执行句柄推荐 tool atr.get_tool_handle(pdf_parser, version1.0.0) result await tool.call_async(file_pathdoc.pdf) # 或同步执行 result tool.call(file_pathdoc.pdf) # 直接取回原始函数调用方自行执行 func atr.get_callable(calculator) result func(a1, b2)ToolHandle是官方推荐的生产级执行入口它自动叠加限流rate limiting、重试retries、指标采集metrics collection、依赖注入dependency injection并通过call()/call_async()提供同步/异步两种执行方式见 schema.py。版本约束语法Registry内置了完整的语义化版本SemVer匹配引擎version_matches()见 registry.py支持约束语义示例匹配1.0.0精确匹配仅 1.0.01.0.0/1.0.0大于等于 / 大于1.0.0 / 1.0.11.0.0/1.0.0小于等于 / 小于1.0.0 及以下^1.0.0兼容同主版本且 约束1.x.x~1.0.0近似同主.次版本1.0.x*或任意版本全部安全设计协议前缀git、file:、http:、https:、ssh:、npm:、workspace:和非 SemVer 标签latest、next、canary、nightly会被显式拒绝为不匹配——这是为了防止依赖混淆与供应链攻击。查询版本时若不传version则默认返回最高版本max(available.keys(), keyparse_version)。同一工具可以注册多个版本get_all_versions(name)按新到旧排序返回。发现与筛选list_tools / search_tools# 按标签筛选 math_tools atr.list_tools(tagmath) # 按成本等级筛选CostLevel.FREE/LOW/MEDIUM/HIGH cheap_tools atr.list_tools(costCostLevel.LOW) # 按副作用类型筛选SideEffect.READ/WRITE/DELETE/NETWORK/FILESYSTEM read_only atr.list_tools(side_effectSideEffect.READ) # 关键词搜索大小写不敏感匹配 name/description/tags results atr.search_tools(scrape)生命周期管理# 查看某工具全部版本 versions atr.get_all_versions(pdf_parser) # [2.0.0, 1.1.0, 1.0.0] # 废弃某个版本可附迁移指引默认查询会跳过废弃版本 atr.deprecate_tool(pdf_parser, 1.0.0, Use version 2.0.0 instead.) # 反注册与清空 registry.unregister_tool(pdf_parser, 1.0.0) # 移除指定版本 registry.clear() # 清空全部注册表定义了三种专有异常ToolNotFoundError工具不存在或全部版本已废弃、ToolAlreadyExistsError同名同版本重复注册可用replaceTrue覆盖、VersionConstraintError无版本满足约束方便上层 Agent 运行时做精确的错误处理。注册表配置若需要为全局注册表注入依赖容器、指标采集器或访问控制管理器from atr import DependencyContainer, configure_registry container DependencyContainer() container.register(Config, Config(api_keysecret)) configure_registry(containercontainer) registry atr.get_registry() # 官方推荐的方式而非直接访问私有 _global_registryregister 装饰器严格类型检查与 Schema 自动生成atr.register()的核心价值在于把 Python 函数签名自动翻译为机器可读的 ToolSpec其实现分四步见 decorator.py提取元数据工具名默认取函数名描述默认取 docstringis_async通过asyncio.iscoroutinefunction自动检测提取参数用inspect.signatureget_type_hints遍历参数把 Python 类型映射为ParameterTypestr→string、int→integer、float→number、bool→boolean、list→array、dict→objectOptional[X]会解包为 XList[str]/Dict[str, int]会映射为 array/object提取返回值有- T注解时生成returns规格注册构建ToolSpec并存入注册表。强约束禁止魔法参数No Magic Arguments这是 ATR 与普通装饰器最大的不同所有参数必须有类型注解否则注册时直接抛ValueError。测试 test_decorator.py 验证了无类型注解的函数def bad_func(url, timeout30)会触发must have a type hint错误。这保证了生成的 LLM Schema 永远完整、可用不会出现模型无法推断的参数类型。完整注册参数一览参数类型默认值说明namestr函数名工具唯一标识descriptionstr函数 docstring人类可读描述供 LLM 理解versionstr1.0.0语义化版本必须匹配^\d\.\d\.\d...格式authorstrNone工具作者coststrfree成本等级free/low/medium/high非法值回退为 freeside_effectslist[none]副作用none/read/write/delete/network/filesystem非法值回退为 nonetagslist[]可搜索标签registryRegistry全局注册表自定义注册表实例async_bool自动检测是否异步工具permissionslist[]允许访问的角色/Agent 列表自动生成AccessPolicy.roles_only(...)rate_limitstrNone限流串如10/minute、100/hourretry_policyRetryPolicyNone自动重试策略health_checkHealthCheckNone健康检查access_policyAccessPolicyNone细粒度访问控制deprecatedboolFalse是否废弃该版本deprecated_messagestrNone废弃迁移指引高级用法示例来自 decorator.py 与包文档from atr import register, RetryPolicy, inject register( namepdf_parser, version1.0.0, async_True, rate_limit10/minute, permissions[claims-agent], retry_policyRetryPolicy(max_attempts3, backoffexponential), ) async def pdf_parser(file_path: str, config: Config inject()) - dict: Parse a PDF document. ...ToolSpecPydantic 强类型规格与 Schema 导出ToolSpec是整个 ATR 的数据核心见 schema.py由三部分组成metadata: ToolMetadata名称、描述、版本、作者、成本等级、副作用、标签、is_async、权限、限流、废弃标记parameters: List[ParameterSpec]每个参数的名字、类型、描述、是否必填、默认值以及 array 的items、object 的properties、枚举的enumreturns: Optional[ParameterSpec]返回值规格。ParameterSpec内置一条校验规则必填参数不能设置默认值validate_default会在两者冲突时抛错确保 Schema 语义自洽。导出为 LLM 函数调用格式spec atr.get_tool(calculator) # OpenAI Function Calling 格式 openai_schema spec.to_openai_function_schema() # - {name: ..., description: ..., parameters: {type: object, # properties: {...}, required: [...]}} # Anthropic Tool Use 格式 anthropic_schema spec.to_anthropic_tool_schema() # - {name: ..., description: ..., input_schema: {...}}这两个方法把ToolSpec翻译为标准 JSON Schema 风格的函数描述是 Agent 与 LLM 之间函数调用Function Calling的桥接层。配合search_tools/list_toolsAgent 可以在运行时动态把全部可用工具批量导出给模型实现能力即插即用。预置安全工具集Safe Toolkit仓库还提供了一批预配置的安全工具通过 atr/tools/safe/toolkit.py 的create_safe_toolkit(preset, config)工厂按预设创建预设包含工具安全边界minimalcalculator、datetime、text无任何 I/Ostandardhttp、files、json、calculator、datetime、text合理默认限制restricted全部工具必须显式指定域名/路径限流更低、体积更小readonlyfiles、json、calculator、datetime、text无网络networkhttp无文件访问例如restricted预设要求allowed_domains[]、sandbox_paths[]必须由调用方显式配置HTTP 限流降至 10 次、响应体上限 1MB文件读取默认关闭符号链接follow_symlinksFalse。这些工具类是受限工具集的最佳实践模板配合 ATR 的沙箱执行可以构建纵深防御。沙箱执行Docker 隔离运行不可信代码SDLC Agent 和 LLM 可能生成你不能安全地在宿主机直接运行的 Python 或 Bash 脚本。ATR 的DockerExecutor让这类代码在一次性容器中执行。为什么需要沙箱执行隔离Isolation代码运行在临时容器中与宿主机完全隔离安全Security无网络访问、内存受限、自动清理安全Safety防御恶意代码、资源耗尽resource exhaustion和意外副作用。使用方式import atr from atr import DockerExecutor atr.register(nameprocessor, tags[data]) def process_data(numbers: list) - int: Process data safely in a sandbox. return sum(numbers) # Option 1: Direct execution (NOT sandboxed - trusted code only) result atr.execute_tool(processor, {numbers: [1, 2, 3, 4]}) # Option 2: Sandboxed execution (RECOMMENDED for untrusted code) docker_exec DockerExecutor() result atr.execute_tool( processor, {numbers: [1, 2, 3, 4]}, executordocker_exec, timeout30 )execute_tool(name, args, executor, timeout)是便捷函数不传 executor 时默认使用LocalExecutor宿主机直跑仅限可信代码传入DockerExecutor即进入沙箱模式见init.py。执行模式对比特性LocalExecutorDockerExecutor速度快较慢容器化安全性无隔离完全隔离网络完全可访问禁用资源限制无可配置清理不适用自动适用场景可信代码不可信代码DockerExecutor 实现细节从 executor.py 可以看到完整的沙箱链路序列化函数源码用inspect.getsource提取函数定义剥离装饰器、反缩进内置函数/lambda 因拿不到源码会报ExecutorError生成执行脚本将参数 JSON 序列化嵌入脚本用__RESULT_START__/__RESULT_END__标记包裹结果输出启动临时容器默认镜像python:3.9-slimauto_pullTrue时自动拉取通过卷挂载把脚本以只读方式传入/app关键安全参数为network_modenone禁用网络mem_limit512m内存上限 512MB执行后强制stopremove自动清理容器超时控制container.wait(timeouttimeout)超时抛出ExecutionTimeoutError结果解析从日志中提取标记间 JSON成功返回result失败抛ExecutorError并携带容器日志。沙箱执行最佳实践来自 sandbox_demo.py对不可信或 Agent 生成的代码始终使用 DockerExecutor设置合理的 timeout 防止执行挂起LocalExecutor 只用于可信、预先审查过的代码生产环境监控 Docker 资源使用考虑使用依赖最少的自定义 Docker 镜像上线前先在 Docker 中测试你的工具。策略引擎重试、限流、健康检查与访问控制ToolHandle之所以是生产级执行入口是因为它在执行前自动叠加四类策略见 schema.py 与 policies.py限流RateLimitPolicyrate_limit10/minute会解析为令牌桶策略超限抛RateLimitExceeded支持同步acquire与异步acquire_async重试RetryPolicymax_attempts含首次、backoffconstant/linear/exponential/fibonacci、initial_delay、max_delay、jitter随机抖动防惊群、retry_on指定可重试的异常类型以及on_retry回调提供with_retry/with_retry_async依赖注入配置container后InjectionResolver会解析inject()标记的参数指标采集每次调用记录latency_ms、success、error、rate_limited到MetricsCollector。此外还有HealthCheckCallableHealthCheck/HttpHealthCheck/TcpHealthCheck支持check()/check_async()与AccessPolicyPrincipal/Permission/AccessControlManager分别用于工具可用性探活与细粒度授权。测试 test_v2_features.py 覆盖了这些增强特性的行为。架构定位与生态地图atr位于Agent OS 栈的第 2 层Infrastructure。职责工具注册、发现与 Schema 生成。不负责工具执行由 Agent Control Plane 处理——The registry stores specifications, not callables. Execution happens in the control plane with proper error handling and observability.设计要点注册表基于内存字典的轻量查找本地或分布式装饰器atr.register()提取类型签名并强制严格类型检查规格Pydantic Schema 强制校验输入、输出、副作用与元数据Schema 导出转换为 OpenAI、Anthropic 及其他 LLM 函数调用格式。在 Agent OS 生态中的位置ATR 是一个模块化 Agent OS 中的组件每一层解决一个特定问题PrimitivesLayer 1caasContext-as-a-ServiceAgent 记忆与状态管理、cmvkContext Verification Kit上下文完整性密码学验证见 modules/cmvk、emkEpisodic Memory Kit长期记忆存取InfrastructureLayer 2iatpInter-Agent Trust Protocol安全消息认证见 modules/iatp、ambAgent Message Bus解耦事件传输见 modules/amb、atrAgent Tool Registry工具发现与 Schema 生成即本模块FrameworkLayer 3agent-control-planeAgent 编排与生命周期管理见 modules/control-plane、scakSelf-Correction Agent Kit自动化错误恢复与学习。这种分层设计让 ATR 只做工具能力的注册表把执行、编排、信任交给相邻层正是Scale by Subtraction在能力层capability layer的落地。测试与验证模块自带完整测试套件位于 tests/通过pytest运行配置了覆盖率统计test_decorator.py装饰器类型映射、参数/返回类型提取、无类型注解报错、函数原样保留、装饰不执行、非法 cost/side_effect 回退test_registry.py注册/查询/版本约束/废弃/搜索/异常路径test_schema.pyToolSpec 校验与 OpenAI/Anthropic Schema 导出test_executor.py 与 test_integration_executor.py本地/沙箱执行与超时test_v2_features.py限流、重试、注入等增强特性。模块另附 CHANGELOG.md、IMPLEMENTATION_SUMMARY.md 与 docs/PYPI_SETUP.md可进一步了解演进历史与发布配置。引用与许可如果在研究中使用 ATR请引用software{atr2024, title{ATR: Agent Tool Registry}, author{Siddique, Imran}, year{2024}, note{Part of the Agent OS ecosystem} }ATR 采用 MIT 许可详见仓库根目录 LICENSE。小结ATRAgent Tool Registry是 Agent OS 基础设施层中能力解耦的关键一环它以注册表只存规格、执行交给控制平面的边界划分通过atr.register()自动把带类型注解的 Python 函数转化为 Pydantic 强校验的ToolSpec原生导出 OpenAI / Anthropic 函数调用 Schema并提供版本约束、标签检索、废弃管理、重试/限流/健康检查/访问控制等治理策略最后用DockerExecutor为不可信代码提供无网络、限内存、自动清理的隔离沙箱。对于需要在 Agent 体系中构建可动态扩展、可治理的工具能力层的开发者这套注册-发现-导出-沙箱执行的完整链路可以直接作为生产方案参考。【免费下载链接】agent-governance-toolkitAI Agent Governance Toolkit — Policy enforcement, zero-trust identity, execution sandboxing, and reliability engineering for autonomous AI agents. Covers 10/10 OWASP Agentic Top 10.项目地址: https://gitcode.com/GitHub_Trending/ag/agent-governance-toolkit创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进