dApp Docs/AI Agent 正式 API 规格与合约接口消费指南
Development reference. Not independently verified for production.

AI Agent 正式 API 规格与合约接口消费指南

基于 MSG Chain developer_entry.json → api_specs/index.json 引导的真实规格包。
所有文件均可在 https://msgchain.org/whitepaper/api_specs/ 下直接访问。
schema_version: v1 | generated_by: msg_whitepaper_pipeline_v1
本指南使用 msg 前缀标识 MSG Chain 原生概念。

⚠️ No-Go Disclaimer: MSGChain 主网裁决为 No-Go。本文件所有内容反映的是开发阶段的技术设计,不代表主网未独立核验上线状态。生产部署状态请以白皮书为准:https://msgchain.org/whitepaper/


目录

  1. 概述
  2. API 规格索引
  3. 正式合约接口
  4. RPC 方法定义
  5. 错误码定义
  6. OpenAPI 规格
  7. AI Agent 消费模式
  8. 边界声明

1. 概述

1.1 什么是 api_specs

api_specs/ 是 MSG Chain 白皮书系统为 AI Agent 和第三方知识爬虫准备的机器可读 API 规格包。它位于 developer_entry.json 的 bootstrap 引导顺序中,是 AI Agent 接入 MSG 链的核心契约层。

# bootstrap 路径
developer_entry.json
  └── entry_points.api_specs_index_json → api_specs/index.json
        ├── formal_contracts.json       # 正式合约接口索引
        ├── rpc_methods.json            # RPC 方法定义
        ├── error_codes.json            # 错误码定义
        └── openapi/
              ├── public_query.yaml      # 公共查询 OpenAPI
              ├── contract_surface.yaml  # 合约交互面 OpenAPI
              └── agent_surface.yaml     # Agent API 面 OpenAPI

1.2 规格包文件清单

# 文件 描述 机器就绪度
1 index.json 规格包主索引,列出 7 个入口文件 public_stable
2 formal_contracts.json 正式合约接口索引,source-backed source_backed_reference
3 rpc_methods.json RPC/REST/Agent/Explorer 方法族摘要 assisted_codegen
4 error_codes.json 机器提示:stub、受保护、治理门禁响应 public_stable
5 openapi/public_query.yaml 公共查询面 OpenAPI public_stable
6 openapi/contract_surface.yaml 合约部署/实例化/执行面 OpenAPI public_stable
7 openapi/agent_surface.yaml Agent 查询与受保护写面 OpenAPI public_stable

1.3 机器就绪度等级 (machine_readiness)

根据 developer_capability_matrix.json,MSG 定义了以下就绪度等级:

1.4 关键入口点

API_SPECS_BASE = 'https://msgchain.org/whitepaper/api_specs'

INDEX = f'{API_SPECS_BASE}/index.json'
FORMAL_CONTRACTS = f'{API_SPECS_BASE}/formal_contracts.json'
RPC_METHODS = f'{API_SPECS_BASE}/rpc_methods.json'
ERROR_CODES = f'{API_SPECS_BASE}/error_codes.json'
PUBLIC_QUERY_OPENAPI = f'{API_SPECS_BASE}/openapi/public_query.yaml'
CONTRACT_SURFACE_OPENAPI = f'{API_SPECS_BASE}/openapi/contract_surface.yaml'
AGENT_SURFACE_OPENAPI = f'{API_SPECS_BASE}/openapi/agent_surface.yaml'
# agent_entry.json 中的推荐爬取顺序
recommended_crawl_order = [
    'index.html',
    'modules/knowledge_network.html',
    'knowledge_network.json',
    'module_exports/index.json',
    # ...
    'api_specs/index.json',
    'api_specs/formal_contracts.json',
    'api_specs/rpc_methods.json',
    'api_specs/error_codes.json',
    'api_specs/openapi/public_query.yaml',
    'api_specs/openapi/contract_surface.yaml',
    'api_specs/openapi/agent_surface.yaml',
    # ...
]

2. API 规格索引

2.1 index.json

index.json 是整个规格包的入口。它列出了所有 7 个文件及其描述。

真实内容:

{
  "schema_version": "v1",
  "generated_by": "msg_whitepaper_pipeline_v1",
  "files": [
    {
      "id": "rpc_methods",
      "path": "api_specs/rpc_methods.json",
      "public_url": "https://msgchain.org/whitepaper/api_specs/rpc_methods.json",
      "description": "Current machine-readable summary of RPC, REST, Agent, contract, and Explorer method families."
    },
    {
      "id": "error_codes",
      "path": "api_specs/error_codes.json",
      "public_url": "https://msgchain.org/whitepaper/api_specs/error_codes.json",
      "description": "Machine hints for interpreting stub, guarded, governance-gated, and non-final responses."
    },
    {
      "id": "openapi_public_query",
      "path": "api_specs/openapi/public_query.yaml",
      "public_url": "https://msgchain.org/whitepaper/api_specs/openapi/public_query.yaml",
      "description": "OpenAPI summary for public read/query surfaces."
    },
    {
      "id": "openapi_contract_surface",
      "path": "api_specs/openapi/contract_surface.yaml",
      "public_url": "https://msgchain.org/whitepaper/api_specs/openapi/contract_surface.yaml",
      "description": "OpenAPI summary for contract deploy/instantiate/execute surfaces."
    },
    {
      "id": "openapi_agent_surface",
      "path": "api_specs/openapi/agent_surface.yaml",
      "public_url": "https://msgchain.org/whitepaper/api_specs/openapi/agent_surface.yaml",
      "description": "OpenAPI summary for agent query and guarded write surfaces."
    },
    {
      "id": "formal_contracts",
      "path": "api_specs/formal_contracts.json",
      "public_url": "https://msgchain.org/whitepaper/api_specs/formal_contracts.json",
      "description": "Source-backed API and contract schema contract index derived from repo manifests, OpenAPI files, and release-level developer packs."
    }
  ],
  "metadata_profile": "public_stable"
}

2.2 AI Agent 发现规格包

import httpx
from typing import Any

API_SPECS_INDEX = 'https://msgchain.org/whitepaper/api_specs/index.json'

async def msg_discover_api_specs() -> dict[str, Any]:
    """发现 api_specs 中的所有规格文件"""
    async with httpx.AsyncClient() as client:
        resp = await client.get(API_SPECS_INDEX)
        resp.raise_for_status()
        index = resp.json()
    
    files = index.get('files', [])
    base = 'https://msgchain.org/whitepaper'
    
    return {
        'schema_version': index.get('schema_version'),
        'entries': [
            {
                'id': f['id'],
                'path': f['public_url'],
                'description': f.get('description', ''),
            }
            for f in files
        ],
        'metadata_profile': index.get('metadata_profile'),
    }

# 使用示例
# specs = await msg_discover_api_specs()
# for entry in specs['entries']:
#     print(f"{entry['id']}: {entry['path']}")

2.3 文件加载器

async def msg_load_spec(spec_id: str) -> dict[str, Any] | None:
    """按 spec_id 加载规格文件内容"""
    base = 'https://msgchain.org/whitepaper/api_specs'
    paths = {
        'formal_contracts': f'{base}/formal_contracts.json',
        'rpc_methods': f'{base}/rpc_methods.json',
        'error_codes': f'{base}/error_codes.json',
    }
    path = paths.get(spec_id)
    if not path:
        return None
    async with httpx.AsyncClient() as client:
        resp = await client.get(path)
        resp.raise_for_status()
        return resp.json()

# 使用示例
# rpc = await msg_load_spec('rpc_methods')
# for family in rpc['families']:
#     print(family['family_id'], family['status'])

3. 正式合约接口

3.1 formal_contracts.json 概述

formal_contracts.json 是 MSG 链的正式 API/Schema 契约索引。它位于 api_specs/ 目录下,是 source_backed_reference 级别的规格——比白皮书摘要更接近真实源码与 release manifest,但仍不能越级宣称 public production API 已完成。

生产支持: False

{
  "schema_version": "v1",
  "generated_by": "msg_whitepaper_pipeline_v1",
  "pack_id": "formal_api_and_schema_contracts",
  "scope": "Release-level API schema pack manifest for external AI agent onboarding, Web3 dApp development, receipt/event parsing, and fail-closed production discovery."
}

3.2 source_backed 文件清单

formal_contracts.json 引用以下 source_backed 文件:

