Skip to main content
Glama

通用智能体经济操作系统 (UAE OS)

Python 版本 许可证 覆盖率 版本

通用智能体经济操作系统 (UAE OS) 是一个基础的、MCP/A2A 原生的核心平台,旨在为蓬勃发展的智能体子经济提供动力。它最初作为一个安全凭证注入和 x402 微支付代理,并逐步演进为一个完整的多垄断帝国(身份引擎、支付、结算、合规包、垂直市场)。

这个 v0 代理骨架是未来所有模块都将基于其扩展的坚实基础。它完全兼容 模型上下文协议 (MCP)智能体间 (A2A) 通信,允许自主智能体在无需人工干预的情况下安全地发现、验证彼此并进行支付。


Python SDK 快速入门

与 UAE OS 交互的最简单方式是通过官方 Python SDK。它提供了强大的连接池、针对瞬时错误(429, 5xx)的自动指数退避重试机制,以及直接映射到 UAEError 系统的结构化异常处理。

1. 安装

直接从仓库根目录安装 SDK:

pip install -e .

2. 基本用法与错误处理

import asyncio
from sdk.uaeos import UAEOSClient
from sdk.uaeos.client import RateLimitError, AuthError, InsufficientScopesError, APIError

async def main():
    # Initialize the client with your API key (uses async context manager for connection pooling)
    # The client automatically retries transient errors (max_retries=3 by default)
    async with UAEOSClient(api_key="sk_test_1234567890abcdef", base_url="http://127.0.0.1:8000") as client:
        try:
            # 1. Register a new agent in the Identity Engine
            agent = await client.register_agent(
                agent_id="agent_sdk_1", 
                name="SDK Test Agent", 
                metadata={"version": "1.0"}
            )
            print("Registered:", agent)
            
            # 2. Rotate/Issue a credential with cryptographic scopes
            cred = await client.rotate_credential(
                agent_id="agent_sdk_1",
                credential_type="stripe_live",
                new_secret_data={"api_key": "sk_live_new123"},
                expires_in_days=30
            )
            print("Credential Rotated:", cred)
            
            # 3. Execute an MCP/A2A tool call with x402 micropayment
            result = await client.execute(
                agent_id="agent_sdk_1",
                tool_call={
                    "target_agent_id": "agent_target_2",
                    "action": "process_data",
                    "payload": {"hello": "world"},
                    "required_scopes": ["read"]
                },
                credential_type="stripe_live",
                payment_amount=1.50
            )
            print("Execution Result:", result)
            
            # 4. Execute a direct A2A payment (no downstream HTTP call)
            payment_result = await client.execute_payment(
                agent_id="agent_sdk_1",
                payment_amount=5.00,
                target_agent_id="agent_target_3",
                action="data_purchase"
            )
            print("Payment Result:", payment_result)
            
            # 5. Get Usage Stats from the Analytics Engine
            stats = await client.get_stats()
            print("Global Stats:", stats)
            
            # 6. Generate a usage-based invoice for the agent
            invoice = await client.get_invoice(agent_id="agent_sdk_1")
            print("Generated Invoice:", invoice)
            
        except RateLimitError as e:
            # Raised if the agent exceeds the rate limit and max_retries are exhausted
            print(f"Rate limited! Retry after {e.retry_after} seconds. Request ID: {e.request_id}")
        except InsufficientScopesError as e:
            # Raised if the agent lacks the required scopes for the credential
            print(f"Permission denied: {e.message}")
        except AuthError:
            # Raised for 401 Unauthorized
            print("Invalid API Key!")
        except APIError as e:
            # Catch-all for other 4xx/5xx errors or network issues
            print(f"API Error ({e.status_code}): {e.message}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    asyncio.run(main())

v0.1 发布说明

欢迎使用通用智能体经济操作系统的基础版本!在过去的 30 天里,我们构建了一个高度模块化、生产就绪的代理骨架,作为 MCP/A2A 网络的核心路由器。

v0.1.0 功能特性:

  • FastAPI + Pydantic v2 核心:严格类型化、高性能的 API 网关。

  • 身份引擎:集成 Supabase,用于安全凭证查找、注入、轮换和加密范围验证。

  • 结算引擎:x402 微支付处理、Stripe/Lightning Webhook 验证以及基于用量的账单发票生成。

  • A2A 路由:智能体间路由存根,支持下游执行 (httpx)。

  • 合规包:审计日志记录和唯一的 adt_ ID 生成。

  • 流量控制:支持 Redis 的速率限制(10 次请求/分钟),并提供正确的 429 响应。

  • 缓存:支持 Redis 的凭证和范围身份缓存层。

  • 安全性:API 密钥认证 (Authorization: BearerX-API-Key)、CORS 中间件、自定义安全标头以及结构化错误报告 (UAEError)。

  • 用量分析仪表板:线程安全的内存中用量跟踪、近期活动日志以及全局 /stats 仪表板。

  • Python SDK:官方的、优先异步的 Python 客户端 (UAEOSClient),具备连接池、指数退避重试和结构化错误处理。

  • 配置:集中式 Pydantic 设置 (app/config.py) 作为单一事实来源。

  • 部署就绪:已 Docker 化,并针对 Railway 一键部署进行了优化。

  • 100% 测试覆盖率:完全模拟的综合测试套件,包含 82 个集成测试。


快速入门(本地服务器)

  1. 安装依赖

    pip install -r requirements.txt
  2. 配置环境.env.example 复制到 .env 并填写您的 Supabase 详细信息(本地模拟可选)。

    cp .env.example .env
  3. 运行服务器

    uvicorn app.main:app --reload

    API 将在 http://127.0.0.1:8000 可用。查看 http://127.0.0.1:8000/docs 获取交互式 Swagger UI。

  4. 运行测试

    pytest -v

快速入门(Docker)

要在隔离容器中运行代理:

  1. 构建镜像

    docker build -t uae-os-proxy .
  2. 运行容器

    docker run -p 8000:8000 --env-file .env uae-os-proxy

环境变量

应用程序完全通过环境变量(由 app/config.py 管理)进行配置。详情请参阅 .env.example

变量

默认值

描述

API_KEY

(必填)

访问受保护端点所需的主 API 密钥。

WEBHOOK_SECRET

(必填)

用于验证传入 Webhook 的 HMAC 签名的密钥。

SUPABASE_URL

""

您的 Supabase 项目 URL(用于凭证查找)。

SUPABASE_KEY

""

您的 Supabase 匿名或服务角色密钥。

ALLOWED_ORIGINS

["*"]

允许的 CORS 源的 JSON 数组。

STRIPE_API_KEY

""

用于真实 Stripe 集成的密钥。

LIGHTNING_ENABLED

False

启用 Lightning 网络微支付。

BILLING_RATE_PER_CALL

0.01

基于用量的计费中,每次 API 调用应用的固定费率。

RATE_LIMIT_MAX_REQUESTS

10

智能体在窗口期内可发出的最大请求数。

RATE_LIMIT_WINDOW_SECONDS

60

速率限制的时间窗口(秒)。

REDIS_URL

""

Redis 连接字符串(例如 redis://localhost:6379)。留空则使用内存后备。

注意:如果缺少 Supabase 变量,应用程序将优雅地回退到模拟模式以供测试。


API 使用示例 (cURL)

代理端点 (/proxy/execute) 受保护,需要您的 API_KEY。您可以使用标准的 Authorization: Bearer <key> 标头或 X-API-Key: <key> 标头进行身份验证。

1. 基本工具调用(无支付)

使用 cURL (Bearer Token):

curl -X POST http://127.0.0.1:8000/proxy/execute \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_test_1234567890abcdef" \
  -d '{
    "agent_id": "agent_alpha",
    "tool_call": {
      "url": "https://api.example.com/v1/data",
      "method": "POST",
      "payload": {"query": "test"}
    },
    "credential_type": "stripe_live"
  }'

2. 带有 x402 微支付的 MCP/A2A 工具调用

要模拟结算并路由到另一个智能体,请包含 payment_amounttarget_agent_id 字段。

curl -X POST http://127.0.0.1:8000/proxy/execute \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_test_1234567890abcdef" \
  -d '{
    "agent_id": "agent_beta",
    "tool_call": {
      "target_agent_id": "agent_gamma",
      "action": "premium_data_fetch"
    },
    "credential_type": "custom_oauth",
    "payment_amount": 0.50
  }'

