{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-tools",
  "title": "Agent Tools",
  "description": "WebMCP tools for browser agents (document.modelContext): get_wallet, list_chains, get_balance (native or ERC-20), get_gas_price and switch_chain, read from the app's wagmi config. Sending and signing stay with the person; 0xui buttons mark those with data-agent-confirm. Exports AgentTools (renders nothing), useAgentTools (add your own tools) and walletAgentTools. Does nothing in browsers without WebMCP.",
  "dependencies": [
    "wagmi",
    "viem"
  ],
  "files": [
    {
      "path": "registry/default/components/agent-tools.tsx",
      "content": "// Docs: https://0xui.io/components/agent-tools.md\nimport { useEffect } from \"react\";\nimport { erc20Abi, formatUnits, isAddress, type Address } from \"viem\";\nimport { useConfig, type Config } from \"wagmi\";\nimport {\n  getBalance,\n  getChainId,\n  getChains,\n  getConnection,\n  getGasPrice,\n  readContracts,\n  switchChain,\n} from \"wagmi/actions\";\n\nexport type AgentTool = {\n  name: string;\n  title: string;\n  description: string;\n  inputSchema: object;\n  annotations: { readOnlyHint: boolean; consequentialHint?: boolean };\n  execute: (input: Record<string, unknown>) => Promise<unknown>;\n};\n\ntype ModelContext = {\n  registerTool(tool: AgentTool, options?: { signal?: AbortSignal }): Promise<void> | void;\n};\n\nfunction chainIdOf(config: Config, value: unknown) {\n  if (value === undefined) return getChainId(config);\n  const chain = getChains(config).find(\n    (c) => c.id === Number(value) || c.name.toLowerCase() === String(value).toLowerCase(),\n  );\n  if (!chain) {\n    const names = getChains(config).map((c) => `${c.name} (${c.id})`);\n    throw new Error(`This app doesn't support chain \"${value}\". Chains: ${names.join(\", \")}.`);\n  }\n  return chain.id;\n}\n\n/**\n * WebMCP tools for the wallet state of a wagmi app: who is connected, on\n * which chain, with what balances. They only read, except `switch_chain`,\n * which opens the wallet's own prompt. Sending and signing stay with the\n * person: 0xui's buttons mark those with `data-agent-confirm`.\n */\nexport function walletAgentTools(config: Config): AgentTool[] {\n  return [\n    {\n      name: \"get_wallet\",\n      title: \"Get the connected wallet\",\n      description:\n        'Returns whether a wallet is connected, its address, the wallet\\'s name, and the chain it is on. Returns { status: \"disconnected\" } when no wallet is connected: ask the person to connect one.',\n      inputSchema: { type: \"object\", properties: {} },\n      annotations: { readOnlyHint: true },\n      async execute() {\n        const connection = getConnection(config);\n        if (connection.status !== \"connected\") return { status: connection.status };\n        const chain = getChains(config).find((c) => c.id === connection.chainId);\n        return {\n          status: \"connected\",\n          address: connection.address,\n          addresses: connection.addresses,\n          wallet: connection.connector?.name,\n          chain: { id: connection.chainId, name: chain?.name ?? \"Unsupported network\" },\n          supportedChain: Boolean(chain),\n        };\n      },\n    },\n    {\n      name: \"list_chains\",\n      title: \"List supported chains\",\n      description: \"Lists the chains this app supports, with the current one marked.\",\n      inputSchema: { type: \"object\", properties: {} },\n      annotations: { readOnlyHint: true },\n      async execute() {\n        const current = getChainId(config);\n        return getChains(config).map((chain) => ({\n          id: chain.id,\n          name: chain.name,\n          nativeCurrency: chain.nativeCurrency.symbol,\n          current: chain.id === current,\n          testnet: Boolean(chain.testnet),\n        }));\n      },\n    },\n    {\n      name: \"get_balance\",\n      title: \"Get a token balance\",\n      description:\n        \"Returns a balance as a decimal string with its symbol and raw integer value. Defaults to the connected account's native balance on the current chain. Pass token (an ERC-20 contract address) for a token, address for another account, chain (id or name) for another chain.\",\n      inputSchema: {\n        type: \"object\",\n        properties: {\n          token: {\n            type: \"string\",\n            description: \"ERC-20 contract address. Omit for the native currency.\",\n          },\n          address: {\n            type: \"string\",\n            description: \"Account to read. Defaults to the connected account.\",\n          },\n          chain: {\n            type: [\"number\", \"string\"],\n            description: \"Chain id or name. Defaults to the current chain.\",\n          },\n        },\n      },\n      annotations: { readOnlyHint: true },\n      async execute(input) {\n        const address = (input.address ?? getConnection(config).address) as Address | undefined;\n        if (!address || !isAddress(address)) {\n          throw new Error(\"No wallet is connected. Pass an address, or ask the person to connect.\");\n        }\n        const chainId = chainIdOf(config, input.chain);\n\n        if (input.token === undefined) {\n          const balance = await getBalance(config, { address, chainId });\n          return {\n            value: balance.value.toString(),\n            formatted: formatUnits(balance.value, balance.decimals),\n            symbol: balance.symbol,\n            chainId,\n          };\n        }\n\n        const token = String(input.token);\n        if (!isAddress(token)) throw new Error(`\"${token}\" isn't a contract address.`);\n        const [value, decimals, symbol] = await readContracts(config, {\n          allowFailure: false,\n          contracts: [\n            { address: token, abi: erc20Abi, functionName: \"balanceOf\", args: [address], chainId },\n            { address: token, abi: erc20Abi, functionName: \"decimals\", chainId },\n            { address: token, abi: erc20Abi, functionName: \"symbol\", chainId },\n          ],\n        });\n        return {\n          value: value.toString(),\n          formatted: formatUnits(value, decimals),\n          symbol,\n          chainId,\n        };\n      },\n    },\n    {\n      name: \"get_gas_price\",\n      title: \"Get the gas price\",\n      description:\n        \"Returns the current gas price on a chain in wei and gwei. Defaults to the current chain.\",\n      inputSchema: {\n        type: \"object\",\n        properties: {\n          chain: { type: [\"number\", \"string\"], description: \"Chain id or name.\" },\n        },\n      },\n      annotations: { readOnlyHint: true },\n      async execute(input) {\n        const chainId = chainIdOf(config, input.chain);\n        const wei = await getGasPrice(config, { chainId });\n        return { wei: wei.toString(), gwei: formatUnits(wei, 9), chainId };\n      },\n    },\n    {\n      name: \"switch_chain\",\n      title: \"Switch the wallet's chain\",\n      description:\n        \"Asks the wallet to switch to another supported chain. The wallet shows the person a prompt; if they decline, this fails with a rejection and you should not retry on your own.\",\n      inputSchema: {\n        type: \"object\",\n        properties: { chain: { type: [\"number\", \"string\"], description: \"Chain id or name.\" } },\n        required: [\"chain\"],\n      },\n      annotations: { readOnlyHint: false },\n      async execute(input) {\n        const chain = await switchChain(config, { chainId: chainIdOf(config, input.chain) });\n        return { id: chain.id, name: chain.name };\n      },\n    },\n  ];\n}\n\n/** Registers `tools` with the browser through WebMCP. Returns the cleanup. Does nothing without WebMCP. */\nexport function registerAgentTools(tools: AgentTool[]) {\n  const context = (globalThis.document as { modelContext?: ModelContext } | undefined)\n    ?.modelContext;\n  const controller = new AbortController();\n  if (!context) return () => {};\n  for (const tool of tools) {\n    // Early builds returned synchronously, and a second registration of a name rejects.\n    Promise.resolve()\n      .then(() => context.registerTool(tool, { signal: controller.signal }))\n      .catch(() => {});\n  }\n  return () => controller.abort();\n}\n\nexport type UseAgentToolsOptions = {\n  /** Your own tools, registered next to the wallet tools. */\n  tools?: AgentTool[];\n  /** Set to false to register nothing, e.g. until the person opts in. */\n  enabled?: boolean;\n};\n\nconst noTools: AgentTool[] = [];\n\n/**\n * Registers the wallet tools, plus any of your own, while the component is\n * mounted. A new `tools` array registers everything again, so keep it stable.\n */\nexport function useAgentTools({ tools = noTools, enabled = true }: UseAgentToolsOptions = {}) {\n  const config = useConfig();\n  useEffect(() => {\n    if (!enabled) return;\n    return registerAgentTools([...walletAgentTools(config), ...tools]);\n  }, [config, enabled, tools]);\n}\n\n/** Drop inside your `Web3Provider` to give browser agents the wallet tools. Renders nothing. */\nexport function AgentTools(props: UseAgentToolsOptions) {\n  useAgentTools(props);\n  return null;\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/components/agent-tools.md",
  "categories": [
    "utilities"
  ],
  "type": "registry:component"
}