ID 文件 描述
agent_openapi api_specs/source_backed/agent_openapi.json Agent API AI-6 面 OpenAPI
tool_manifest api_specs/source_backed/tool_manifest.json AI-6 工具清单 (OpenAI tool format)
mcp_manifest api_specs/source_backed/mcp_manifest.json MCP 兼容工具清单
rest_swagger api_specs/source_backed/rest_swagger.yaml REST 面 Swagger
developer_openapi api_specs/source_backed/developer_openapi.yaml 开发者面 OpenAPI
developer_swagger api_specs/source_backed/developer_swagger.yaml 开发者面 Swagger
core_contracts contract_reference/core_contracts.json 核心合约消费索引
ai1_contract_schema_manifest contract_reference/ai1_contract_schema_manifest.json AI-1 合约 Schema 清单
developer_api_schema_pack_manifest release_pack/developer_api_schema_pack_manifest.json 开发者 API Schema 发布包
developer_contract_schema_abi_pack_manifest release_pack/developer_contract_schema_abi_pack_manifest.json 开发者合约 Schema ABI 发布包

3.3 必需合约

"required_contracts": [
    "counter_v1",
    "genesis_registry_v1",
    "agent_registry_v1",
    "micropayment_session_v1",
    "agent_payment_v1"
]

每个合约的用途:

合约 用途
counter_v1 计数器合约,最小参考实现
genesis_registry_v1 创世注册中心,维护 canonical key → 合约地址映射
agent_registry_v1 AI Agent 注册中心,维护 agent_id → 能力/状态
micropayment_session_v1 微支付会话管理
agent_payment_v1 Agent 支付结算协议

3.4 必需公共错误码

"required_common_error_codes": [
    0, 1001, 1002, 3001, 4001, 5001, 5005, 5006, 5007, 9999
]
Code 名称 含义
0 success 成功
1001 invalid_params 无效参数
1002 invalid_address 无效地址
3001 contract_not_found 合约未找到
4001 tx_not_found 交易未找到
5001 auth_failed 认证失败
5005 policy_denied 策略拒绝
5006 kill_switch_active 紧急开关激活
5007 duplicate_request 重复请求
9999 internal_error 内部错误

3.5 source_backed/agent_openapi.json 详解

title: MSG Chain Agent API AI-6 Surface
version: 1.2.0-ai-pay
server: http://localhost:8081 (本地 Q1/Q2 API 服务器)

核心元数据

x-msg-ai6:
  capability_boundary: "OpenAPI lists routable Agent API endpoints only."
  stub_marker: "Stub responses set X-MSG-Stub=true and data.implemented=false."
  write_auth:
    api_key_header: "X-API-Key"
    policy_header: "X-Agent-Policy-ID"
    scope_header: "X-Agent-Scope"
    idempotency_header: "Idempotency-Key"
    production_without_keys: fail-closed
  agent_constitution:
    required: true
    canonical_key: "ai_agent_constitution_v1"
    production_enforcement_status: check_action_preflight_available
  agent_payment:
    native_protocol: "msg-agent-payment-intent-v1"
    default_trust_boundary: "MSG native payment intent and settlement receipt are the default trust root"
    production_private_key_policy: "AI Runtime must not receive cleartext private keys"

路由分类 (x-msg-agent-route-classification)

- pattern: /agent/v1/query/account/
  access: public_read
  status: implemented

- pattern: /agent/v1/query/balance/
  access: public_read
  status: implemented

- pattern: /agent/v1/query/balances
  access: public_read
  status: implemented

- pattern: /agent/v1/query/tx/
  access: public_read
  status: implemented

- pattern: /agent/v1/query/block/
  access: public_read
  status: implemented

- pattern: /agent/v1/events/history
  access: public_read
  status: implemented

- pattern: /agent/v1/events/subscribe
  access: public_read
  status: implemented

- pattern: /agent/v1/registry/discover
  access: public_read
  status: implemented

- pattern: /agent/v1/registry/list
  access: public_read
  status: implemented

- pattern: /agent/v1/wallet/
  access: protected_write
  status: implemented

- pattern: /agent/v1/wallet/transfer
  access: protected_write
  status: implemented

- pattern: /agent/v1/mpc/sign
  access: protected_write
  status: implemented

- pattern: /agent/v1/registry/register
  access: protected_write
  status: implemented

- pattern: /agent/v1/constitution/acknowledge
  access: protected_write
  status: implemented

- pattern: /agent/v1/payment/session
  access: protected_write
  status: implemented

响应 Schema

AgentResponse:
  type: object
  required:
    - code
    - status
    - error_code
    - message
    - request_id
    - audit_id
    - time
    - timestamp
  properties:
    code: integer
    status: string (enum: success, error, stub)
    error_code: integer
    message: string
    data: object
    error: string
    request_id: string
    audit_id: string
    time: string (date-time)
    timestamp: string (date-time)

受保护写路径的安全头部

security:
  - AgentApiKey: []
parameters:
  - name: X-API-Key
    in: header
    required: true
  - name: X-Agent-Policy-ID
    in: header
    required: true
  - name: X-Agent-Scope
    in: header
    required: true
  - name: Idempotency-Key
    in: header
    required: true
  - name: X-Agent-ID
    in: header
    required: true (constitution preflight)
  - name: X-Agent-Constitution-Version
    in: header
    required: true
  - name: X-Agent-Constitution-Hash
    in: header
    required: true
  - name: X-Agent-AIDID
    in: header
    required: false
  - name: X-Agent-Budget-ID
    in: header
    required: false
  - name: X-Agent-Signer-ID
    in: header
    required: false
  - name: X-Agent-Receipt-ID
    in: header
    required: false

3.6 source_backed/tool_manifest.json 详解

manifest_id: msg-ai6-tool-manifest-ai-pay
version: 1.2.0-ai-pay

状态值定义

{
  "implemented": "Routable and backed by current node code.",
  "implemented_protected": "Routable write endpoint protected by API key, policy, scope and idempotency checks.",
  "implemented_local": "Routable but local/in-process only; not a full chain settlement proof.",
  "stub": "Routable but marked by X-MSG-Stub=true and data.implemented=false.",
  "available_via_rest": "Available through non-Agent REST/RPC route, not native /agent/v1.",
  "planned": "Machine schema reserved; endpoint or contract path is not implemented yet.",
  "blocked": "Schema reserved but final execution is blocked by listed evidence gate."
}

公共头部

{
  "read": ["X-Request-ID"],
  "write": ["X-API-Key", "X-Agent-Policy-ID", "X-Agent-Scope", "Idempotency-Key", "X-Request-ID"],
  "constitution_preflight_write": [
    "X-Agent-ID", "X-Agent-Constitution-Version", "X-Agent-Constitution-Hash",
    "X-Agent-AIDID", "X-Agent-Budget-ID", "X-Agent-Signer-ID",
    "X-Agent-Receipt-ID", "X-Agent-Proof-ID"
  ]
}

必需工具分类

["query", "execute", "wallet", "governance", "registry", "treasury", "gas", "validator", "ai_registry"]

工具清单 (tools) 示例

{
  "name": "msg_query_account",
  "category": "query",
  "status": "implemented",
  "method": "GET",
  "path": "/agent/v1/query/account/{address}",
  "scope": "query:read",
  "input_schema": {
    "type": "object",
    "required": ["address"],
    "properties": {
      "address": {"type": "string", "pattern": "^msg"}
    }
  },
  "response_schema": {"$ref": "..."},
  "idempotency": null,
  "errors": [1001, 1002, 9999],
  "payment": {
    "price_model": "free_or_rate_limited",
    "budget_required": false,
    "risk_level": "low"
  }
}
{
  "name": "msg_wallet_transfer",
  "category": "wallet",
  "status": "implemented_protected",
  "method": "POST",
  "path": "/agent/v1/wallet/transfer",
  "scope": "wallet:write",
  "idempotency": {"required": true, "header": "Idempotency-Key"},
  "constitution_preflight": {
    "required": true,
    "status": "implemented_when_required",
    "check_action": true,
    "fail_closed": true
  },
  "errors": [1001, 1002, 5001, 5002, 5005, 5006, 5007, 9999],
  "payment": {
    "price_model": "gas_metered_msg",
    "budget_required": true,
    "risk_level": "high",
    "settlement_receipt": {
      "required": true,
      "fields": ["tx_hash", "height", "events", "gas_used", "payer", "payee", "amount", "asset", "audit_id"]
    }
  }
}
{
  "name": "msg_governance_proposal_create",
  "category": "governance",
  "status": "blocked",
  "blocked_by": ["1.5-1 live DAO owner voting power", "P3-1 governance live closure"]
}

3.7 AI Agent 合约消费