预期响应:

{
  "success": true,
  "injected_credential": true,
  "x402_settled": true,
  "transaction_id": "tx_a1b2c3d4e5f6",
  "audit_id": "adt_9876543210abcdef"
}

部署(零成本 / 一键式)

Dockerfile 针对现代 PaaS 提供商进行了优化。它使用轻量级的 Python 3.11 slim 镜像,暴露 8000 端口,并绑定到 0.0.0.0

部署到 Railway (推荐)

Railway 提供无缝的一键部署体验,可自动读取包含的 railway.tomlDockerfile

  1. 推送到 GitHub:将此仓库提交到 GitHub 仓库。

  2. 连接 Railway:登录 Railway 并点击 New Project -> Deploy from GitHub repo

  3. 选择仓库:选择您刚推送的仓库。

  4. 设置环境变量:在 Railway 项目仪表板中,转到 Variables 标签页并添加您的 API_KEYWEBHOOK_SECRET 以及任何可选的 Supabase/Stripe 密钥。确保在生产环境中为密钥生成强随机字符串。

  5. 部署:Railway 将自动检测 railway.toml 文件,构建 Docker 镜像并进行部署。

预期实时 URL 模式: https://agent-economy-os-production.up.railway.app

生产监控与验证

部署后,您可以使用公共端点验证服务是否正在运行并监控其健康状况。这些是建议用于 PaaS 健康检查的端点:

  • 健康检查https://agent-economy-os-production.up.railway.app/health

    • 返回基本状态、版本和时间戳。

  • 指标https://agent-economy-os-production.up.railway.app/metrics

    • 返回正常运行时间和已计量的智能体总数。

注意:由于当前的速率限制和缓存是在内存中的,请确保您的 PaaS 配置为运行单个实例/副本(免费层级的默认设置),直到完全集成 Redis。

Stripe Webhook 设置

要为实时 Stripe 支付启用实时结算跟踪,请在 Stripe 仪表板中配置 Webhook:

  1. 转到 Stripe 仪表板中的 Developers > Webhooks

  2. 点击 Add endpoint

  3. Endpoint URL 设置为 https://agent-economy-os-production.up.railway.app/webhooks/stripe

  4. 选择 Events to sendpayment_intent.succeededpayment_intent.payment_failed

  5. 点击 Add endpoint

  6. 显示 Signing secret(以 whsec_ 开头)并将其作为 STRIPE_WEBHOOK_SECRET 添加到您的 Railway 环境变量中。


贡献

我们欢迎贡献!通用智能体经济操作系统旨在成为智能体经济的权威开源标准。

请确保在提交 Pull Request 之前所有测试通过 (pytest -v) 且覆盖率保持在 100%。如果您要添加新模块,请确保它在现有架构上进行复合,而不会破坏核心代理执行流程。

-
security - not tested
A
license - permissive license
-
quality - not tested

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sommerhussain/agent-economy-os'

If you have feedback or need assistance with the MCP directory API, please join our Discord server