MSG_FORMAL_CONTRACTS = 'https://msgchain.org/whitepaper/api_specs/formal_contracts.json'
MSG_AGENT_OPENAPI = 'https://msgchain.org/whitepaper/api_specs/source_backed/agent_openapi.json'
MSG_TOOL_MANIFEST = 'https://msgchain.org/whitepaper/api_specs/source_backed/tool_manifest.json'
MSG_MCP_MANIFEST = 'https://msgchain.org/whitepaper/api_specs/source_backed/mcp_manifest.json'


class msgFormalContractConsumer:
    """正式合约接口消费者 - AI Agent 消费入口"""

    def __init__(self):
        self.base = 'https://msgchain.org/whitepaper'
        self.session = httpx.AsyncClient()

    async def load_formal_contracts(self) -> dict:
        resp = await self.session.get(f'{self.base}/api_specs/formal_contracts.json')
        return resp.json()

    async def load_agent_openapi(self) -> dict:
        resp = await self.session.get(f'{self.base}/api_specs/source_backed/agent_openapi.json')
        return resp.json()

    async def load_tool_manifest(self) -> dict:
        resp = await self.session.get(f'{self.base}/api_specs/source_backed/tool_manifest.json')
        return resp.json()

    async def load_mcp_manifest(self) -> dict:
        resp = await self.session.get(f'{self.base}/api_specs/source_backed/mcp_manifest.json')
        return resp.json()

    async def list_required_contracts(self) -> list[str]:
        contracts = await self.load_formal_contracts()
        return contracts.get('required_contracts', [])

    async def list_implemented_tools(self) -> list[dict]:
        manifest = await self.load_tool_manifest()
        return [t for t in manifest.get('tools', []) if t['status'] == 'implemented']

    async def list_protected_tools(self) -> list[dict]:
        manifest = await self.load_tool_manifest()
        return [t for t in manifest.get('tools', []) if t['status'] == 'implemented_protected']

    async def list_tools_by_category(self, category: str) -> list[dict]:
        manifest = await self.load_tool_manifest()
        return [t for t in manifest.get('tools', []) if t.get('category') == category]

    async def get_tool_errors(self, tool_name: str) -> list[int]:
        manifest = await self.load_tool_manifest()
        for tool in manifest.get('tools', []):
            if tool['name'] == tool_name:
                return tool.get('errors', [])
        return []

    async def get_write_headers(self) -> dict:
        """获取受保护写路径必需的请求头部"""
        return {
            'X-API-Key': '<api-key>',
            'X-Agent-Policy-ID': '<policy-id>',
            'X-Agent-Scope': '<scope>',
            'Idempotency-Key': '<uuid>',
            'X-Agent-ID': '<agent-id>',
            'X-Agent-Constitution-Version': '<version>',
            'X-Agent-Constitution-Hash': '<hash>',
        }

    async def close(self):
        await self.session.aclose()

4. RPC 方法定义

4.1 rpc_methods.json 概述

rpc_methods.json 是从白皮书模块派生的机器可读 API 面摘要。它包含 7 个方法族 (families),覆盖 Tendermint RPC、REST、合约面、Agent 读面、Agent 受保护写面、Agent Stub 面和 Explorer 面。

重要: 这属于 coding aid,不是最终 source-of-truth OpenAPI 契约。

{
  "schema_version": "v1",
  "generated_by": "msg_whitepaper_pipeline_v1",
  "scope": "Machine-readable API surface summary derived from whitepaper modules. This is a coding aid, not the final source-of-truth OpenAPI contract."
}

4.2 方法族总览

family_id 协议 状态 machine_safe_for_codegen
tendermint_rpc_core tendermint-rpc implemented true
rest_public_query rest implemented true
contract_surface rest partial true
agent_read_surface agent-rest+ws partial true
agent_guarded_write_surface agent-rest partial false
agent_stub_write_surface agent-rest partial false
explorer_read_surface rest+json-rpc+ws partial true

4.3 方法族详解

4.3.1 tendermint_rpc_core (已实现)

{
  "family_id": "tendermint_rpc_core",
  "protocol": "tendermint-rpc",
  "methods": [
    {"name": "broadcast_tx_commit",   "path_or_method": "/broadcast_tx_commit",  "mode": "write", "stability": "implemented"},
    {"name": "abci_query",            "path_or_method": "/abci_query",            "mode": "read",  "stability": "implemented"},
    {"name": "tx",                    "path_or_method": "/tx",                    "mode": "read",  "stability": "implemented"},
    {"name": "block",                 "path_or_method": "/block",                 "mode": "read",  "stability": "implemented"},
    {"name": "net_info",              "path_or_method": "/net_info",              "mode": "read",  "stability": "implemented"}
  ]
}

4.3.2 rest_public_query (已实现)

{
  "family_id": "rest_public_query",
  "protocol": "rest",
  "methods": [
    {"name": "status",            "path_or_method": "/api/v1/status",             "mode": "read",  "stability": "implemented"},
    {"name": "bank_balances",     "path_or_method": "/api/v1/bank/balances",      "mode": "read",  "stability": "implemented"},
    {"name": "staking_validators", "path_or_method": "/api/v1/staking/validators", "mode": "read", "stability": "implemented"},
    {"name": "auth_accounts",     "path_or_method": "/api/v1/auth/accounts",      "mode": "read",  "stability": "implemented"}
  ]
}

4.3.3 contract_surface (部分实现)

{
  "family_id": "contract_surface",
  "protocol": "rest",
  "methods": [
    {"name": "contracts_list",       "path_or_method": "/api/v1/contracts",                 "mode": "read",  "stability": "partial"},
    {"name": "contracts_canonical",  "path_or_method": "/api/v1/contracts?source=canonical", "mode": "read",  "stability": "partial"},
    {"name": "contract_deploy",      "path_or_method": "/api/v1/contracts/deploy",           "mode": "write", "stability": "partial"},
    {"name": "contract_instantiate", "path_or_method": "/api/v1/contracts/instantiate",      "mode": "write", "stability": "partial"},
    {"name": "contract_execute",     "path_or_method": "/api/v1/contracts/execute",          "mode": "write", "stability": "partial"}
  ]
}

4.3.4 agent_read_surface (部分实现)

{
  "family_id": "agent_read_surface",
  "protocol": "agent-rest+ws",
  "methods": [
    {"name": "agent_query_account",   "path_or_method": "/agent/v1/query/account",    "mode": "read", "stability": "partial"},
    {"name": "agent_query_balance",   "path_or_method": "/agent/v1/query/balance",    "mode": "read", "stability": "partial"},
    {"name": "agent_query_balances",  "path_or_method": "/agent/v1/query/balances",   "mode": "read", "stability": "partial"},
    {"name": "agent_query_tx",        "path_or_method": "/agent/v1/query/tx",         "mode": "read", "stability": "partial"},
    {"name": "agent_query_block",     "path_or_method": "/agent/v1/query/block",      "mode": "read", "stability": "partial"},
    {"name": "agent_events_history",  "path_or_method": "/agent/v1/events/history",   "mode": "read", "stability": "partial"},
    {"name": "agent_events_subscribe","path_or_method": "/agent/v1/events/subscribe", "mode": "read", "stability": "partial"}
  ]
}

4.3.5 agent_guarded_write_surface (部分实现, 不安全用于代码生成)

{
  "family_id": "agent_guarded_write_surface",
  "machine_safe_for_codegen": false,
  "methods": [
    {"name": "agent_wallet",        "path_or_method": "/agent/v1/wallet/*",             "mode": "write", "stability": "guarded"},
    {"name": "agent_mpc_sign",      "path_or_method": "/agent/v1/mpc/sign",             "mode": "write", "stability": "guarded"},
    {"name": "agent_payment_session","path_or_method": "/agent/v1/payment/session",     "mode": "write", "stability": "guarded"}
  ]
}

4.3.6 agent_stub_write_surface (Stub, 不安全)

{
  "family_id": "agent_stub_write_surface",
  "machine_safe_for_codegen": false,
  "methods": [
    {"name": "agent_defi",              "path_or_method": "/agent/v1/defi/*",              "mode": "write", "stability": "stub"},
    {"name": "agent_bridge_transfer",   "path_or_method": "/agent/v1/bridge/transfer",     "mode": "write", "stability": "stub"},
    {"name": "agent_registry_register", "path_or_method": "/agent/v1/registry/register",   "mode": "write", "stability": "stub"}
  ]
}

boundary: "返回 success (stub - not yet implemented) 或 X-MSG-Stub=true 时,AI 必须判定为未完成写入。"

4.3.7 explorer_read_surface (部分实现)

{
  "family_id": "explorer_read_surface",
  "protocol": "rest+json-rpc+ws",
  "methods": [
    {"name": "explorer_contracts",        "path_or_method": "/api/v1/contracts",                        "mode": "read", "stability": "partial"},
    {"name": "explorer_contracts_canonical","path_or_method": "/api/v1/contracts?source=canonical",      "mode": "read", "stability": "partial"},
    {"name": "explorer_eth_getLogs",      "path_or_method": "eth_getLogs",                               "mode": "read", "stability": "partial"},
    {"name": "explorer_ws_logs_filter",   "path_or_method": "ws://... logs address/topics filter",        "mode": "read", "stability": "partial"}
  ]
}

4.4 RPC 消费示例

import httpx
from typing import Any


MSG_RPC_METHODS = 'https://msgchain.org/whitepaper/api_specs/rpc_methods.json'


async def msg_load_rpc_families() -> list[dict[str, Any]]:
    """加载所有 RPC 方法族"""
    async with httpx.AsyncClient() as client:
        resp = await client.get(MSG_RPC_METHODS)
        resp.raise_for_status()
        data = resp.json()
    return data.get('families', [])


async def msg_find_rpc_method(method_name: str) -> dict[str, Any] | None:
    """按方法名查找 RPC 方法"""
    families = await msg_load_rpc_families()
    for family in families:
        for method in family.get('methods', []):
            if method['name'] == method_name:
                return {
                    'method': method,
                    'family_id': family['family_id'],
                    'protocol': family.get('protocol'),
                    'status': family.get('status'),
                }
    return None


async def msg_list_read_methods() -> list[dict[str, Any]]:
    """列出所有只读方法"""
    families = await msg_load_rpc_families()
    results = []
    for family in families:
        for method in family.get('methods', []):
            if method.get('mode') == 'read':
                results.append({
                    'name': method['name'],
                    'path': method['path_or_method'],
                    'family': family['family_id'],
                })
    return results


async def msg_list_write_methods() -> list[dict[str, Any]]:
    """列出所有写方法 (含受保护和 stub)"""
    families = await msg_load_rpc_families()
    results = []
    for family in families:
        for method in family.get('methods', []):
            if method.get('mode') == 'write':
                results.append({
                    'name': method['name'],
                    'path': method['path_or_method'],
                    'stability': method.get('stability'),
                    'family': family['family_id'],
                })
    return results


async def msg_list_safe_for_codegen() -> list[dict[str, Any]]:
    """列出可安全用于代码生成的方法族"""
    families = await msg_load_rpc_families()
    return [
        f for f in families
        if f.get('machine_safe_for_codegen', False)
    ]

4.5 协议路由表

MSG_ROUTE_MAP = {
    # tendermint_rpc_core
    'broadcast_tx_commit': {'path': '/broadcast_tx_commit', 'protocol': 'tendermint-rpc', 'mode': 'write'},
    'abci_query':          {'path': '/abci_query',          'protocol': 'tendermint-rpc', 'mode': 'read'},
    'tx':                  {'path': '/tx',                  'protocol': 'tendermint-rpc', 'mode': 'read'},
    'block':               {'path': '/block',               'protocol': 'tendermint-rpc', 'mode': 'read'},
    'net_info':            {'path': '/net_info',            'protocol': 'tendermint-rpc', 'mode': 'read'},

    # rest_public_query
    'status':              {'path': '/api/v1/status',               'protocol': 'rest', 'mode': 'read'},
    'bank_balances':       {'path': '/api/v1/bank/balances',        'protocol': 'rest', 'mode': 'read'},
    'staking_validators':  {'path': '/api/v1/staking/validators',   'protocol': 'rest', 'mode': 'read'},
    'auth_accounts':       {'path': '/api/v1/auth/accounts',        'protocol': 'rest', 'mode': 'read'},

    # contract_surface
    'contract_deploy':     {'path': '/api/v1/contracts/deploy',      'protocol': 'rest', 'mode': 'write'},
    'contract_instantiate':{'path': '/api/v1/contracts/instantiate', 'protocol': 'rest', 'mode': 'write'},
    'contract_execute':    {'path': '/api/v1/contracts/execute',     'protocol': 'rest', 'mode': 'write'},

    # agent_read_surface
    'agent_query_account':  {'path': '/agent/v1/query/account',   'protocol': 'agent-rest', 'mode': 'read'},
    'agent_query_balance':  {'path': '/agent/v1/query/balance',   'protocol': 'agent-rest', 'mode': 'read'},
    'agent_query_tx':       {'path': '/agent/v1/query/tx',        'protocol': 'agent-rest', 'mode': 'read'},
    'agent_query_block':    {'path': '/agent/v1/query/block',     'protocol': 'agent-rest', 'mode': 'read'},
    'agent_events_history': {'path': '/agent/v1/events/history',  'protocol': 'agent-rest', 'mode': 'read'},

    # agent_guarded_write
    'agent_wallet':         {'path': '/agent/v1/wallet/*',        'protocol': 'agent-rest', 'mode': 'write', 'stability': 'guarded'},
    'agent_mpc_sign':       {'path': '/agent/v1/mpc/sign',        'protocol': 'agent-rest', 'mode': 'write', 'stability': 'guarded'},

    # agent_stub
    'agent_defi_swap':      {'path': '/agent/v1/defi/swap',       'protocol': 'agent-rest', 'mode': 'write', 'stability': 'stub'},
    'agent_bridge_transfer':{'path': '/agent/v1/bridge/transfer', 'protocol': 'agent-rest', 'mode': 'write', 'stability': 'stub'},
}

5. 错误码定义

5.1 error_codes.json 概述

error_codes.json 是面向开发者的机器提示,用于解释非最终、受保护或证据敏感的响应。它帮助 AI Agent 正确判断响应状态是成功、受保护门禁、治理门禁还是 stub。

{
  "schema_version": "v1",
  "generated_by": "msg_whitepaper_pipeline_v1",
  "scope": "Developer-facing machine hints for interpreting non-final, guarded, or evidence-sensitive responses mentioned in the whitepaper system."
}

5.2 完整错误码清单

[
  {
    "code": "AGENT_STUB_SUCCESS",
    "severity": "hard-boundary",
    "signal": "X-MSG-Stub=true",
    "meaning": "The endpoint shape exists but the business write path is not yet implemented.",
    "ai_action": "Do not treat this as a successful write or deployment completion.",
    "source_modules": ["ai_agent.html", "agent_api_surface.html", "ai_wallet.html"]
  },
  {
    "code": "STUB_NOT_YET_IMPLEMENTED",
    "severity": "hard-boundary",
    "signal": "success (stub - not yet implemented)",
    "meaning": "A stub response surfaced for compatibility, not a completed business action.",
    "ai_action": "Escalate to human or switch to a non-stub path before claiming completion.",
    "source_modules": ["ai_agent.html", "agent_api_surface.html"]
  },
  {
    "code": "DAO_TIMELOCK_NOT_FINISHED",
    "severity": "governance-gate",
    "signal": "dao timelock not finished",
    "meaning": "DAO execution conditions are not yet satisfied.",
    "ai_action": "Wait for timelock completion and re-check execution state before retrying.",
    "source_modules": ["dao.html", "foundation.html"]
  },
  {
    "code": "HIGH_VALUE_THRESHOLD_NOT_MET",
    "severity": "governance-gate",
    "signal": "required_signers > collected_signers",
    "meaning": "High-value execution did not yet gather enough signatures.",
    "ai_action": "Do not continue execution; fetch threshold and execution signature state first.",
    "source_modules": ["foundation.html"]
  },
  {
    "code": "QUERY_TIMEOUT_OR_EMPTY",
    "severity": "runtime-boundary",
    "signal": "timeout / empty response / query failed",
    "meaning": "The evidence loop or runtime query did not complete reliably.",
    "ai_action": "Do not infer success from silence; retry, fall back, or mark verification incomplete.",
    "source_modules": ["trust_verdict.html", "evidence_index.html", "explorer.html"]
  },
  {
    "code": "PLANNED_SURFACE_ONLY",
    "severity": "planning-boundary",
    "signal": "status=planned",
    "meaning": "The surface exists as architecture/design knowledge but is not yet a stable implementation surface.",
    "ai_action": "Use it for roadmap understanding only, not production code completion claims.",
    "source_modules": ["sdk_dev_surface.html", "crosschain.html"]
  },
  {
    "code": "LIVE_PUBLIC_NOT_READY",
    "severity": "release-boundary",
    "signal": "live/public not ready",
    "meaning": "Local or internal proof may exist, but the public production surface is not fully closed.",
    "ai_action": "Avoid claiming public release readiness; keep rollout and local gate states separate.",
    "source_modules": ["explorer.html", "agent_entry.json"]
  }
]

5.3 错误码分类

MSG_ERROR_CODES_URL = 'https://msgchain.org/whitepaper/api_specs/error_codes.json'

MSG_ERROR_CATEGORIES = {
    'hard_boundary': ['AGENT_STUB_SUCCESS', 'STUB_NOT_YET_IMPLEMENTED'],
    'governance_gate': ['DAO_TIMELOCK_NOT_FINISHED', 'HIGH_VALUE_THRESHOLD_NOT_MET'],
    'runtime_boundary': ['QUERY_TIMEOUT_OR_EMPTY'],
    'planning_boundary': ['PLANNED_SURFACE_ONLY'],
    'release_boundary': ['LIVE_PUBLIC_NOT_READY'],
}


async def msg_load_error_codes() -> list[dict]:
    """加载所有错误码定义"""
    async with httpx.AsyncClient() as client:
        resp = await client.get(MSG_ERROR_CODES_URL)
        resp.raise_for_status()
        data = resp.json()
    return data.get('items', [])


async def msg_check_stub(response_data: dict) -> bool:
    """检查响应是否为 stub
    
    当响应包含 X-MSG-Stub: true 头部,或
    status='success' 但携带 stub 标记时,返回 True。
    """
    headers = response_data.get('headers', {})
    if headers.get('X-MSG-Stub') == 'true':
        return True
    body = response_data.get('body', {})
    if body.get('status') == 'success' and body.get('data', {}).get('implemented') == False:
        return True
    return False


async def msg_classify_error(error_code: str) -> str | None:
    """按错误码判断严重等级"""
    codes = await msg_load_error_codes()
    for item in codes:
        if item['code'] == error_code:
            return item['severity']
    return None


async def msg_get_ai_action(error_code: str) -> str | None:
    """获取 AI Agent 应采取的响应动作"""
    codes = await msg_load_error_codes()
    for item in codes:
        if item['code'] == error_code:
            return item['ai_action']
    return None

5.4 工具清单公共错误码

来自 source_backed/tool_manifest.json 的 common_error_codes:

MSG_COMMON_ERROR_CODES = {
    0:    'success',
    1001: 'invalid_params',
    1002: 'invalid_address',
    2001: 'account_not_found',
    3001: 'contract_not_found',
    3002: 'contract_failed',
    4001: 'tx_not_found',
    4002: 'block_not_found',
    5001: 'auth_failed',
    5002: 'invalid_api_key',
    5005: 'policy_denied',
    5006: 'kill_switch_active',
    5007: 'duplicate_request',
    9999: 'internal_error',
}

MSG_ERROR_SEVERITY = {
    0:    'success',
    1001: 'client_error',
    1002: 'client_error',
    2001: 'not_found',
    3001: 'not_found',
    3002: 'execution_error',
    4001: 'not_found',
    4002: 'not_found',
    5001: 'auth_error',
    5002: 'auth_error',
    5005: 'policy_error',
    5006: 'system_error',
    5007: 'conflict',
    9999: 'internal_error',
}


def msg_is_retryable(error_code: int) -> bool:
    """判断错误是否可重试"""
    non_retryable = {1001, 1002, 5001, 5002, 5005, 5006}
    return error_code not in non_retryable


def msg_is_success(error_code: int) -> bool:
    """判断是否为成功"""
    return error_code == 0

6. OpenAPI 规格

6.1 三份 OpenAPI 规格概述

规格 server 用途 写路径
public_query.yaml https://api.msgchain.org 公共查询面 无
contract_surface.yaml https://api.msgchain.org 合约交互面 有 (partial)
agent_surface.yaml https://msgchain.org Agent API 面 有 (guarded/stub)

6.2 public_query.yaml

openapi: 3.1.0
info:
  title: MSG Public Query Surface
  version: 2026-06-01
  description: >
    Whitepaper-generated OpenAPI summary for MSG public query surfaces.
    This is a machine-friendly coding aid and must not replace live endpoint verification.
servers:
  - url: https://api.msgchain.org
paths:
  /api/v1/status:
    get:
      operationId: getStatus
      summary: Query node and chain status.
      responses:
        '200': { description: Status payload returned. }

  /api/v1/bank/balances:
    get:
      operationId: getBalances
      summary: Query balances for an address.
      parameters:
        - in: query
          name: address
          required: true
          schema: { type: string }
      responses:
        '200': { description: Balance list returned. }

  /api/v1/staking/validators:
    get:
      operationId: listValidators
      summary: Query validator list.
      responses:
        '200': { description: Validator list returned. }

  /api/v1/auth/accounts:
    get:
      operationId: getAccount
      summary: Query account state by address.
      parameters:
        - in: query
          name: address
          required: true
          schema: { type: string }
      responses:
        '200': { description: Account payload returned. }

x-msg-boundary:
  - Public endpoints still require real availability checks before production use.
class msgPublicQueryClient:
    """MSG 公共查询面客户端"""

    def __init__(self, base_url: str = 'https://api.msgchain.org'):
        self.base = base_url
        self.session = httpx.AsyncClient(timeout=30.0)

    async def get_status(self) -> dict:
        resp = await self.session.get(f'{self.base}/api/v1/status')
        resp.raise_for_status()
        return resp.json()

    async def get_balances(self, address: str) -> dict:
        resp = await self.session.get(
            f'{self.base}/api/v1/bank/balances',
            params={'address': address},
        )
        resp.raise_for_status()
        return resp.json()

    async def list_validators(self) -> dict:
        resp = await self.session.get(f'{self.base}/api/v1/staking/validators')
        resp.raise_for_status()
        return resp.json()

    async def get_account(self, address: str) -> dict:
        resp = await self.session.get(
            f'{self.base}/api/v1/auth/accounts',
            params={'address': address},
        )
        resp.raise_for_status()
        return resp.json()

    async def close(self):
        await self.session.aclose()

6.3 contract_surface.yaml

openapi: 3.1.0
info:
  title: MSG Contract Surface
  version: 2026-06-01
  description: >
    Whitepaper-generated contract API summary for AI coding.
    Write paths may still be partial or guarded; always verify receipts and evidence loops.
servers:
  - url: https://api.msgchain.org
paths:
  /api/v1/contracts:
    get:
      operationId: listContracts
      summary: List visible contracts or canonical registry entries.
      parameters:
        - in: query
          name: source
          required: false
          schema:
            type: string
            enum: [canonical]
      responses:
        '200': { description: Contract list returned. }

  /api/v1/contracts/deploy:
    post:
      operationId: deployContract
      summary: Deploy contract code.
      responses:
        '200': { description: Deploy accepted. }

  /api/v1/contracts/instantiate:
    post:
      operationId: instantiateContract
      summary: Instantiate a deployed contract.
      responses:
        '200': { description: Instantiate accepted. }

  /api/v1/contracts/execute:
    post:
      operationId: executeContract
      summary: Execute a contract message.
      responses:
        '200': { description: Execute accepted. }

x-msg-boundary:
  - Contract write paths are not equivalent to a full audited deploy platform.
  - AI agents must verify tx hash, receipt, and post-state query before claiming success.
class msgContractSurfaceClient:
    """MSG 合约交互面客户端"""

    def __init__(self, base_url: str = 'https://api.msgchain.org'):
        self.base = base_url
        self.session = httpx.AsyncClient(timeout=60.0)

    async def list_contracts(self, source: str | None = None) -> dict:
        params = {}
        if source:
            params['source'] = source
        resp = await self.session.get(f'{self.base}/api/v1/contracts', params=params)
        resp.raise_for_status()
        return resp.json()

    async def deploy_contract(self, payload: dict) -> dict:
        resp = await self.session.post(f'{self.base}/api/v1/contracts/deploy', json=payload)
        resp.raise_for_status()
        return resp.json()

    async def instantiate_contract(self, payload: dict) -> dict:
        resp = await self.session.post(f'{self.base}/api/v1/contracts/instantiate', json=payload)
        resp.raise_for_status()
        return resp.json()

    async def execute_contract(self, payload: dict) -> dict:
        resp = await self.session.post(f'{self.base}/api/v1/contracts/execute', json=payload)
        resp.raise_for_status()
        return resp.json()

    async def verify_execution(self, tx_hash: str) -> dict:
        """验证合约执行结果: 查询交易回执"""
        resp = await self.session.get(
            f'{self.base}/agent/v1/query/tx/{tx_hash}',
        )
        resp.raise_for_status()
        return resp.json()

    async def close(self):
        await self.session.aclose()

6.4 agent_surface.yaml

openapi: 3.1.0
info:
  title: MSG Agent Query And Guarded Write Surface
  version: 2026-06-01
  description: >
    Whitepaper-generated Agent API summary. Some write paths remain guarded or stubbed.
servers:
  - url: https://msgchain.org
components:
  schemas:
    AgentBalanceResponse:
      type: object
      properties:
        account:  { type: string }
        asset:    { type: string }
        amount:   { type: string }
        height:   { type: integer }
      required: [account, asset, amount]

    GuardedWalletActionRequest:
      type: object
      properties:
        account:         { type: string }
        action:          { type: string }
        unsigned_payload: { type: object, additionalProperties: true }
        justification:   { type: string }
      required: [account, action, unsigned_payload]

    GuardedWalletActionResponse:
      type: object
      properties:
        status:
          type: string
          enum: [stub, pending_human_approval, rejected, ready_for_signing]
        approval_gate: { type: string }
        next_step:     { type: string }
      required: [status]

paths:
  /agent/v1/query/account:
    get:
      operationId: queryAgentAccount
      responses:
        '200': { description: Account payload returned. }

  /agent/v1/query/balance:
    get:
      operationId: queryAgentBalance
      parameters:
        - in: query
          name: account
          required: true
          schema: { type: string }
        - in: query
          name: asset
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Balance payload returned.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentBalanceResponse'
              example:
                account: "msg1developerexample..."
                asset: "umsg"
                amount: "125000000"
                height: 128

  /agent/v1/query/tx:
    get:
      operationId: queryAgentTx
      responses:
        '200': { description: Tx payload returned. }

  /agent/v1/events/history:
    get:
      operationId: queryAgentEventHistory
      responses:
        '200': { description: Event history returned. }

  /agent/v1/wallet/{action}:
    post:
      operationId: guardedWalletAction
      parameters:
        - in: path
          name: action
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GuardedWalletActionRequest'
      x-msg-human-approval-gates:
        - secret_injection
        - production_release
      x-msg-boundary:
        - This path must remain guarded and cannot be interpreted as autonomous production signing.
      responses:
        '200':
          description: Guarded action response returned.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GuardedWalletActionResponse'

x-msg-boundary:
  - Stub responses and guarded writes must never be treated as autonomous production completion.

6.5 Auth 要求

MSG_AUTH_REQUIREMENTS = {
    'public_read': {
        'required': False,
        'headers': ['X-Request-ID'],
    },
    'protected_write': {
        'required': True,
        'headers': [
            'X-API-Key',
            'X-Agent-Policy-ID',
            'X-Agent-Scope',
            'Idempotency-Key',
        ],
        'constitution_preflight': [
            'X-Agent-ID',
            'X-Agent-Constitution-Version',
            'X-Agent-Constitution-Hash',
            'X-Agent-AIDID',
            'X-Agent-Budget-ID',
            'X-Agent-Signer-ID',
            'X-Agent-Receipt-ID',
            'X-Agent-Proof-ID',
        ],
    },
    'production_without_keys': 'fail-closed',
}


def msg_build_write_headers(
    api_key: str,
    policy_id: str,
    scope: str,
    idempotency_key: str,
    agent_id: str | None = None,
    constitution_version: str | None = None,
    constitution_hash: str | None = None,
) -> dict[str, str]:
    """构建受保护写路径所需的请求头"""
    headers = {
        'X-API-Key': api_key,
        'X-Agent-Policy-ID': policy_id,
        'X-Agent-Scope': scope,
        'Idempotency-Key': idempotency_key,
    }
    if agent_id:
        headers['X-Agent-ID'] = agent_id
    if constitution_version:
        headers['X-Agent-Constitution-Version'] = constitution_version
    if constitution_hash:
        headers['X-Agent-Constitution-Hash'] = constitution_hash
    return headers

6.6 Stub 检测

def msg_is_stub_response(response: httpx.Response) -> bool:
    """检测响应是否为 Stub
    
    当满足以下任一条件时判定为 stub:
    1. 响应头包含 X-MSG-Stub: true
    2. 响应体中 status='success' 且 data.implemented=False
    3. 响应体中 status 为 'stub'
    """
    # 检查响应头
    if response.headers.get('X-MSG-Stub', '').lower() == 'true':
        return True

    try:
        body = response.json()
    except Exception:
        return False

    # 检查响应体
    if body.get('status') == 'stub':
        return True
    if body.get('status') == 'success' and body.get('data', {}).get('implemented') is False:
        return True
    if body.get('error_code') == 0 and body.get('data', {}).get('implemented') is False:
        return True

    return False


async def msg_safe_execute(client: httpx.AsyncClient, url: str, payload: dict, headers: dict) -> dict:
    """安全执行写操作: 检查 stub 并验证回执"""
    resp = await client.post(url, json=payload, headers=headers)
    
    # Step 1: 检查 stub
    if msg_is_stub_response(resp):
        raise RuntimeError(f'Stub response: {url} is not yet implemented (X-MSG-Stub=true)')
    
    result = resp.json()
    
    # Step 2: 验证基本成功
    if result.get('status') == 'error':
        raise RuntimeError(f'Execution failed: code={result.get("error_code")} message={result.get("message")}')
    
    # Step 3: 如果有 tx_hash,验证回执
    tx_hash = result.get('data', {}).get('tx_hash')
    if tx_hash:
        receipt = await client.get(
            f'https://api.msgchain.org/agent/v1/query/tx/{tx_hash}'
        )
        receipt.raise_for_status()
        return {
            'execution_result': result,
            'receipt': receipt.json(),
            'tx_hash': tx_hash,
        }
    
    return {'execution_result': result}

7. AI Agent 消费模式

7.1 统一消费者类

import httpx
from typing import Any


class msgApiSpecs:
    """MSG API 规格统一消费者
    
    使用示例:
        async with msgApiSpecs() as specs:
            contracts = await specs.load_formal_contracts()
            rpc = await specs.load_rpc_methods()
            errors = await specs.load_error_codes()
            print(contracts['required_contracts'])
    """

    def __init__(self):
        self.base = 'https://msgchain.org/whitepaper'
        self._client: httpx.AsyncClient | None = None

    async def __aenter__(self):
        self._client = httpx.AsyncClient(timeout=30.0)
        return self

    async def __aexit__(self, *args):
        if self._client:
            await self._client.aclose()

    @property
    def client(self) -> httpx.AsyncClient:
        if self._client is None:
            raise RuntimeError('Use async with msgApiSpecs() as specs:')
        return self._client

    async def _load(self, path: str) -> dict[str, Any]:
        resp = await self.client.get(f'{self.base}/{path}')
        resp.raise_for_status()
        return resp.json()

    async def load_index(self) -> dict[str, Any]:
        return await self._load('api_specs/index.json')

    async def load_formal_contracts(self) -> dict[str, Any]:
        return await self._load('api_specs/formal_contracts.json')

    async def load_rpc_methods(self) -> dict[str, Any]:
        return await self._load('api_specs/rpc_methods.json')

    async def load_error_codes(self) -> dict[str, Any]:
        return await self._load('api_specs/error_codes.json')

    async def load_agent_openapi(self) -> dict[str, Any]:
        return await self._load('api_specs/source_backed/agent_openapi.json')

    async def load_tool_manifest(self) -> dict[str, Any]:
        return await self._load('api_specs/source_backed/tool_manifest.json')

    async def load_mcp_manifest(self) -> dict[str, Any]:
        return await self._load('api_specs/source_backed/mcp_manifest.json')

    async def load_all(self) -> dict[str, Any]:
        """并行加载所有核心规格"""
        import asyncio
        results = await asyncio.gather(
            self.load_formal_contracts(),
            self.load_rpc_methods(),
            self.load_error_codes(),
            self.load_agent_openapi(),
            self.load_tool_manifest(),
        )
        return {
            'formal_contracts': results[0],
            'rpc_methods': results[1],
            'error_codes': results[2],
            'agent_openapi': results[3],
            'tool_manifest': results[4],
        }

7.2 检查当前所有可用工具

class msgToolInspector:
    """工具检查器 - 列出当前可用的所有工具"""

    def __init__(self, specs: msgApiSpecs):
        self.specs = specs

    async def list_all_tools(self) -> list[dict]:
        manifest = await self.specs.load_tool_manifest()
        return manifest.get('tools', [])

    async def list_implemented_read_tools(self) -> list[dict]:
        tools = await self.list_all_tools()
        return [
            t for t in tools
            if t['status'] in ('implemented', 'implemented_local')
            and t.get('method') == 'GET'
        ]

    async def list_protected_write_tools(self) -> list[dict]:
        tools = await self.list_all_tools()
        return [
            t for t in tools
            if t['status'] == 'implemented_protected'
        ]

    async def list_blocked_or_planned(self) -> list[dict]:
        tools = await self.list_all_tools()
        return [
            t for t in tools
            if t['status'] in ('blocked', 'planned')
        ]

    async def print_summary(self):
        tools = await self.list_all_tools()
        categories: dict[str, list[str]] = {}
        for t in tools:
            cat = t.get('category', 'uncategorized')
            status = t['status']
            if cat not in categories:
                categories[cat] = []
            categories[cat].append(f"  [{status}] {t['name']}: {t['path']}")
        
        for cat, items in sorted(categories.items()):
            print(f'\n{cat}:')
            for item in items:
                print(item)

7.3 OpenAPI 到 SDK 的映射

class msgOpenApiToSdk:
    """OpenAPI 规格到 SDK 代码的映射生成器"""

    @staticmethod
    def map_public_query() -> dict[str, dict]:
        return {
            'getStatus': {
                'method': 'GET',
                'path': '/api/v1/status',
                'params': [],
                'returns': 'dict',
            },
            'getBalances': {
                'method': 'GET',
                'path': '/api/v1/bank/balances',
                'params': [{'name': 'address', 'type': 'str', 'required': True}],
                'returns': 'dict',
            },
            'listValidators': {
                'method': 'GET',
                'path': '/api/v1/staking/validators',
                'params': [],
                'returns': 'dict',
            },
            'getAccount': {
                'method': 'GET',
                'path': '/api/v1/auth/accounts',
                'params': [{'name': 'address', 'type': 'str', 'required': True}],
                'returns': 'dict',
            },
        }

    @staticmethod
    def map_agent_read() -> dict[str, dict]:
        return {
            'queryAgentAccount': {
                'method': 'GET',
                'path': '/agent/v1/query/account/{address}',
                'params': [{'name': 'address', 'type': 'str', 'required': True, 'in': 'path'}],
                'auth': False,
            },
            'queryAgentBalance': {
                'method': 'GET',
                'path': '/agent/v1/query/balance/{address}',
                'params': [{'name': 'address', 'type': 'str', 'required': True, 'in': 'path'}],
                'auth': False,
            },
            'queryAgentTx': {
                'method': 'GET',
                'path': '/agent/v1/query/tx/{tx_hash}',
                'params': [{'name': 'tx_hash', 'type': 'str', 'required': True, 'in': 'path'}],
                'auth': False,
            },
            'queryAgentEventHistory': {
                'method': 'GET',
                'path': '/agent/v1/events/history',
                'params': [
                    {'name': 'from_height', 'type': 'int', 'required': True},
                    {'name': 'to_height', 'type': 'int', 'required': True},
                    {'name': 'type', 'type': 'str', 'required': False},
                ],
                'auth': False,
            },
        }

    @staticmethod
    def map_protected_write() -> dict[str, dict]:
        return {
            'guardedWalletAction': {
                'method': 'POST',
                'path': '/agent/v1/wallet/{action}',
                'auth': True,
                'constitution_preflight': True,
                'headers': ['X-API-Key', 'X-Agent-Policy-ID', 'X-Agent-Scope', 'Idempotency-Key'],
            },
            'msg_wallet_transfer': {
                'method': 'POST',
                'path': '/agent/v1/wallet/transfer',
                'auth': True,
                'constitution_preflight': True,
                'headers': ['X-API-Key', 'X-Agent-Policy-ID', 'X-Agent-Scope', 'Idempotency-Key'],
            },
            'msg_agent_registry_register': {
                'method': 'POST',
                'path': '/agent/v1/registry/register',
                'auth': True,
                'constitution_preflight': True,
            },
            'msg_ai_agent_constitution_acknowledge': {
                'method': 'POST',
                'path': '/agent/v1/constitution/acknowledge',
                'auth': True,
                'constitution_preflight': False,  # bootstrap entry: skips check_action
            },
        }

7.4 消费模式示例:完整工作流

async def msg_agent_workflow_example():
    """AI Agent 完整工作流示例"""
    async with msgApiSpecs() as specs:
        # Step 1: 发现可用工具
        tool_inspector = msgToolInspector(specs)
        read_tools = await tool_inspector.list_implemented_read_tools()
        write_tools = await tool_inspector.list_protected_write_tools()
        blocked = await tool_inspector.list_blocked_or_planned()

        print(f'可用读取工具: {len(read_tools)}')
        print(f'受保护写工具: {len(write_tools)}')
        print(f'阻塞/计划中: {len(blocked)}')

        # Step 2: 加载 RPC 方法
        rpc = await specs.load_rpc_methods()
        for family in rpc.get('families', []):
            print(f'[{family["status"]}] {family["family_id"]}: {len(family.get("methods", []))} methods')

        # Step 3: 加载错误码
        error_codes = await specs.load_error_codes()
        for item in error_codes.get('items', []):
            print(f'[{item["severity"]}] {item["code"]}: {item["meaning"]}')

        # Step 4: 检查 stub 检测逻辑
        stub_headers = {'X-MSG-Stub': 'true'}
        stub_response = httpx.Response(200, headers=stub_headers, json={'status': 'success', 'data': {'implemented': False}})
        if msg_is_stub_response(stub_response):
            print('Stub detected - will not treat as successful write')

        # Step 5: 验证回执循环
        print(await specs.load_formal_contracts()['required_contracts'])

7.5 从 tool_manifest 获取工具详情

class msgToolDetailResolver:
    """工具详情解析器"""

    def __init__(self, manifest: dict):
        self.tools = {t['name']: t for t in manifest.get('tools', [])}
        self.status_values = manifest.get('status_values', {})
        self.common_headers = manifest.get('common_headers', {})
        self.common_error_codes = manifest.get('common_error_codes', [])

    def get_tool(self, name: str) -> dict | None:
        return self.tools.get(name)

    def get_required_headers(self, tool_name: str) -> list[str]:
        tool = self.get_tool(tool_name)
        if not tool:
            return []
        
        headers = []
        if tool.get('status') in ('implemented_protected', 'available_via_rest'):
            headers.extend(self.common_headers.get('write', []))
        
        if tool.get('constitution_preflight', {}).get('required'):
            headers.extend(self.common_headers.get('constitution_preflight_write', []))
        
        return list(set(headers))

    def get_common_errors(self, tool_name: str) -> list[dict]:
        tool = self.get_tool(tool_name)
        if not tool:
            return []
        error_codes = tool.get('errors', [])
        return [
            {'code': ec['code'], 'name': ec['name']}
            for ec in self.common_error_codes
            if ec['code'] in error_codes
        ]

    def get_payment_info(self, tool_name: str) -> dict | None:
        tool = self.get_tool(tool_name)
        if not tool:
            return None
        return tool.get('payment')

8. 边界声明

8.1 source_backed_reference: 非生产

MSG_BOUNDARY_STATEMENTS = {
    'formal_api_schema_pack': """
这层已经比白皮书摘要更接近 repo-backed OpenAPI、tool manifest 与 contract schema,
但仍不是 signed production release contract。
涉及 public route inventory、receipt consistency、error negative suite 与 final signatures 时,
仍以 release manifest blocker 为准。
    """.strip(),

    'contract_surface': """
Contract write paths are not equivalent to a full audited deploy platform.
AI agents must verify tx hash, receipt, and post-state query before claiming success.
    """.strip(),

    'agent_stub': """
返回 success (stub - not yet implemented) 或 X-MSG-Stub=true 时,
AI 必须判定为未完成写入。
    """.strip(),

    'guarded_write': """
涉及审批、权限、风控、签名与密钥,不应被视为零人工干预写路径。
    """.strip(),

    'agent_constitution': """
Official MSG Chain AI Agent protected write surfaces must fail closed
with ai_agent_constitution_v1 check_action when constitution enforcement is required;
acknowledge_constitution is the bootstrap entry action and is not checked against itself.
    """.strip(),

    'production_private_key': """
AI Runtime must not receive cleartext private keys;
production writes require policy, budget and signer controls.
    """.strip(),
}

8.2 开发者能力矩阵中的边界

MSG_DEVELOPER_BOUNDARIES = {
    # 来自 developer_entry.json
    'human_inputs_required': [
        '产品目标与业务规则',
        '真实部署权限与签名账户',
        '生产环境变量、域名、CI/CD 或发布权限',
        '治理、多签、金库、审批等高风险动作的授权与窗口',
    ],

    'current_boundaries': [
        '当前开发协议层可显著提升 AI coding 的可执行性,但仍不能诚实承诺"只靠入口即可 100% 自动完成任何产品上线"。',
        '当前已补 Quick Start、source-backed 合约消费索引、正式 API/Schema 契约索引与 fail-closed sandbox 策略,但仍不等于 signed public SDK、public sandbox 或 not independently verified for production 交付。',
        '涉及私钥、部署权限、生产域名、资金操作、DAO/timelock/threshold 的动作,必须保留人类确认与审批门禁。',
    ],

    'metadata_profile': 'public_stable',
}

8.3 各能力面的机器就绪度总结

MSG_READINESS_MATRIX = {
    'contract_runtime': {
        'machine_readiness': 'assisted_codegen',
        'production_supported': True,
        'best_for': ['合约消息设计', '状态流转设计', '部署调用路径生成', '回执验证规划'],
    },
    'core_contract_reference_pack': {
        'machine_readiness': 'source_backed_reference',
        'production_supported': False,
        'best_for': ['识别核心合约 canonical key 与 schema', '生成 typed query/execute payload'],
    },
    'rpc_gateway': {
        'machine_readiness': 'assisted_codegen',
        'production_supported': True,
        'best_for': ['dApp 查询层', '交易广播', '基础客户端封装'],
    },
    'formal_api_schema_pack': {
        'machine_readiness': 'source_backed_reference',
        'production_supported': False,
        'best_for': ['读取 repo-backed OpenAPI/Swagger/agent manifest', '生成 request/response parser', '统一 receipt/event/error code 消费入口'],
    },
    'agent_query_and_guarded_write': {
        'machine_readiness': 'guarded_write',
        'production_supported': False,
        'machine_safe_for_codegen': False,
        'best_for': ['AI coding 辅助编排', '监控读取', '高风险动作门禁理解'],
    },
}

8.4 关键边界:未签名发布

def msg_check_production_readiness(surface_id: str) -> dict:
    """检查某个能力面是否可用于生产"""
    surface = MSG_READINESS_MATRIX.get(surface_id, {})
    return {
        'surface_id': surface_id,
        'production_supported': surface.get('production_supported', False),
        'machine_safe_for_codegen': surface.get('machine_safe_for_codegen', True),
        'write_path_ready': surface.get('write_path_ready', False),
        'verdict': 'PRODUCTION READY' if surface.get('production_supported') else 'NOT PRODUCTION - REFERENCE ONLY',
    }

PRODUCTION_READY_SURFACES = [
    'contract_runtime',
    'rpc_gateway',
]

REFERENCE_ONLY_SURFACES = [
    'core_contract_reference_pack',
    'formal_api_schema_pack',
    'wallet_frontend',
    'explorer_receipts',
    'agent_query_and_guarded_write',
    'sdk_surface',
    'public_sandbox_strategy',
    'contract_template_pack',
    'dapp_starter_pack',
]

STARTER_READY_SURFACES = [
    'chain_config_pack',
    'contract_template_pack',
    'dapp_starter_pack',
]

8.5 AI Agent 行为守则

MSG_AGENT_RULES = """
1. 不得将 stub 响应视为成功的写入或部署完成。
2. 所有受保护写路径必须携带 X-API-Key、X-Agent-Policy-ID、X-Agent-Scope 和 Idempotency-Key。
3. 涉及宪法 (Constitution) 预检的写路径,需额外提供 X-Agent-ID、X-Agent-Constitution-Version、X-Agent-Constitution-Hash。
4. 写操作完成后,必须通过 /agent/v1/query/tx/{tx_hash} 验证回执。
5. AI Runtime 不得接触明文私钥;生产写操作需要策略、预算和签名人控制。
6. format_api_schema_pack 是 source_backed_reference 级别,不是 signed production release contract。
7. 所有开发参考级部署、资金操作、DAO/timelock/threshold 动作必须保留人类确认与审批门禁。
8. 不要在未经验证的情况下将 local/in-process 的证明等同于 public production 可用性。
9. 涉及治理门禁 (governance-gate) 的错误码,必须等待条件满足再重试。
10. 涉及 hard-boundary 的错误码 (stub),必须上报人类或切换路径。
"""

8.6 引用完整性

MSG_SPEC_REFERENCES = {
    'developer_entry': 'https://msgchain.org/whitepaper/developer_entry.json',
    'agent_entry': 'https://msgchain.org/whitepaper/agent_entry.json',
    'developer_capability_matrix': 'https://msgchain.org/whitepaper/developer_capability_matrix.json',
    'api_specs_index': 'https://msgchain.org/whitepaper/api_specs/index.json',
    'formal_contracts': 'https://msgchain.org/whitepaper/api_specs/formal_contracts.json',
    'rpc_methods': 'https://msgchain.org/whitepaper/api_specs/rpc_methods.json',
    'error_codes': 'https://msgchain.org/whitepaper/api_specs/error_codes.json',
    'public_query_openapi': 'https://msgchain.org/whitepaper/api_specs/openapi/public_query.yaml',
    'contract_surface_openapi': 'https://msgchain.org/whitepaper/api_specs/openapi/contract_surface.yaml',
    'agent_surface_openapi': 'https://msgchain.org/whitepaper/api_specs/openapi/agent_surface.yaml',
    'tool_manifest': 'https://msgchain.org/whitepaper/api_specs/source_backed/tool_manifest.json',
    'agent_openapi': 'https://msgchain.org/whitepaper/api_specs/source_backed/agent_openapi.json',
    'mcp_manifest': 'https://msgchain.org/whitepaper/api_specs/source_backed/mcp_manifest.json',
}

附录

A. 快速参考:工具状态图

implemented ──→ 可路由且有当前节点代码支持
implemented_protected ──→ 受 API Key/Policy/Scope/Idempotency 保护的写路径
implemented_local ──→ 仅本地/进程内可路由
stub ──→ 路由存在但 X-MSG-Stub=true, data.implemented=false
available_via_rest ──→ 通过非 Agent REST/RPC 路径可用
planned ──→ Schema 保留,端点未实现
blocked ──→ Schema 保留,执行被证据门禁阻塞

B. 快速参考:错误码

0    success              (成功)
1001 invalid_params       (无效参数)
1002 invalid_address      (无效地址)
2001 account_not_found    (账户未找到)
3001 contract_not_found   (合约未找到)
3002 contract_failed      (合约执行失败)
4001 tx_not_found         (交易未找到)
4002 block_not_found      (区块未找到)
5001 auth_failed          (认证失败)
5002 invalid_api_key      (无效 API Key)
5005 policy_denied        (策略拒绝)
5006 kill_switch_active   (紧急开关激活)
5007 duplicate_request    (重复请求)
9999 internal_error       (内部错误)

C. 快速参考:关键端点

# 公共查询 (无需认证)
GET  https://api.msgchain.org/api/v1/status
GET  https://api.msgchain.org/api/v1/bank/balances?address={address}
GET  https://api.msgchain.org/api/v1/staking/validators
GET  https://api.msgchain.org/api/v1/auth/accounts?address={address}

# 合约面 (写路径需认证)
GET  https://api.msgchain.org/api/v1/contracts
POST https://api.msgchain.org/api/v1/contracts/deploy
POST https://api.msgchain.org/api/v1/contracts/instantiate
POST https://api.msgchain.org/api/v1/contracts/execute

# Agent 查询面 (无需认证)
GET  https://msgchain.org/agent/v1/query/account/{address}
GET  https://msgchain.org/agent/v1/query/balance/{address}
GET  https://msgchain.org/agent/v1/query/tx/{tx_hash}
GET  https://msgchain.org/agent/v1/query/block/{height}
GET  https://msgchain.org/agent/v1/events/history

# Agent 保护写路径 (需 API Key + Policy + Scope + Idempotency)
POST https://msgchain.org/agent/v1/wallet/transfer
POST https://msgchain.org/agent/v1/wallet/create
POST https://msgchain.org/agent/v1/constitution/acknowledge
POST https://msgchain.org/agent/v1/registry/register
POST https://msgchain.org/agent/v1/mpc/sign

D. 关键边界:不应使用的端点

以下端点的 stability 为 stub 或 guarded,AI Agent 不应将其视为可用写路径:

# Stub 端点 (未实现)
POST /agent/v1/defi/swap          (stub)
POST /agent/v1/defi/liquidity     (stub)
POST /agent/v1/defi/stake         (stub)
POST /agent/v1/bridge/transfer    (stub)

# Guarded 端点 (需人工审批)
POST /agent/v1/wallet/{action}    (guarded)
POST /agent/v1/mpc/sign           (guarded)
POST /agent/v1/payment/session    (guarded)

# Blocked 端点 (被证据门禁阻塞)
POST /agent/v1/governance/proposals/create  (blocked)
POST /agent/v1/treasury/executions/create   (blocked)
POST /agent/v1/validator/register           (planned)
POST /agent/v1/ai-registry/register         (planned)

本文档基于 MSG Chain developer_entry.json version v1 的 bootstrap 顺序生成。
所有 URL 均指向 https://msgchain.org/whitepaper/ 下的真实文件。
元数据: public_stable | machine_readable