Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(mcp): add the Metaplex agent registry MCP server package
nirholasfd7acd9ab50a
diff --git a/package.json b/package.jsonindex 123eececc..df4ebd55b 100644--- a/package.json+++ b/package.json@@ -92,6 +92,7 @@"packages/intel-mcp","packages/marketplace-mcp","packages/x402-mcp",+ "packages/metaplex-agent-mcp","packages/agent-sniper","packages/provenance-mcp","packages/autopilot-mcp",diff --git a/packages/metaplex-agent-mcp/LICENSE b/packages/metaplex-agent-mcp/LICENSEnew file mode 100644index 000000000..dff21b7f4--- /dev/null+++ b/packages/metaplex-agent-mcp/LICENSE@@ -0,0 +1,20 @@+Copyright 2026 nirholas++All rights reserved.++This software is proprietary and may not be used, copied, modified, distributed,+translated, or made available to any third party without the express written+permission of the copyright owner.++No rights are granted by implication, estoppel, or otherwise. Use of this+software is subject to the terms of a separate license agreement with the+copyright owner.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.++IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/metaplex-agent-mcp/README.md b/packages/metaplex-agent-mcp/README.mdnew file mode 100644index 000000000..217d11cb2--- /dev/null+++ b/packages/metaplex-agent-mcp/README.md@@ -0,0 +1,129 @@+# @three-ws/metaplex-agent-mcp++Deploy AI agents on-chain into the **[Metaplex Agent Registry](https://www.metaplex.com/agents)** on Solana, from any MCP client.++One atomic transaction mints a **Metaplex Core asset** and registers its **EIP-8004 agent identity**, so the agent shows up on metaplex.com/agents with its own built-in wallet, reputation surface, and explorer pages. The default output reproduces the exact shape of the [three.ws](https://three.ws) Genesis 333 mints, verified byte-for-byte against the live assets:++- asset metadata as a self-contained `data:application/json;base64` URI (`name`, `image`, `animation_url` GLB)+- Royalties plugin (5% to the owner), VerifiedCreators (the signing wallet), ImmutableMetadata+- AgentIdentity plugin carrying the `eip-8004#registration-v1` document (`model.uri`, `active`, `x402Support`, `registrations`, `supportedTrust`)++Two signing lanes, both self-custodial:++- **Agents** sign with their own keypair (`SOLANA_SECRET_KEY`): `mint_onchain_agent`.+- **People** sign with Phantom, Solflare, Backpack, Ledger, or any Solana wallet: `prepare_agent_mint` builds the transaction, the wallet signs it, `send_signed_transaction` broadcasts it. No key ever touches the server.++Nothing is mocked: real Metaplex programs, real Solana, and devnet support for free end-to-end rehearsal.++## Install++```bash+npm install -g @three-ws/metaplex-agent-mcp+# or run ad hoc+npx -y @three-ws/metaplex-agent-mcp+```++## Setup++Claude Code:++```bash+claude mcp add metaplex-agent -e SOLANA_SECRET_KEY=<base58> -- npx -y @three-ws/metaplex-agent-mcp+```++Cursor / any MCP client (`mcp.json`):++```json+{+ "mcpServers": {+ "metaplex-agent": {+ "command": "npx",+ "args": ["-y", "@three-ws/metaplex-agent-mcp"],+ "env": { "SOLANA_SECRET_KEY": "<base58 secret key>" }+ }+ }+}+```++`SOLANA_SECRET_KEY` is optional: every read tool and the whole Phantom/Solflare flow works without it.++## Quick start++Rehearse on devnet for free, then go to mainnet:++```+1. agent_wallet {} → confirm the signer is funded+2. mint_onchain_agent { name: "Astra", description: "…",+ image: "https://…png", model_url: "https://…glb",+ x402_support: true, network: "devnet" } → preview (nothing broadcast)+3. …same call with confirm: true → minted + registered, links returned+4. get_onchain_agent { asset: "<returned asset>", network: "devnet" }+```++The mint costs ~0.007 SOL on mainnet (Core rent + identity PDA rent + fees).++## Tools++| Tool | What it does |+|---|---|+| `mint_onchain_agent` | Atomic mint + register, signed by your key. `confirm:true` gates the spend; anything else returns a full preview. |+| `prepare_agent_mint` | The same transaction, built for an external wallet (`wallet` param) to sign. Returns base64, already co-signed by the new asset keypair. |+| `send_signed_transaction` | Broadcast a wallet-signed transaction and poll to confirmation. |+| `register_agent_identity` | Enrol an already-minted Core asset in the Agent Registry (idempotent; the signer must be the asset authority). |+| `get_onchain_agent` | Read any registered agent: asset, plugins, decoded metadata + registration documents, identity PDA, built-in wallet + balance. |+| `agent_wallet` | An asset's built-in wallet (mpl-core Asset Signer PDA), any address, or the configured signer, with live SOL balance. |+| `build_registration` | The EIP-8004 registration JSON + `data:` URI, fully offline. |+| `list_onchain_agents` | Latest registrations from the live three.ws `/api/deployments` feed (Solana by default, `all_chains:true` for EVM ERC-8004 too). |++## Customization++Every field the mint touches is a parameter: owner, collection, royalty basis points and splits, verified creator, immutable metadata, on-chain Attributes, permanent freeze/transfer/burn delegates, AddBlocker, off-chain metadata attributes, `external_url`, services, trust models, registration entries, and full `metadata_uri` / `registration_uri` overrides for documents you host yourself. The defaults are the Genesis 333 values, so calling with just `name`, `description`, `image`, and `model_url` produces an asset indistinguishable in shape from the originals.++## Safety++- `mint_onchain_agent` and `register_agent_identity` broadcast **only** with `confirm: true` (set `REQUIRE_CONFIRM=false` to opt out); previews cost nothing.+- Keys stay yours: `SOLANA_SECRET_KEY` or a per-call `secret`, never a custodial wallet. The wallet lane needs no key at all.+- Balances are checked before spending, RPC endpoints must be HTTPS, and devnet is a first-class target for rehearsal.++## Environment variables++| Variable | Default | Meaning |+|---|---|---|+| `SOLANA_SECRET_KEY` | unset | Base58 secret key or JSON byte array for the minting wallet. |+| `SOLANA_RPC_URL` | public endpoint | HTTPS RPC. Bring your own for production traffic. |+| `METAPLEX_AGENT_NETWORK` | `mainnet` | Default cluster (`mainnet` or `devnet`); every tool takes a per-call `network` too. |+| `REQUIRE_CONFIRM` | `true` | Gate spends behind `confirm: true`. |+| `THREE_WS_BASE` | `https://three.ws` | Host for the deployments feed. |++## Library use++The builders are exported for direct embedding (web apps, scripts):++```js+import { buildAgentMint, buildUmi } from '@three-ws/metaplex-agent-mcp/lib';++const umi = buildUmi({ network: 'devnet', secret: process.env.SOLANA_SECRET_KEY });+const mint = buildAgentMint(umi, {+ network: 'devnet',+ creator: umi.identity.publicKey.toString(),+ name: 'Astra',+ description: 'An autonomous 3D agent',+ image: 'https://example.com/astra.png',+ modelUrl: 'https://example.com/astra.glb',+ x402Support: true,+});+await mint.builder.sendAndConfirm(umi);+```++## Requirements++- Node 20++- SOL on the target network for minting (~0.007 SOL per agent on mainnet; devnet is free via faucet)++## Links++- three.ws: https://three.ws+- Live deployments feed: https://three.ws/deployments+- Metaplex Agent Registry: https://www.metaplex.com/agents+- Metaplex docs: https://www.metaplex.com/docs/agents+- Source: https://github.com/nirholas/three.ws/tree/main/packages/metaplex-agent-mcpdiff --git a/packages/metaplex-agent-mcp/package.json b/packages/metaplex-agent-mcp/package.jsonnew file mode 100644index 000000000..076b33657--- /dev/null+++ b/packages/metaplex-agent-mcp/package.json@@ -0,0 +1,67 @@+{+ "name": "@three-ws/metaplex-agent-mcp",+ "version": "0.1.0",+ "mcpName": "io.github.nirholas/metaplex-agent",+ "description": "Deploy AI agents on-chain into the Metaplex Agent Registry on Solana, exactly the way the three.ws Genesis 333 shipped: one atomic transaction mints a Metaplex Core asset (data: URI metadata, verified creator, royalties, immutable metadata) and registers its EIP-8004 agent identity. Agents sign with their own key; people sign with Phantom, Solflare, or any Solana wallet via the prepare/send flow. Every Core plugin and every metadata field is customizable.",+ "type": "module",+ "author": "nirholas <[email protected]>",+ "license": "SEE LICENSE IN LICENSE",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/metaplex-agent-mcp"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "keywords": [+ "mcp",+ "model-context-protocol",+ "three.ws",+ "metaplex",+ "agent-registry",+ "mpl-core",+ "solana",+ "onchain-agent",+ "erc-8004",+ "eip-8004",+ "x402",+ "ai-agent",+ "nft"+ ],+ "publishConfig": {+ "access": "public"+ },+ "files": [+ "src",+ "server.json",+ "README.md",+ "LICENSE"+ ],+ "bin": {+ "metaplex-agent-mcp": "src/index.js"+ },+ "main": "./src/index.js",+ "exports": {+ ".": "./src/index.js",+ "./lib": "./src/lib/index.js"+ },+ "engines": {+ "node": ">=20"+ },+ "scripts": {+ "start": "node src/index.js",+ "test": "node --test \"test/**/*.test.mjs\"",+ "inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"+ },+ "dependencies": {+ "@metaplex-foundation/mpl-agent-registry": "^0.2.6",+ "@metaplex-foundation/mpl-core": "^1.10.0",+ "@metaplex-foundation/umi": "^1.5.1",+ "@metaplex-foundation/umi-bundle-defaults": "^1.5.1",+ "@modelcontextprotocol/sdk": "^1.29.0",+ "bs58": "^6.0.0",+ "zod": "^3.23.8"+ }+}diff --git a/packages/metaplex-agent-mcp/server.json b/packages/metaplex-agent-mcp/server.jsonnew file mode 100644index 000000000..fa8a39b4d--- /dev/null+++ b/packages/metaplex-agent-mcp/server.json@@ -0,0 +1,52 @@+{+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",+ "name": "io.github.nirholas/metaplex-agent",+ "title": "Metaplex Agent Registry",+ "description": "Deploy AI agents on-chain on Solana: one atomic tx mints a Metaplex Core asset and registers its EIP-8004 agent identity. By three.ws.",+ "websiteUrl": "https://three.ws",+ "icons": [{ "src": "https://three.ws/three-ws-mcp-icon.svg", "mimeType": "image/svg+xml", "sizes": ["any"] }],+ "repository": {+ "url": "https://github.com/nirholas/three.ws",+ "source": "github",+ "subfolder": "packages/metaplex-agent-mcp"+ },+ "version": "0.1.0",+ "packages": [+ {+ "registryType": "npm",+ "identifier": "@three-ws/metaplex-agent-mcp",+ "version": "0.1.0",+ "runtimeHint": "npx",+ "transport": { "type": "stdio" },+ "environmentVariables": [+ {+ "name": "SOLANA_SECRET_KEY",+ "description": "Base58 secret key (or JSON byte array) for the minting wallet. Optional: read tools and the Phantom/Solflare prepare/send flow work without it.",+ "isRequired": false,+ "isSecret": true,+ "format": "string"+ },+ {+ "name": "SOLANA_RPC_URL",+ "description": "HTTPS Solana RPC endpoint. Defaults to the public endpoint for the configured network; bring your own (Helius / Quicknode / Triton) for production.",+ "isRequired": false,+ "format": "string"+ },+ {+ "name": "METAPLEX_AGENT_NETWORK",+ "description": "Default cluster: mainnet or devnet. Defaults to mainnet; every tool also takes a per-call network.",+ "isRequired": false,+ "default": "mainnet",+ "format": "string"+ },+ {+ "name": "REQUIRE_CONFIRM",+ "description": "Refuse to broadcast a mint or registration until the call is re-issued with confirm=true. Default true.",+ "isRequired": false,+ "default": "true",+ "format": "boolean"+ }+ ]+ }+ ]+}diff --git a/packages/metaplex-agent-mcp/smithery.yaml b/packages/metaplex-agent-mcp/smithery.yamlnew file mode 100644index 000000000..8b678ccab--- /dev/null+++ b/packages/metaplex-agent-mcp/smithery.yaml@@ -0,0 +1,44 @@+# Smithery deployment config for @three-ws/metaplex-agent-mcp+# https://smithery.ai/docs/config#smitheryyaml+#+# Deploy AI agents on-chain into the Metaplex Agent Registry on Solana,+# Genesis-333 style: one atomic tx mints a Metaplex Core asset and registers+# its EIP-8004 agent identity. Read tools and the Phantom/Solflare+# prepare/send flow work with no key; only the self-custody mint needs one.+startCommand:+ type: stdio+ configSchema:+ type: object+ properties:+ SOLANA_SECRET_KEY:+ type: string+ title: Solana secret key+ description: Base58 secret key (or JSON byte array) for the minting wallet. Optional. Read tools and the wallet prepare/send flow work without it.+ SOLANA_RPC_URL:+ type: string+ title: Solana RPC URL+ description: HTTPS Solana RPC endpoint. Defaults to the public endpoint for the configured network. Bring your own (Helius / Quicknode / Triton) for production.+ METAPLEX_AGENT_NETWORK:+ type: string+ title: Default network+ default: mainnet+ enum: [mainnet, devnet]+ description: Default Solana cluster. Every tool also takes a per-call network.+ REQUIRE_CONFIRM:+ type: boolean+ title: Require explicit confirm+ default: true+ description: Refuse to broadcast a mint or registration until re-issued with confirm=true.+ required: []+ commandFunction: |+ (config) => ({+ command: 'npx',+ args: ['-y', '@three-ws/metaplex-agent-mcp'],+ env: Object.assign(+ {},+ config.SOLANA_SECRET_KEY ? { SOLANA_SECRET_KEY: config.SOLANA_SECRET_KEY } : {},+ config.SOLANA_RPC_URL ? { SOLANA_RPC_URL: config.SOLANA_RPC_URL } : {},+ config.METAPLEX_AGENT_NETWORK ? { METAPLEX_AGENT_NETWORK: config.METAPLEX_AGENT_NETWORK } : {},+ config.REQUIRE_CONFIRM != null ? { REQUIRE_CONFIRM: String(config.REQUIRE_CONFIRM) } : {}+ )+ })diff --git a/packages/metaplex-agent-mcp/src/config.js b/packages/metaplex-agent-mcp/src/config.jsnew file mode 100644index 000000000..128bb0724--- /dev/null+++ b/packages/metaplex-agent-mcp/src/config.js@@ -0,0 +1,87 @@+// Centralized env for the Metaplex Agent Registry MCP.+//+// This server is user-keyed: mints are signed by a Solana keypair the operator+// supplies (SOLANA_SECRET_KEY) or a per-call `secret` overrides. We never bake+// in a key. The read tools and the prepare/send wallet flow (Phantom, Solflare,+// any Solana wallet) work with no key at all.++export function env(key, fallback) {+ const v = process.env[key];+ return v !== undefined && String(v).trim() !== '' ? String(v).trim() : fallback;+}++// Default cluster for every tool. Any tool can override per-call with `network`.+export const NETWORK = (() => {+ const raw = env('METAPLEX_AGENT_NETWORK', env('SOLANA_NETWORK', 'mainnet')).toLowerCase();+ if (raw === 'devnet') return 'devnet';+ if (raw === 'mainnet' || raw === 'mainnet-beta') return 'mainnet';+ throw Object.assign(+ new Error(`METAPLEX_AGENT_NETWORK must be "mainnet" or "devnet" (got "${raw}")`),+ { code: 'bad_network_config' },+ );+})();++export const DEFAULT_RPC = {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};++// Validate the Solana RPC endpoint at load. Mint transactions are signed and+// broadcast over this URL, so a plaintext-http endpoint (outside localhost) is+// a MITM risk.+function validateRpcUrl(raw) {+ let u;+ try {+ u = new URL(raw);+ } catch {+ throw Object.assign(new Error(`SOLANA_RPC_URL is not a valid URL: "${raw}"`), { code: 'bad_rpc_url' });+ }+ if (u.protocol === 'https:') return raw;+ const isLocal = ['localhost', '127.0.0.1', '0.0.0.0', '::1'].includes(u.hostname);+ if (u.protocol === 'http:' && isLocal) return raw;+ throw Object.assign(+ new Error(+ `SOLANA_RPC_URL must be https (got "${u.protocol}//${u.hostname}"). Only http://localhost is allowed for local dev.`,+ ),+ { code: 'insecure_rpc_url' },+ );+}++// RPC for the configured NETWORK. Bring your own (Helius / Quicknode / Triton)+// for production traffic; the public endpoints rate-limit hard.+export const SOLANA_RPC_URL = validateRpcUrl(env('SOLANA_RPC_URL', DEFAULT_RPC[NETWORK]));++/** Resolve the RPC endpoint for a per-call network override. */+export function rpcFor(network) {+ const net = network === 'devnet' ? 'devnet' : 'mainnet';+ return net === NETWORK ? SOLANA_RPC_URL : DEFAULT_RPC[net];+}++// Optional default signer (base58 secret key, or a JSON byte array). The mint+// and register tools accept a per-call `secret` that overrides this.+export const SOLANA_DEFAULT_SECRET = env('SOLANA_SECRET_KEY', env('FUNDER_SECRET', ''));++// three.ws API host: serves the /api/deployments cross-chain registration feed.+export const THREE_WS_BASE = env('THREE_WS_BASE', 'https://three.ws').replace(/\/+$/, '');++// Broadcasting a mint requires an explicit confirm:true unless opted out.+export const REQUIRE_CONFIRM = (() => {+ const raw = env('REQUIRE_CONFIRM');+ if (raw === undefined) return true;+ return !['0', 'false', 'no', 'off'].includes(String(raw).toLowerCase());+})();++// Per-request timeout (ms) for off-chain fetches (registration docs, the feed).+export const HTTP_TIMEOUT_MS = (() => {+ const raw = env('THREE_WS_TIMEOUT_MS');+ if (raw === undefined) return 30000;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) {+ throw Object.assign(new Error(`THREE_WS_TIMEOUT_MS must be a positive number (got "${raw}")`), {+ code: 'bad_config',+ });+ }+ return n;+})();++export const USER_AGENT = '@three-ws/metaplex-agent-mcp';diff --git a/packages/metaplex-agent-mcp/src/index.js b/packages/metaplex-agent-mcp/src/index.jsnew file mode 100755index 000000000..01b00a1fc--- /dev/null+++ b/packages/metaplex-agent-mcp/src/index.js@@ -0,0 +1,130 @@+#!/usr/bin/env node+// @three-ws/metaplex-agent-mcp: MCP server entry point.+//+// Deploy AI agents on-chain into the Metaplex Agent Registry on Solana, the+// exact way the three.ws Genesis 333 shipped:+// • mint_onchain_agent : atomic mint + register, signed by the agent's own key+// • prepare_agent_mint : the same tx built for Phantom/Solflare/any wallet to sign+// • send_signed_transaction : broadcast a wallet-signed tx and confirm it+// • register_agent_identity : enrol an already-minted Core asset+// • get_onchain_agent : read any registered agent (asset, docs, wallet)+// • agent_wallet : an agent's built-in wallet (Asset Signer PDA) + balance+// • build_registration : the EIP-8004 document + data: URI, offline+// • list_onchain_agents : the live registration feed+//+// Self-custodial: mints are signed by YOUR key (SOLANA_SECRET_KEY) or your own+// browser wallet via prepare/send. The read tools and the wallet flow need no+// key at all. Real Metaplex programs on real Solana; nothing is mocked.+//+// Run standalone:+// SOLANA_SECRET_KEY=<base58> node packages/metaplex-agent-mcp/src/index.js+//+// Or wire into Claude Code / Cursor: see README.md.++import { realpathSync } from 'node:fs';+import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';++import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++import { def as mintOnchainAgent } from './tools/mint-onchain-agent.js';+import { def as prepareAgentMint } from './tools/prepare-agent-mint.js';+import { def as sendSignedTransaction } from './tools/send-signed-transaction.js';+import { def as registerAgentIdentity } from './tools/register-agent-identity.js';+import { def as getOnchainAgent } from './tools/get-onchain-agent.js';+import { def as agentWallet } from './tools/agent-wallet.js';+import { def as buildRegistration } from './tools/build-registration.js';+import { def as listOnchainAgents } from './tools/list-onchain-agents.js';++const require = createRequire(import.meta.url);+const { version: PKG_VERSION } = require('../package.json');++export const TOOLS = [+ mintOnchainAgent,+ prepareAgentMint,+ sendSignedTransaction,+ registerAgentIdentity,+ getOnchainAgent,+ agentWallet,+ buildRegistration,+ listOnchainAgents,+];++/**+ * Construct a fully-registered McpServer without connecting a transport or+ * requiring a signer. Registration is env-free; only the signing tools need+ * SOLANA_SECRET_KEY. Safe to import from tests.+ * @returns {McpServer}+ */+export function buildServer() {+ const server = new McpServer(+ { name: 'metaplex-agent-mcp', title: 'Metaplex Agent Registry', version: PKG_VERSION },+ {+ capabilities: { tools: {} },+ instructions:+ 'Metaplex Agent Registry MCP by three.ws: put an AI agent on-chain on Solana with its own wallet, ' ++ 'identity, and reputation surface, Genesis-333 style. mint_onchain_agent is the self-custody path ' ++ '(one atomic tx, signed by SOLANA_SECRET_KEY, ~0.007 SOL, gated by confirm:true). prepare_agent_mint ' ++ '+ send_signed_transaction are the SAME mint for a human wallet (Phantom, Solflare, anything) with ' ++ 'no key configured. register_agent_identity enrols an existing Core asset. get_onchain_agent, ' ++ 'agent_wallet, build_registration, and list_onchain_agents are read-only. Every Core plugin and ' ++ 'metadata field is customizable; the defaults reproduce the three.ws Genesis mint shape exactly.',+ },+ );++ for (const tool of TOOLS) {+ server.registerTool(+ tool.name,+ {+ title: tool.title,+ description: tool.description,+ inputSchema: tool.inputSchema,+ annotations: tool.annotations,+ },+ async (args, extra) => {+ try {+ const result = await tool.handler(args, extra);+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);+ return { content: [{ type: 'text', text }] };+ } catch (err) {+ const payload = {+ ok: false,+ error: err?.code || 'unhandled',+ message: err?.message || String(err),+ ...(err?.status ? { status: err.status } : {}),+ };+ return {+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],+ isError: true,+ };+ }+ },+ );+ }++ return server;+}++async function main() {+ const server = buildServer();+ const transport = new StdioServerTransport();+ await server.connect(transport);+ console.error(`[metaplex-agent-mcp@${PKG_VERSION}] connected over stdio with ${TOOLS.length} tools`);+}++function isProcessEntryPoint() {+ if (!process.argv[1]) return false;+ try {+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;+ } catch {+ return false;+ }+}++if (isProcessEntryPoint()) {+ main().catch((err) => {+ console.error('[metaplex-agent-mcp] fatal:', err);+ process.exit(1);+ });+}diff --git a/packages/metaplex-agent-mcp/src/lib/index.js b/packages/metaplex-agent-mcp/src/lib/index.jsnew file mode 100644index 000000000..a286d4712--- /dev/null+++ b/packages/metaplex-agent-mcp/src/lib/index.js@@ -0,0 +1,27 @@+// Library surface for embedding the Genesis-style mint outside MCP (web apps,+// scripts, the three.ws deploy page). Everything here is pure Umi + fetch.++export {+ EIP_8004_REGISTRATION_TYPE,+ jsonDataUri,+ buildAssetMetadata,+ buildRegistrationDoc,+ chainRegistration,+ threeWsRegistration,+ decodeJsonUri,+} from './registration.js';++export { buildPlugins, buildAgentMint } from './mint.js';++export {+ LAMPORTS_PER_SOL,+ EST_MINT_LAMPORTS,+ EST_REGISTER_LAMPORTS,+ parseSecretKey,+ buildUmi,+ solBalance,+ assetSignerAddress,+ agentLinks,+ txLink,+ toBase58Signature,+} from './solana.js';diff --git a/packages/metaplex-agent-mcp/src/lib/mint.js b/packages/metaplex-agent-mcp/src/lib/mint.jsnew file mode 100644index 000000000..719a2e931--- /dev/null+++ b/packages/metaplex-agent-mcp/src/lib/mint.js@@ -0,0 +1,174 @@+// The atomic Genesis-style mint: one transaction that creates a Metaplex Core+// asset AND registers its Agent Identity in the Metaplex Agent Registry.+//+// Shape (mirrors the three.ws Genesis 333, verified against the live assets):+// • asset uri data: URI of { name, image, animation_url }+// • Royalties plugin 500 bps to the owner by default, ruleSet None+// • VerifiedCreators the signing wallet, verified (it signs this tx)+// • ImmutableMetadata on by default+// • AgentIdentity data: URI of the EIP-8004 registration document+//+// Every knob is exposed: royalty split, extra creators, attributes, permanent+// delegate plugins, collection membership, a different owner, and full control+// of both JSON documents (or complete URI overrides).++import { create, ruleSet } from '@metaplex-foundation/mpl-core';+import { generateSigner, publicKey as umiPublicKey } from '@metaplex-foundation/umi';+import { registerIdentityV1 } from '@metaplex-foundation/mpl-agent-registry';++import {+ buildAssetMetadata,+ buildRegistrationDoc,+ chainRegistration,+ threeWsRegistration,+ jsonDataUri,+} from './registration.js';++/**+ * Genesis-style plugin list for a Core `create`.+ * @param {object} p+ * @param {string} p.creator base58 wallet that signs the mint (royalty + verified-creator default)+ */+export function buildPlugins({+ creator,+ royaltyBasisPoints = 500,+ royaltyCreators,+ verifiedCreator = true,+ immutableMetadata = true,+ attributes,+ permanentFreeze = false,+ permanentTransfer = false,+ permanentBurn = false,+ addBlocker = false,+} = {}) {+ const plugins = [];+ const bps = Number(royaltyBasisPoints);+ if (!Number.isInteger(bps) || bps < 0 || bps > 10000) {+ throw Object.assign(new Error(`royalty_basis_points must be an integer 0..10000 (got ${royaltyBasisPoints})`), {+ code: 'validation_error',+ });+ }+ if (bps > 0) {+ const creators = (royaltyCreators?.length ? royaltyCreators : [{ address: creator, percentage: 100 }]).map(+ (c) => ({ address: umiPublicKey(c.address), percentage: Number(c.percentage) }),+ );+ const total = creators.reduce((sum, c) => sum + c.percentage, 0);+ if (total !== 100) {+ throw Object.assign(new Error(`royalty creator percentages must sum to 100 (got ${total})`), {+ code: 'validation_error',+ });+ }+ plugins.push({ type: 'Royalties', basisPoints: bps, creators, ruleSet: ruleSet('None') });+ }+ if (verifiedCreator) {+ plugins.push({+ type: 'VerifiedCreators',+ signatures: [{ address: umiPublicKey(creator), verified: true }],+ });+ }+ if (immutableMetadata) plugins.push({ type: 'ImmutableMetadata' });+ if (Array.isArray(attributes) && attributes.length) {+ plugins.push({+ type: 'Attributes',+ attributeList: attributes.map((a) => ({ key: String(a.key), value: String(a.value) })),+ });+ }+ if (permanentFreeze) plugins.push({ type: 'PermanentFreezeDelegate', frozen: false });+ if (permanentTransfer) plugins.push({ type: 'PermanentTransferDelegate' });+ if (permanentBurn) plugins.push({ type: 'PermanentBurnDelegate' });+ if (addBlocker) plugins.push({ type: 'AddBlocker' });+ return plugins;+}++/**+ * Assemble the whole mint: documents, URIs, and the single-transaction builder+ * (`create` + `registerIdentityV1`). The caller decides how to sign it:+ * `sendAndConfirm` with a keypair identity, or `buildAndSign` behind a noop+ * signer for the Phantom/Solflare prepare flow.+ *+ * @returns {{ builder, assetSigner, assetMetadata, metadataUri, registration, registrationUri }}+ */+export function buildAgentMint(umi, {+ network,+ creator,+ owner,+ collection,+ name,+ description = '',+ image,+ modelUrl,+ externalUrl,+ metadataAttributes,+ metadataUri,+ services,+ active = true,+ x402Support = false,+ registrations,+ threeWsAgentId,+ supportedTrust,+ registrationUri,+ royaltyBasisPoints,+ royaltyCreators,+ verifiedCreator,+ immutableMetadata,+ attributes,+ permanentFreeze,+ permanentTransfer,+ permanentBurn,+ addBlocker,+} = {}) {+ const assetSigner = generateSigner(umi);+ const assetAddress = assetSigner.publicKey.toString();++ const assetMetadata = metadataUri+ ? null+ : buildAssetMetadata({ name, image, animationUrl: modelUrl, description: undefined, externalUrl, attributes: metadataAttributes });+ const uri = metadataUri || jsonDataUri(assetMetadata);++ const regEntries = registrations?.length+ ? registrations+ : threeWsAgentId+ ? [threeWsRegistration(threeWsAgentId)]+ : [chainRegistration(assetAddress, network)];+ const registration = registrationUri+ ? null+ : buildRegistrationDoc({+ name,+ description,+ image,+ modelUrl,+ services,+ active,+ x402Support,+ registrations: regEntries,+ supportedTrust,+ });+ const agentRegistrationUri = registrationUri || jsonDataUri(registration);++ const createArgs = {+ asset: assetSigner,+ name,+ uri,+ plugins: buildPlugins({+ creator,+ royaltyBasisPoints,+ royaltyCreators,+ verifiedCreator,+ immutableMetadata,+ attributes,+ permanentFreeze,+ permanentTransfer,+ permanentBurn,+ addBlocker,+ }),+ };+ if (owner) createArgs.owner = umiPublicKey(owner);+ if (collection) createArgs.collection = umiPublicKey(collection);++ const registerArgs = { asset: assetSigner.publicKey, agentRegistrationUri };+ if (collection) registerArgs.collection = umiPublicKey(collection);++ const builder = create(umi, createArgs).add(registerIdentityV1(umi, registerArgs));++ return { builder, assetSigner, assetMetadata, metadataUri: uri, registration, registrationUri: agentRegistrationUri };+}diff --git a/packages/metaplex-agent-mcp/src/lib/registration.js b/packages/metaplex-agent-mcp/src/lib/registration.jsnew file mode 100644index 000000000..793e8fb17--- /dev/null+++ b/packages/metaplex-agent-mcp/src/lib/registration.js@@ -0,0 +1,131 @@+// EIP-8004 registration documents and Core asset metadata, Genesis-333 style.+//+// The three.ws Genesis 333 established a concrete on-chain shape for a 3D AI+// agent on Solana, and this module reproduces it byte-for-byte:+//+// Asset metadata URI data:application/json;base64 of+// { name, image, animation_url }+// Agent Identity URI data:application/json;base64 of+// { type: <eip-8004 registration-v1>, name, description,+// image, model: { uri }, active, x402Support,+// registrations, supportedTrust }+//+// data: URIs are fully self-contained: nothing to pin, nothing that can rot,+// and the whole identity lives in the transaction. Key ORDER matters for+// byte-exactness, so both builders assemble their objects field by field in+// the Genesis order and only ever append optional fields in that same order.++export const EIP_8004_REGISTRATION_TYPE = 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1';++const b64 = (obj) => Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');++/** Wrap a JSON document in a data:application/json;base64 URI. */+export function jsonDataUri(doc) {+ return `data:application/json;base64,${b64(doc)}`;+}++/**+ * The Core asset's token-metadata document, Genesis order:+ * name, image, animation_url, then optional description / external_url /+ * attributes for callers that want more than the Genesis minimum.+ */+export function buildAssetMetadata({ name, image, animationUrl, description, externalUrl, attributes } = {}) {+ if (!name) throw Object.assign(new Error('asset metadata requires a name'), { code: 'validation_error' });+ const doc = { name };+ if (image) doc.image = image;+ if (animationUrl) doc.animation_url = animationUrl;+ if (description) doc.description = description;+ if (externalUrl) doc.external_url = externalUrl;+ if (Array.isArray(attributes) && attributes.length) {+ doc.attributes = attributes.map((a) => ({ trait_type: String(a.key ?? a.trait_type), value: String(a.value) }));+ }+ return doc;+}++/**+ * The EIP-8004 registration-v1 document, Genesis order:+ * type, name, description, image, model, services, active, x402Support,+ * registrations, supportedTrust.+ *+ * `registrations` entries are `{ agentId, agentRegistry }`. The Genesis mints+ * point back at their home registry (`https://three.ws`); a standalone agent+ * conventionally points at the chain registry (`solana:101:metaplex`).+ */+export function buildRegistrationDoc({+ name,+ description,+ image,+ modelUrl,+ services,+ active = true,+ x402Support = false,+ registrations = [],+ supportedTrust = ['reputation'],+} = {}) {+ if (!name) throw Object.assign(new Error('registration requires a name'), { code: 'validation_error' });+ const doc = { type: EIP_8004_REGISTRATION_TYPE, name, description: description || '' };+ if (image) doc.image = image;+ if (modelUrl) doc.model = { uri: modelUrl };+ if (Array.isArray(services) && services.length) {+ doc.services = services.map((s) => ({ name: String(s.name), endpoint: String(s.endpoint) }));+ }+ doc.active = active !== false;+ doc.x402Support = Boolean(x402Support);+ if (Array.isArray(registrations) && registrations.length) {+ doc.registrations = registrations.map((r) => ({+ agentId: String(r.agentId ?? r.agent_id),+ agentRegistry: String(r.agentRegistry ?? r.agent_registry),+ }));+ }+ doc.supportedTrust = Array.isArray(supportedTrust) && supportedTrust.length ? supportedTrust.map(String) : ['reputation'];+ return doc;+}++/**+ * Default `registrations` for an agent that has no home registry: the chain+ * registry itself, keyed by the asset address (Metaplex docs convention).+ */+export function chainRegistration(assetPubkey, network) {+ return { agentId: String(assetPubkey), agentRegistry: `solana:${network === 'devnet' ? 103 : 101}:metaplex` };+}++/** The Genesis-exact registration entry for a three.ws-hosted agent. */+export function threeWsRegistration(agentId) {+ return { agentId: String(agentId), agentRegistry: 'https://three.ws' };+}++/**+ * Resolve a registration or metadata URI to its JSON document.+ * data: URIs decode locally; http(s) URIs are fetched with a timeout.+ */+export async function decodeJsonUri(uri, { timeoutMs = 30000 } = {}) {+ if (typeof uri !== 'string' || !uri) return null;+ if (uri.startsWith('data:')) {+ const comma = uri.indexOf(',');+ if (comma < 0) return null;+ const meta = uri.slice(5, comma);+ const payload = uri.slice(comma + 1);+ try {+ const raw = meta.includes('base64')+ ? Buffer.from(payload, 'base64').toString('utf8')+ : decodeURIComponent(payload);+ return JSON.parse(raw);+ } catch {+ return null;+ }+ }+ if (uri.startsWith('https://') || uri.startsWith('http://')) {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);+ try {+ const res = await fetch(uri, { signal: ctrl.signal, headers: { accept: 'application/json' } });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+ }+ return null;+}diff --git a/packages/metaplex-agent-mcp/src/lib/solana.js b/packages/metaplex-agent-mcp/src/lib/solana.jsnew file mode 100644index 000000000..cbcb1160e--- /dev/null+++ b/packages/metaplex-agent-mcp/src/lib/solana.js@@ -0,0 +1,95 @@+// Umi construction, key handling, balances, and explorer links.++import bs58 from 'bs58';+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import { mplCore, findAssetSignerPda } from '@metaplex-foundation/mpl-core';+import { keypairIdentity, publicKey as umiPublicKey } from '@metaplex-foundation/umi';+import { mplAgentIdentity } from '@metaplex-foundation/mpl-agent-registry';++import { NETWORK, rpcFor, SOLANA_DEFAULT_SECRET } from '../config.js';++export const LAMPORTS_PER_SOL = 1_000_000_000;++// Conservative cost ceilings, mirrored from the three.ws deploy pipeline:+// a Core mint is ~0.004 SOL (rent + fee), the identity PDA ~0.003 SOL.+export const EST_MINT_LAMPORTS = Math.floor(0.004 * LAMPORTS_PER_SOL);+export const EST_REGISTER_LAMPORTS = Math.floor(0.003 * LAMPORTS_PER_SOL);++/** Parse a base58 secret key or a JSON byte array into a 64-byte secret. */+export function parseSecretKey(secret) {+ const raw = String(secret || '').trim();+ if (!raw) {+ throw Object.assign(+ new Error('No Solana key configured. Set SOLANA_SECRET_KEY (base58 or JSON byte array) or pass `secret`.'),+ { code: 'no_signer' },+ );+ }+ let bytes;+ if (raw.startsWith('[')) {+ try {+ bytes = Uint8Array.from(JSON.parse(raw));+ } catch {+ throw Object.assign(new Error('secret looks like a JSON array but does not parse'), { code: 'bad_secret' });+ }+ } else {+ try {+ bytes = bs58.decode(raw);+ } catch {+ throw Object.assign(new Error('secret is not valid base58'), { code: 'bad_secret' });+ }+ }+ if (bytes.length !== 64) {+ throw Object.assign(new Error(`secret must be a 64-byte keypair (got ${bytes.length} bytes)`), {+ code: 'bad_secret',+ });+ }+ return bytes;+}++/**+ * Build a Umi instance with the Core and Agent Identity programs registered.+ * Pass `secret` (or rely on SOLANA_SECRET_KEY) to attach a signing identity;+ * omit both for read-only or noop-signer (wallet prep) usage.+ */+export function buildUmi({ network = NETWORK, secret, requireSigner = false } = {}) {+ const umi = createUmi(rpcFor(network)).use(mplCore()).use(mplAgentIdentity());+ const material = secret !== undefined && String(secret).trim() !== '' ? secret : SOLANA_DEFAULT_SECRET;+ if (material) {+ const keypair = umi.eddsa.createKeypairFromSecretKey(parseSecretKey(material));+ umi.use(keypairIdentity(keypair));+ } else if (requireSigner) {+ parseSecretKey(''); // throws no_signer with the actionable message+ }+ return umi;+}++/** SOL balance of an address, as a number of SOL. */+export async function solBalance(umi, address) {+ const value = await umi.rpc.getBalance(umiPublicKey(address));+ return Number(value.basisPoints) / LAMPORTS_PER_SOL;+}++/** The asset's built-in wallet: the mpl-core Asset Signer PDA. */+export function assetSignerAddress(umi, asset) {+ const [pda] = findAssetSignerPda(umi, { asset: umiPublicKey(asset) });+ return pda.toString();+}++const cluster = (network) => (network === 'devnet' ? '?cluster=devnet' : '');++/** Everywhere a freshly minted agent can be seen. */+export function agentLinks(asset, network = NETWORK) {+ return {+ metaplex_agents: `https://www.metaplex.com/agents/${asset}`,+ core_explorer: `https://core.metaplex.com/explorer/${asset}${network === 'devnet' ? '?env=devnet' : ''}`,+ solscan: `https://solscan.io/account/${asset}${cluster(network)}`,+ };+}++export function txLink(signature, network = NETWORK) {+ return `https://solscan.io/tx/${signature}${cluster(network)}`;+}++export function toBase58Signature(signature) {+ return typeof signature === 'string' ? signature : bs58.encode(signature);+}diff --git a/packages/metaplex-agent-mcp/src/tools/agent-wallet.js b/packages/metaplex-agent-mcp/src/tools/agent-wallet.jsnew file mode 100644index 000000000..dbfcaf5f7--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/agent-wallet.js@@ -0,0 +1,62 @@+// `agent_wallet`: resolve a wallet and its SOL balance. Three modes:+// asset → the asset's built-in wallet (mpl-core Asset Signer PDA)+// address → any wallet, verbatim+// neither → the configured signer (the wallet that pays for mints)++import { z } from 'zod';++import { NETWORK, SOLANA_DEFAULT_SECRET } from '../config.js';+import { buildUmi, solBalance, assetSignerAddress } from '../lib/solana.js';++export const def = {+ name: 'agent_wallet',+ title: "An agent's built-in wallet, or the signer wallet, with balance",+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Show a wallet address and its live SOL balance. Pass `asset` to derive an on-chain agent's built-in wallet " ++ '(the Metaplex Core Asset Signer PDA, the wallet shown on metaplex.com/agents). Pass `address` to inspect ' ++ 'any wallet. Pass neither to see the configured signing wallet, e.g. to confirm it is funded before ' ++ 'mint_onchain_agent. Read-only; never moves funds.',+ inputSchema: {+ asset: z.string().min(32).max(44).optional().describe("A Core asset address: derives that agent's built-in wallet."),+ address: z.string().min(32).max(44).optional().describe('A wallet address to inspect verbatim.'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Cluster. Defaults to the configured network.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ if (args.asset && args.address) {+ throw Object.assign(new Error('pass either `asset` or `address`, not both'), { code: 'validation_error' });+ }+ const umi = buildUmi({ network });++ let address;+ let kind;+ if (args.asset) {+ address = assetSignerAddress(umi, args.asset);+ kind = 'asset_signer';+ } else if (args.address) {+ address = String(args.address).trim();+ kind = 'address';+ } else {+ if (!SOLANA_DEFAULT_SECRET) {+ throw Object.assign(+ new Error('No `asset` or `address` given and no SOLANA_SECRET_KEY configured. Pass one, or set a signer.'),+ { code: 'no_signer' },+ );+ }+ const signerUmi = buildUmi({ network, requireSigner: true });+ address = signerUmi.identity.publicKey.toString();+ kind = 'signer';+ }++ const sol = await solBalance(umi, address);+ return {+ ok: true,+ network,+ kind,+ address,+ sol,+ ...(args.asset ? { asset: args.asset } : {}),+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/build-registration.js b/packages/metaplex-agent-mcp/src/tools/build-registration.jsnew file mode 100644index 000000000..04e8b5c8e--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/build-registration.js@@ -0,0 +1,65 @@+// `build_registration`: pure document builder. Produces the EIP-8004+// registration JSON and its data: URI without touching the chain, so an agent+// can preview, host, or hand-tune its identity before minting.++import { z } from 'zod';++import { NETWORK } from '../config.js';+import { buildRegistrationDoc, chainRegistration, threeWsRegistration, jsonDataUri } from '../lib/registration.js';++export const def = {+ name: 'build_registration',+ title: 'Build an EIP-8004 registration document (no chain access)',+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },+ description:+ 'Build the Genesis-style EIP-8004 registration-v1 JSON document and its self-contained ' ++ 'data:application/json;base64 URI, without touching Solana. Use it to preview exactly what ' ++ 'mint_onchain_agent / register_agent_identity will write on-chain, or to host the document yourself and ' ++ 'pass it back as registration_uri.',+ inputSchema: {+ name: z.string().min(1).max(60).describe('Agent name.'),+ description: z.string().max(2000).optional().describe('Agent description.'),+ image: z.string().url().optional().describe('Thumbnail image URL.'),+ model_url: z.string().url().optional().describe('3D model URL (GLB), written as model.uri.'),+ services: z.array(z.object({ name: z.string().min(1).max(64), endpoint: z.string().url() })).max(16).optional()+ .describe('Services the agent offers.'),+ x402_support: z.boolean().optional().describe('Advertise x402 payment support. Default false.'),+ active: z.boolean().optional().describe('Registration active flag. Default true.'),+ supported_trust: z.array(z.string().min(1).max(64)).max(8).optional().describe("Default ['reputation']."),+ registrations: z.array(z.object({+ agent_id: z.string().min(1).max(128),+ agent_registry: z.string().min(1).max(256),+ })).max(8).optional().describe('External registry entries.'),+ threews_agent_id: z.string().uuid().optional().describe('three.ws agent UUID for the Genesis-exact three.ws entry.'),+ asset: z.string().min(32).max(44).optional().describe('Asset address for the default chain-registry entry when no registrations are given.'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Network for the default chain-registry entry. Defaults to the configured network.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const registrations = args.registrations?.length+ ? args.registrations.map((r) => ({ agentId: r.agent_id, agentRegistry: r.agent_registry }))+ : args.threews_agent_id+ ? [threeWsRegistration(args.threews_agent_id)]+ : args.asset+ ? [chainRegistration(args.asset, network)]+ : [];+ const registration = buildRegistrationDoc({+ name: args.name,+ description: args.description || '',+ image: args.image,+ modelUrl: args.model_url,+ services: args.services,+ active: args.active,+ x402Support: args.x402_support,+ registrations,+ supportedTrust: args.supported_trust,+ });+ const uri = jsonDataUri(registration);+ return {+ ok: true,+ registration,+ registration_uri: uri,+ registration_uri_bytes: uri.length,+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/get-onchain-agent.js b/packages/metaplex-agent-mcp/src/tools/get-onchain-agent.jsnew file mode 100644index 000000000..9a3870796--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/get-onchain-agent.js@@ -0,0 +1,80 @@+// `get_onchain_agent` reads everything about a registered agent from chain:+// the Core asset, its plugins, the decoded metadata and EIP-8004 registration+// documents, the identity PDA, and the asset's built-in wallet with balance.+// Works on ANY Metaplex Agent Registry asset, not just three.ws mints.++import { z } from 'zod';++import { NETWORK, HTTP_TIMEOUT_MS } from '../config.js';+import { fetchAsset } from '@metaplex-foundation/mpl-core';+import { publicKey as umiPublicKey } from '@metaplex-foundation/umi';+import { findAgentIdentityV1Pda } from '@metaplex-foundation/mpl-agent-registry';++import { decodeJsonUri } from '../lib/registration.js';+import { buildUmi, solBalance, assetSignerAddress, agentLinks } from '../lib/solana.js';++export const def = {+ name: 'get_onchain_agent',+ title: 'Read an on-chain agent (asset, registration, wallet)',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ "Fetch a Metaplex Agent Registry agent by its Core asset address: name, owner, update authority, plugins " ++ '(royalties, verified creators, immutable metadata, attributes), the decoded asset metadata and EIP-8004 ' ++ 'registration documents, whether the identity PDA exists, and the built-in agent wallet (Asset Signer PDA) ' ++ 'with its live SOL balance. Read-only. Works on any registered agent, e.g. the three.ws Genesis mints.',+ inputSchema: {+ asset: z.string().min(32).max(44).describe('The Core asset address (base58).'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Cluster. Defaults to the configured network.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const umi = buildUmi({ network });+ const assetPk = umiPublicKey(args.asset);++ const asset = await fetchAsset(umi, assetPk);++ const [identityPda] = findAgentIdentityV1Pda(umi, { asset: assetPk });+ const identityAccount = await umi.rpc.getAccount(identityPda).catch(() => null);+ const registered = Boolean(identityAccount?.exists && identityAccount.data?.length);++ const registrationUri = asset.agentIdentities?.[0]?.uri || null;+ const [metadata, registration] = await Promise.all([+ decodeJsonUri(asset.uri, { timeoutMs: HTTP_TIMEOUT_MS }),+ registrationUri ? decodeJsonUri(registrationUri, { timeoutMs: HTTP_TIMEOUT_MS }) : null,+ ]);++ const agentWallet = assetSignerAddress(umi, args.asset);+ const agentWalletSol = await solBalance(umi, agentWallet).catch(() => null);++ return {+ ok: true,+ network,+ asset: args.asset,+ name: asset.name,+ owner: asset.owner.toString(),+ update_authority: { type: asset.updateAuthority.type, address: asset.updateAuthority.address?.toString() ?? null },+ registered,+ identity_pda: identityPda.toString(),+ metadata_uri: asset.uri,+ metadata,+ registration_uri: registrationUri,+ registration,+ agent_wallet: agentWallet,+ agent_wallet_sol: agentWalletSol,+ plugins: {+ royalties: asset.royalties+ ? {+ basis_points: asset.royalties.basisPoints,+ creators: asset.royalties.creators.map((c) => ({ address: c.address.toString(), percentage: c.percentage })),+ }+ : null,+ verified_creators: asset.verifiedCreators+ ? asset.verifiedCreators.signatures.map((s) => ({ address: s.address.toString(), verified: s.verified }))+ : null,+ immutable_metadata: Boolean(asset.immutableMetadata),+ attributes: asset.attributes ? asset.attributes.attributeList.map((a) => ({ key: a.key, value: a.value })) : null,+ },+ links: agentLinks(args.asset, network),+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/list-onchain-agents.js b/packages/metaplex-agent-mcp/src/tools/list-onchain-agents.jsnew file mode 100644index 000000000..cb80247a8--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/list-onchain-agents.js@@ -0,0 +1,80 @@+// `list_onchain_agents` is the live registration feed. Agents landing in the+// Metaplex Agent Registry (and, cross-chain, ERC-8004 registries), served by+// the public three.ws /api/deployments feed. Real registrations only.++import { z } from 'zod';++import { NETWORK, THREE_WS_BASE, HTTP_TIMEOUT_MS, USER_AGENT } from '../config.js';+import { agentLinks } from '../lib/solana.js';++// The feed treats Solana as a chain id: mainnet-beta 101, devnet 103.+const SOLANA_CHAIN_ID = { mainnet: 101, devnet: 103 };++export const def = {+ name: 'list_onchain_agents',+ title: 'List the latest on-chain agent registrations',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'The latest agents to land on-chain in the Metaplex Agent Registry, newest first, from the live three.ws ' ++ '/api/deployments feed (which also indexes registrations minted outside three.ws). Each entry carries the ' ++ 'Core asset address, name, description, image, owner, 3D and x402 flags, and explorer links. Set ' ++ "all_chains:true to include EVM ERC-8004 registrations in the same stream. Read-only.",+ inputSchema: {+ limit: z.number().int().min(1).max(60).optional().describe('How many registrations to return. Default 12.'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Solana cluster. Defaults to the configured network.'),+ all_chains: z.boolean().optional().describe('Include EVM ERC-8004 registrations too. Default false (Solana only).'),+ cursor: z.string().optional().describe('Pagination cursor from a previous call.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const limit = args.limit || 12;+ const params = new URLSearchParams({ limit: String(limit) });+ params.set('network', network === 'devnet' ? 'testnet' : 'mainnet');+ if (!args.all_chains) params.set('chain', String(SOLANA_CHAIN_ID[network]));+ if (args.cursor) params.set('cursor', args.cursor);++ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), HTTP_TIMEOUT_MS);+ let body;+ try {+ const res = await fetch(`${THREE_WS_BASE}/api/deployments?${params}`, {+ signal: ctrl.signal,+ headers: { accept: 'application/json', 'user-agent': USER_AGENT },+ });+ if (!res.ok) {+ throw Object.assign(new Error(`deployments feed returned ${res.status}`), {+ code: 'feed_error',+ status: res.status,+ });+ }+ body = await res.json();+ } finally {+ clearTimeout(timer);+ }++ const items = (body?.data?.deployments || []).map((d) => ({+ chain: d.chain,+ chain_id: d.chain_id,+ asset: d.agent_id,+ name: d.name,+ description: d.description,+ image: d.image,+ owner: d.owner,+ has_3d: d.has_3d,+ x402_support: d.x402_support,+ registered_at: d.registered_at,+ ...(d.family === 'solana'+ ? { links: agentLinks(d.agent_id, d.testnet ? 'devnet' : 'mainnet') }+ : { explorer: d.agent_explorer }),+ }));++ return {+ ok: true,+ network,+ count: items.length,+ agents: items,+ ...(body?.data?.next_cursor ? { next_cursor: body.data.next_cursor } : {}),+ feed: `${THREE_WS_BASE}/deployments`,+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.js b/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.jsnew file mode 100644index 000000000..83f51ebeb--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/mint-onchain-agent.js@@ -0,0 +1,90 @@+// `mint_onchain_agent` is the self-custody path. Mint + register in ONE atomic+// transaction, signed by the agent's own keypair (SOLANA_SECRET_KEY or a+// per-call `secret`). Called without confirm:true it returns a full preview+// (documents, wallet, cost) and spends nothing.++import { z } from 'zod';++import { NETWORK, REQUIRE_CONFIRM } from '../config.js';+import { buildAgentMint } from '../lib/mint.js';+import {+ buildUmi,+ solBalance,+ assetSignerAddress,+ agentLinks,+ txLink,+ toBase58Signature,+ EST_MINT_LAMPORTS,+ EST_REGISTER_LAMPORTS,+ LAMPORTS_PER_SOL,+} from '../lib/solana.js';+import { mintShape, mintParams } from './mint-shape.js';++const EST_TOTAL_SOL = (EST_MINT_LAMPORTS + EST_REGISTER_LAMPORTS) / LAMPORTS_PER_SOL;++export const def = {+ name: 'mint_onchain_agent',+ title: 'Mint an on-chain agent into the Metaplex Agent Registry',+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Deploy an AI agent on-chain, Genesis-333 style: one atomic Solana transaction mints a Metaplex Core asset ' ++ '(data: URI metadata, verified creator, royalties, immutable metadata) AND registers its EIP-8004 Agent ' ++ 'Identity, so it appears on metaplex.com/agents with its own built-in wallet. Signs with the configured ' ++ 'SOLANA_SECRET_KEY (or a per-call secret) and spends ~0.007 SOL in rent + fees. Without confirm:true it ' ++ 'returns a full preview (both JSON documents, the paying wallet, the cost) and broadcasts NOTHING. ' ++ 'For Phantom/Solflare users, use prepare_agent_mint instead.',+ inputSchema: {+ ...mintShape,+ secret: z.string().optional().describe('Per-call signing key (base58 secret key or JSON byte array). Overrides SOLANA_SECRET_KEY.'),+ confirm: z.boolean().optional().describe('Must be true to broadcast. Anything else returns a spend-nothing preview.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const umi = buildUmi({ network, secret: args.secret, requireSigner: true });+ const wallet = umi.identity.publicKey.toString();++ const mint = buildAgentMint(umi, mintParams(args, { network, creator: wallet }));+ const asset = mint.assetSigner.publicKey.toString();++ if (REQUIRE_CONFIRM && args.confirm !== true) {+ return {+ ok: true,+ confirm_required: true,+ message: `Preview only. Re-issue with confirm:true to mint on ${network} for ~${EST_TOTAL_SOL} SOL.`,+ network,+ paying_wallet: wallet,+ estimated_cost_sol: EST_TOTAL_SOL,+ asset_metadata: mint.assetMetadata,+ metadata_uri_bytes: mint.metadataUri.length,+ registration: mint.registration,+ };+ }++ const balance = await solBalance(umi, wallet);+ if (balance * LAMPORTS_PER_SOL < EST_MINT_LAMPORTS + EST_REGISTER_LAMPORTS) {+ throw Object.assign(+ new Error(+ `Wallet ${wallet} holds ${balance} SOL on ${network}; the mint needs ~${EST_TOTAL_SOL} SOL. Fund it and retry.`,+ ),+ { code: 'insufficient_sol' },+ );+ }++ const result = await mint.builder.sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ const signature = toBase58Signature(result.signature);++ return {+ ok: true,+ network,+ asset,+ signature,+ tx: txLink(signature, network),+ owner: args.owner || wallet,+ agent_wallet: assetSignerAddress(umi, asset),+ metadata_uri: mint.metadataUri,+ registration: mint.registration,+ links: agentLinks(asset, network),+ note: 'The agent is live in the Metaplex Agent Registry. DAS indexers surface it within minutes; fund agent_wallet to let the asset act on-chain.',+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/mint-shape.js b/packages/metaplex-agent-mcp/src/tools/mint-shape.jsnew file mode 100644index 000000000..a50792d4b--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/mint-shape.js@@ -0,0 +1,78 @@+// The full customization surface shared by `mint_onchain_agent` (keypair+// signing) and `prepare_agent_mint` (Phantom/Solflare signing). One place, so+// both flows accept exactly the same fields and produce exactly the same asset.++import { z } from 'zod';++const pubkey = z.string().min(32).max(44);++export const mintShape = {+ name: z.string().min(1).max(60).describe('Agent name. Becomes the Core asset name and the registration name.'),+ description: z.string().max(2000).optional().describe('What this agent is or does. Stored in the EIP-8004 registration document.'),+ image: z.string().url().optional().describe('Thumbnail/avatar image URL (PNG or similar). Shown on metaplex.com/agents, wallets, and explorers.'),+ model_url: z.string().url().optional().describe('3D model URL (GLB). Written as the asset metadata animation_url and as model.uri in the registration, Genesis style.'),+ external_url: z.string().url().optional().describe('Optional external_url in the asset metadata (e.g. the agent home page).'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Solana cluster. Defaults to the configured network (mainnet unless overridden).'),+ owner: pubkey.optional().describe('Mint the asset to this owner instead of the signing wallet.'),+ collection: pubkey.optional().describe('Mint into this Metaplex Core collection. The signer must be the collection authority.'),+ royalty_basis_points: z.number().int().min(0).max(10000).optional().describe('Royalty in basis points. Default 500 (5%), the Genesis value. 0 removes the Royalties plugin.'),+ royalty_creators: z.array(z.object({+ address: pubkey,+ percentage: z.number().int().min(0).max(100),+ })).max(8).optional().describe('Royalty split. Percentages must sum to 100. Defaults to the signing wallet at 100%.'),+ verified_creator: z.boolean().optional().describe('Attach the VerifiedCreators plugin with the signing wallet verified. Default true (Genesis style).'),+ immutable_metadata: z.boolean().optional().describe('Attach the ImmutableMetadata plugin so the metadata can never change. Default true (Genesis style).'),+ attributes: z.array(z.object({ key: z.string().min(1).max(64), value: z.string().max(256) })).max(24).optional().describe('On-chain Attributes plugin entries (real bytes in the asset account).'),+ metadata_attributes: z.array(z.object({ key: z.string().min(1).max(64), value: z.string().max(256) })).max(48).optional().describe('Off-chain attributes array inside the asset metadata JSON (trait_type/value pairs).'),+ permanent_freeze: z.boolean().optional().describe('Attach PermanentFreezeDelegate (unfrozen). Default false.'),+ permanent_transfer: z.boolean().optional().describe('Attach PermanentTransferDelegate. Default false.'),+ permanent_burn: z.boolean().optional().describe('Attach PermanentBurnDelegate. Default false.'),+ add_blocker: z.boolean().optional().describe('Attach AddBlocker so no further plugins can be added. Default false.'),+ services: z.array(z.object({+ name: z.string().min(1).max(64),+ endpoint: z.string().url(),+ })).max(16).optional().describe('Services the agent offers, listed on its Metaplex agent page ({name, endpoint}).'),+ x402_support: z.boolean().optional().describe('Advertise x402 payment support in the registration document. Default false.'),+ active: z.boolean().optional().describe('Registration active flag. Default true.'),+ supported_trust: z.array(z.string().min(1).max(64)).max(8).optional().describe("Trust models the agent supports. Default ['reputation'] (Genesis style)."),+ registrations: z.array(z.object({+ agent_id: z.string().min(1).max(128),+ agent_registry: z.string().min(1).max(256),+ })).max(8).optional().describe('External registry registrations. Defaults to the chain registry entry, or the three.ws entry when threews_agent_id is set.'),+ threews_agent_id: z.string().uuid().optional().describe('three.ws agent UUID. Adds the Genesis-exact registration entry {agentId, agentRegistry: "https://three.ws"}.'),+ metadata_uri: z.string().optional().describe('Full override for the asset metadata URI (https or data:). Skips the built-in metadata builder.'),+ registration_uri: z.string().optional().describe('Full override for the Agent Identity registration URI (https or data:). Skips the built-in registration builder.'),+};++/** Map snake_case tool args onto buildAgentMint camelCase params. */+export function mintParams(args, { network, creator }) {+ return {+ network,+ creator,+ owner: args.owner,+ collection: args.collection,+ name: args.name,+ description: args.description || '',+ image: args.image,+ modelUrl: args.model_url,+ externalUrl: args.external_url,+ metadataAttributes: args.metadata_attributes?.map((a) => ({ key: a.key, value: a.value })),+ metadataUri: args.metadata_uri,+ services: args.services,+ active: args.active,+ x402Support: args.x402_support,+ registrations: args.registrations?.map((r) => ({ agentId: r.agent_id, agentRegistry: r.agent_registry })),+ threeWsAgentId: args.threews_agent_id,+ supportedTrust: args.supported_trust,+ registrationUri: args.registration_uri,+ royaltyBasisPoints: args.royalty_basis_points,+ royaltyCreators: args.royalty_creators,+ verifiedCreator: args.verified_creator,+ immutableMetadata: args.immutable_metadata,+ attributes: args.attributes,+ permanentFreeze: args.permanent_freeze,+ permanentTransfer: args.permanent_transfer,+ permanentBurn: args.permanent_burn,+ addBlocker: args.add_blocker,+ };+}diff --git a/packages/metaplex-agent-mcp/src/tools/prepare-agent-mint.js b/packages/metaplex-agent-mcp/src/tools/prepare-agent-mint.jsnew file mode 100644index 000000000..615c348a3--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/prepare-agent-mint.js@@ -0,0 +1,62 @@+// `prepare_agent_mint` is the wallet path. It builds the SAME atomic mint+register+// transaction for a Phantom / Solflare / any-Solana-wallet owner. No key is+// needed here: the transaction comes back base64, partially signed by the new+// asset keypair, with the owner's wallet as fee payer. The owner signs and+// broadcasts it (or hands the signed bytes to send_signed_transaction).++import { z } from 'zod';++import { NETWORK } from '../config.js';+import { buildAgentMint } from '../lib/mint.js';+import {+ buildUmi,+ assetSignerAddress,+ agentLinks,+ EST_MINT_LAMPORTS,+ EST_REGISTER_LAMPORTS,+ LAMPORTS_PER_SOL,+} from '../lib/solana.js';+import { mintShape, mintParams } from './mint-shape.js';+import { createNoopSigner, publicKey as umiPublicKey, signerIdentity } from '@metaplex-foundation/umi';++export const def = {+ name: 'prepare_agent_mint',+ title: 'Prepare an agent mint for a Phantom/Solflare wallet to sign',+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Build the exact Genesis-style mint+register transaction (Metaplex Core asset + Agent Identity, one atomic ' ++ 'tx) for an EXTERNAL Solana wallet: Phantom, Solflare, Backpack, Ledger, anything. Needs no secret key. ' ++ 'Returns the unsigned transaction base64 (already co-signed by the new asset keypair) with `wallet` as the ' ++ 'fee payer; the wallet signs it and broadcasts, or passes the signed bytes to send_signed_transaction. ' ++ 'Broadcasts nothing itself. The blockhash expires after roughly a minute, so sign promptly and re-prepare ' ++ 'if a wallet reports an expired transaction.',+ inputSchema: {+ ...mintShape,+ wallet: z.string().min(32).max(44).describe('The base58 address of the wallet that will sign, pay, and own the agent.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const umi = buildUmi({ network });+ umi.use(signerIdentity(createNoopSigner(umiPublicKey(args.wallet))));++ const mint = buildAgentMint(umi, mintParams(args, { network, creator: args.wallet }));+ const asset = mint.assetSigner.publicKey.toString();++ const tx = await mint.builder.buildAndSign(umi);+ const txBase64 = Buffer.from(umi.transactions.serialize(tx)).toString('base64');++ return {+ ok: true,+ network,+ wallet: args.wallet,+ asset,+ agent_wallet: assetSignerAddress(umi, asset),+ tx_base64: txBase64,+ estimated_cost_sol: (EST_MINT_LAMPORTS + EST_REGISTER_LAMPORTS) / LAMPORTS_PER_SOL,+ asset_metadata: mint.assetMetadata,+ registration: mint.registration,+ links: agentLinks(asset, network),+ next: 'Have the wallet sign tx_base64 (signTransaction on a VersionedTransaction/legacy tx from these bytes) and broadcast it, or call send_signed_transaction with the signed base64.',+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/register-agent-identity.js b/packages/metaplex-agent-mcp/src/tools/register-agent-identity.jsnew file mode 100644index 000000000..e7c8aa848--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/register-agent-identity.js@@ -0,0 +1,129 @@+// `register_agent_identity`: enrol an EXISTING Metaplex Core asset in the+// Agent Registry. This is the back-fill path: the asset was minted earlier+// (any Core mint qualifies) and only the Agent Identity is missing. The signer+// must hold the asset's update authority (for collection-bound assets, the+// collection authority).++import { z } from 'zod';++import { NETWORK, REQUIRE_CONFIRM } from '../config.js';+import { publicKey as umiPublicKey } from '@metaplex-foundation/umi';+import { registerIdentityV1, findAgentIdentityV1Pda } from '@metaplex-foundation/mpl-agent-registry';++import {+ buildRegistrationDoc,+ chainRegistration,+ threeWsRegistration,+ jsonDataUri,+} from '../lib/registration.js';+import {+ buildUmi,+ agentLinks,+ txLink,+ toBase58Signature,+ EST_REGISTER_LAMPORTS,+ LAMPORTS_PER_SOL,+} from '../lib/solana.js';++export const def = {+ name: 'register_agent_identity',+ title: 'Register an existing Core asset in the Metaplex Agent Registry',+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },+ description:+ 'Give an ALREADY-MINTED Metaplex Core asset its Agent Identity: writes the EIP-8004 registration document ' ++ '(as a self-contained data: URI) onto the asset and creates its identity PDA, after which it appears on ' ++ 'metaplex.com/agents. The signing wallet must be the asset authority (or the collection authority for ' ++ 'collection-bound assets). Registration is one-time per asset and costs ~0.003 SOL; an already-registered ' ++ 'asset returns already_registered without spending. Without confirm:true it returns a spend-nothing preview. ' ++ 'To mint a NEW agent, use mint_onchain_agent or prepare_agent_mint instead.',+ inputSchema: {+ asset: z.string().min(32).max(44).describe('The Core asset address to register.'),+ collection: z.string().min(32).max(44).optional().describe('The collection address, required for collection-bound assets.'),+ name: z.string().min(1).max(60).describe('Agent name for the registration document.'),+ description: z.string().max(2000).optional().describe('Agent description.'),+ image: z.string().url().optional().describe('Thumbnail image URL.'),+ model_url: z.string().url().optional().describe('3D model URL (GLB), written as model.uri.'),+ services: z.array(z.object({ name: z.string().min(1).max(64), endpoint: z.string().url() })).max(16).optional()+ .describe('Services the agent offers.'),+ x402_support: z.boolean().optional().describe('Advertise x402 payment support. Default false.'),+ active: z.boolean().optional().describe('Registration active flag. Default true.'),+ supported_trust: z.array(z.string().min(1).max(64)).max(8).optional().describe("Default ['reputation']."),+ registrations: z.array(z.object({+ agent_id: z.string().min(1).max(128),+ agent_registry: z.string().min(1).max(256),+ })).max(8).optional().describe('External registry entries. Defaults to the chain registry entry.'),+ threews_agent_id: z.string().uuid().optional().describe('three.ws agent UUID for the Genesis-exact three.ws registration entry.'),+ registration_uri: z.string().optional().describe('Full override for the registration URI (https or data:).'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Cluster. Defaults to the configured network.'),+ secret: z.string().optional().describe('Per-call signing key. Overrides SOLANA_SECRET_KEY.'),+ confirm: z.boolean().optional().describe('Must be true to broadcast. Anything else returns a preview.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const umi = buildUmi({ network, secret: args.secret, requireSigner: true });+ const assetPk = umiPublicKey(args.asset);+ const [identityPda] = findAgentIdentityV1Pda(umi, { asset: assetPk });++ const existing = await umi.rpc.getAccount(identityPda).catch(() => null);+ if (existing?.exists && existing.data?.length) {+ return {+ ok: true,+ already_registered: true,+ asset: args.asset,+ identity_pda: identityPda.toString(),+ links: agentLinks(args.asset, network),+ };+ }++ const registrations = args.registrations?.length+ ? args.registrations.map((r) => ({ agentId: r.agent_id, agentRegistry: r.agent_registry }))+ : args.threews_agent_id+ ? [threeWsRegistration(args.threews_agent_id)]+ : [chainRegistration(args.asset, network)];+ const registration = args.registration_uri+ ? null+ : buildRegistrationDoc({+ name: args.name,+ description: args.description || '',+ image: args.image,+ modelUrl: args.model_url,+ services: args.services,+ active: args.active,+ x402Support: args.x402_support,+ registrations,+ supportedTrust: args.supported_trust,+ });+ const agentRegistrationUri = args.registration_uri || jsonDataUri(registration);++ if (REQUIRE_CONFIRM && args.confirm !== true) {+ return {+ ok: true,+ confirm_required: true,+ message: `Preview only. Re-issue with confirm:true to register on ${network} for ~${EST_REGISTER_LAMPORTS / LAMPORTS_PER_SOL} SOL.`,+ network,+ asset: args.asset,+ identity_pda: identityPda.toString(),+ paying_wallet: umi.identity.publicKey.toString(),+ registration,+ };+ }++ const registerArgs = { asset: assetPk, agentRegistrationUri };+ if (args.collection) registerArgs.collection = umiPublicKey(args.collection);+ const result = await registerIdentityV1(umi, registerArgs).sendAndConfirm(umi, {+ confirm: { commitment: 'confirmed' },+ });+ const signature = toBase58Signature(result.signature);++ return {+ ok: true,+ network,+ asset: args.asset,+ identity_pda: identityPda.toString(),+ signature,+ tx: txLink(signature, network),+ registration,+ links: agentLinks(args.asset, network),+ };+ },+};diff --git a/packages/metaplex-agent-mcp/src/tools/send-signed-transaction.js b/packages/metaplex-agent-mcp/src/tools/send-signed-transaction.jsnew file mode 100644index 000000000..e32a55293--- /dev/null+++ b/packages/metaplex-agent-mcp/src/tools/send-signed-transaction.js@@ -0,0 +1,68 @@+// `send_signed_transaction`: broadcast a fully signed transaction (usually+// the output of prepare_agent_mint after the owner's wallet signed it) and+// wait for confirmation.++import { z } from 'zod';++import { NETWORK } from '../config.js';+import { buildUmi, toBase58Signature, txLink } from '../lib/solana.js';++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++export const def = {+ name: 'send_signed_transaction',+ title: 'Broadcast a signed Solana transaction and confirm it',+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },+ description:+ 'Broadcast a fully signed Solana transaction (base64) and poll until it confirms. Use it to complete the ' ++ 'prepare_agent_mint flow when the signing wallet does not broadcast on its own. Whatever the transaction ' ++ 'does on-chain happens for real, so only send bytes you built and inspected.',+ inputSchema: {+ tx_base64: z.string().min(64).describe('The fully signed transaction, base64 encoded.'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Cluster to broadcast on. Defaults to the configured network.'),+ },+ async handler(args) {+ const network = args.network || NETWORK;+ const umi = buildUmi({ network });++ let tx;+ try {+ tx = umi.transactions.deserialize(new Uint8Array(Buffer.from(args.tx_base64, 'base64')));+ } catch {+ throw Object.assign(new Error('tx_base64 does not deserialize as a Solana transaction'), {+ code: 'bad_transaction',+ });+ }++ const rawSignature = await umi.rpc.sendTransaction(tx, { commitment: 'confirmed' });+ const signature = toBase58Signature(rawSignature);++ // Bounded confirmation poll: ~60s at 2s intervals.+ let status = null;+ for (let i = 0; i < 30; i++) {+ const [s] = await umi.rpc.getSignatureStatuses([rawSignature]);+ if (s?.error) {+ throw Object.assign(new Error(`transaction ${signature} failed on-chain: ${JSON.stringify(s.error)}`), {+ code: 'tx_failed',+ });+ }+ if (s && (s.commitment === 'confirmed' || s.commitment === 'finalized')) {+ status = s.commitment;+ break;+ }+ await sleep(2000);+ }++ return {+ ok: true,+ network,+ signature,+ confirmed: status !== null,+ commitment: status,+ tx: txLink(signature, network),+ ...(status === null+ ? { note: 'Broadcast succeeded but confirmation was not observed within 60s. Check the tx link before retrying; re-sending a landed transaction is harmless (same signature).' }+ : {}),+ };+ },+};diff --git a/packages/metaplex-agent-mcp/test/genesis-shape.test.mjs b/packages/metaplex-agent-mcp/test/genesis-shape.test.mjsnew file mode 100644index 000000000..882cc876e--- /dev/null+++ b/packages/metaplex-agent-mcp/test/genesis-shape.test.mjs@@ -0,0 +1,120 @@+// Byte-exact Genesis-333 reproduction.+//+// The fixtures below are the LIVE on-chain URIs of three.ws Genesis #332+// ("mao", Core asset 9Mx9XgSHRJrgqS77t8hTtDPYtX995M87Wi7TRKgkQ3Vy), read from+// mainnet. The builders must reproduce them byte for byte from their decoded+// fields; if a refactor reorders a key or changes serialization, these tests+// fail before a mint ever ships a drifted shape. Offline: no RPC, no fetch.+//+// Run: node --test packages/metaplex-agent-mcp/test/genesis-shape.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import {+ buildAssetMetadata,+ buildRegistrationDoc,+ threeWsRegistration,+ chainRegistration,+ jsonDataUri,+ decodeJsonUri,+ EIP_8004_REGISTRATION_TYPE,+} from '../src/lib/registration.js';+import { buildPlugins } from '../src/lib/mint.js';++// Asset metadata URI of Genesis #332, verbatim from the asset account.+const MAO_METADATA_URI =+ 'data:application/json;base64,eyJuYW1lIjoibWFvIiwiaW1hZ2UiOiJodHRwczovL3B1Yi0yNTM0ZTkyMWJmOWM0MzE0YWRkY2Q0ZDhhNmU5OGI3Yi5yMi5kZXYvdGh1bWIvN2I5MWIwNmUtNDE5My00NjEwLTg5MmUtNmRmZTM0OTM5ZWI2LnBuZyIsImFuaW1hdGlvbl91cmwiOiJodHRwczovL3B1Yi0yNTM0ZTkyMWJmOWM0MzE0YWRkY2Q0ZDhhNmU5OGI3Yi5yMi5kZXYvdS82YTQ1ZmMwNi0wNWEyLTQxNmQtYjA5Yy1jZGU5ZTg1NTNjOWQvZHJhZnQtd3N6cjNuL21wa3A4MWNzLmdsYiJ9';++// Agent Identity registration URI of Genesis #332, verbatim from the+// AgentIdentity plugin on the asset.+const MAO_REGISTRATION_URI =+ 'data:application/json;base64,eyJ0eXBlIjoiaHR0cHM6Ly9laXBzLmV0aGVyZXVtLm9yZy9FSVBTL2VpcC04MDA0I3JlZ2lzdHJhdGlvbi12MSIsIm5hbWUiOiJtYW8iLCJkZXNjcmlwdGlvbiI6InRocmVlLndzIEdlbmVzaXMgIzMzMiIsImltYWdlIjoiaHR0cHM6Ly9wdWItMjUzNGU5MjFiZjljNDMxNGFkZGNkNGQ4YTZlOThiN2IucjIuZGV2L3RodW1iLzdiOTFiMDZlLTQxOTMtNDYxMC04OTJlLTZkZmUzNDkzOWViNi5wbmciLCJtb2RlbCI6eyJ1cmkiOiJodHRwczovL3B1Yi0yNTM0ZTkyMWJmOWM0MzE0YWRkY2Q0ZDhhNmU5OGI3Yi5yMi5kZXYvdS82YTQ1ZmMwNi0wNWEyLTQxNmQtYjA5Yy1jZGU5ZTg1NTNjOWQvZHJhZnQtd3N6cjNuL21wa3A4MWNzLmdsYiJ9LCJhY3RpdmUiOnRydWUsIng0MDJTdXBwb3J0Ijp0cnVlLCJyZWdpc3RyYXRpb25zIjpbeyJhZ2VudElkIjoiN2I5MWIwNmUtNDE5My00NjEwLTg5MmUtNmRmZTM0OTM5ZWI2IiwiYWdlbnRSZWdpc3RyeSI6Imh0dHBzOi8vdGhyZWUud3MifV0sInN1cHBvcnRlZFRydXN0IjpbInJlcHV0YXRpb24iXX0=';++test('asset metadata rebuilds Genesis #332 byte for byte', async () => {+ const decoded = await decodeJsonUri(MAO_METADATA_URI);+ assert.ok(decoded, 'fixture must decode');+ const rebuilt = buildAssetMetadata({+ name: decoded.name,+ image: decoded.image,+ animationUrl: decoded.animation_url,+ });+ assert.equal(jsonDataUri(rebuilt), MAO_METADATA_URI);+});++test('registration document rebuilds Genesis #332 byte for byte', async () => {+ const decoded = await decodeJsonUri(MAO_REGISTRATION_URI);+ assert.ok(decoded, 'fixture must decode');+ assert.equal(decoded.type, EIP_8004_REGISTRATION_TYPE);+ const rebuilt = buildRegistrationDoc({+ name: decoded.name,+ description: decoded.description,+ image: decoded.image,+ modelUrl: decoded.model.uri,+ active: decoded.active,+ x402Support: decoded.x402Support,+ registrations: [threeWsRegistration(decoded.registrations[0].agentId)],+ supportedTrust: decoded.supportedTrust,+ });+ assert.equal(jsonDataUri(rebuilt), MAO_REGISTRATION_URI);+});++test('default registration entry points at the chain registry', () => {+ assert.deepEqual(chainRegistration('SoMeAsset', 'mainnet'), {+ agentId: 'SoMeAsset',+ agentRegistry: 'solana:101:metaplex',+ });+ assert.deepEqual(chainRegistration('SoMeAsset', 'devnet'), {+ agentId: 'SoMeAsset',+ agentRegistry: 'solana:103:metaplex',+ });+});++test('default plugins are the Genesis set: royalties, verified creator, immutable metadata', () => {+ const creator = 'WWW3eeR7LjgCNSCnC4qmSfLfQZgxHF9ZvqhD8NbKrPV';+ const plugins = buildPlugins({ creator });+ assert.deepEqual(plugins.map((p) => p.type), ['Royalties', 'VerifiedCreators', 'ImmutableMetadata']);+ const royalties = plugins[0];+ assert.equal(royalties.basisPoints, 500);+ assert.equal(royalties.creators.length, 1);+ assert.equal(royalties.creators[0].address.toString(), creator);+ assert.equal(royalties.creators[0].percentage, 100);+ const verified = plugins[1];+ assert.equal(verified.signatures[0].address.toString(), creator);+ assert.equal(verified.signatures[0].verified, true);+});++test('plugin knobs work: zero royalty, attributes, permanent delegates, add blocker', () => {+ const creator = 'WWW3eeR7LjgCNSCnC4qmSfLfQZgxHF9ZvqhD8NbKrPV';+ const plugins = buildPlugins({+ creator,+ royaltyBasisPoints: 0,+ verifiedCreator: false,+ immutableMetadata: false,+ attributes: [{ key: 'platform', value: 'three.ws' }],+ permanentFreeze: true,+ permanentTransfer: true,+ permanentBurn: true,+ addBlocker: true,+ });+ assert.deepEqual(+ plugins.map((p) => p.type),+ ['Attributes', 'PermanentFreezeDelegate', 'PermanentTransferDelegate', 'PermanentBurnDelegate', 'AddBlocker'],+ );+ assert.deepEqual(plugins[0].attributeList, [{ key: 'platform', value: 'three.ws' }]);+});++test('royalty splits must sum to 100', () => {+ const creator = 'WWW3eeR7LjgCNSCnC4qmSfLfQZgxHF9ZvqhD8NbKrPV';+ assert.throws(+ () => buildPlugins({ creator, royaltyCreators: [{ address: creator, percentage: 60 }] }),+ /sum to 100/,+ );+});++test('decodeJsonUri handles data: URIs offline and rejects junk', async () => {+ assert.deepEqual(await decodeJsonUri(jsonDataUri({ a: 1 })), { a: 1 });+ assert.equal(await decodeJsonUri('data:application/json;base64'), null);+ assert.equal(await decodeJsonUri('ipfs://nope'), null);+ assert.equal(await decodeJsonUri(''), null);+});diff --git a/packages/metaplex-agent-mcp/test/registration.test.mjs b/packages/metaplex-agent-mcp/test/registration.test.mjsnew file mode 100644index 000000000..8296f9df9--- /dev/null+++ b/packages/metaplex-agent-mcp/test/registration.test.mjs@@ -0,0 +1,78 @@+// Tool-surface invariants for @three-ws/metaplex-agent-mcp.+//+// Importing src/index.js is side-effect-free: the stdio transport only connects+// when the file is the process entry point, and buildServer() needs no signer.+// These tests run offline: they never touch the network or sign anything.+//+// Run: node --test packages/metaplex-agent-mcp/test/registration.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++import { TOOLS, buildServer } from '../src/index.js';++const READ_ONLY_TOOLS = new Set([+ 'prepare_agent_mint',+ 'get_onchain_agent',+ 'agent_wallet',+ 'build_registration',+ 'list_onchain_agents',+]);+const EXECUTION_TOOLS = new Set(['mint_onchain_agent', 'send_signed_transaction', 'register_agent_identity']);++test('exactly the expected tools are registered', () => {+ assert.equal(TOOLS.length, 8);+ assert.deepEqual(new Set(TOOLS.map((t) => t.name)), new Set([...READ_ONLY_TOOLS, ...EXECUTION_TOOLS]));+});++test('every tool has a title, description, input schema and complete annotations', () => {+ for (const tool of TOOLS) {+ assert.equal(typeof tool.title, 'string', `${tool.name} is missing a title`);+ assert.ok(tool.title.length > 0, `${tool.name} has an empty title`);+ assert.equal(typeof tool.description, 'string', `${tool.name} is missing a description`);+ assert.ok(tool.description.length >= 20, `${tool.name} has a thin description`);+ assert.ok(tool.inputSchema && typeof tool.inputSchema === 'object', `${tool.name} is missing inputSchema`);+ assert.equal(typeof tool.handler, 'function', `${tool.name} is missing a handler`);+ assert.ok(tool.annotations, `${tool.name} is missing MCP ToolAnnotations`);+ assert.equal(typeof tool.annotations.readOnlyHint, 'boolean', `${tool.name} must set readOnlyHint`);+ assert.equal(typeof tool.annotations.idempotentHint, 'boolean', `${tool.name} must set idempotentHint`);+ assert.equal(typeof tool.annotations.openWorldHint, 'boolean', `${tool.name} must set openWorldHint`);+ }+});++test('the read tools advertise readOnlyHint', () => {+ for (const name of READ_ONLY_TOOLS) {+ const tool = TOOLS.find((t) => t.name === name);+ assert.ok(tool, `${name} must exist`);+ assert.equal(tool.annotations.readOnlyHint, true, `${name} should be read-only`);+ }+});++test('the execution tools spend SOL and say so', () => {+ const destructive = TOOLS.filter((t) => t.annotations.destructiveHint === true).map((t) => t.name);+ assert.deepEqual(new Set(destructive), EXECUTION_TOOLS);+ for (const name of EXECUTION_TOOLS) {+ const tool = TOOLS.find((t) => t.name === name);+ assert.equal(tool.annotations.readOnlyHint, false, `${name} must not claim read-only`);+ }+});++test('non-read-only tools set destructiveHint explicitly (spec default is TRUE when omitted)', () => {+ for (const tool of TOOLS) {+ if (tool.annotations.readOnlyHint === false) {+ assert.equal(typeof tool.annotations.destructiveHint, 'boolean', `${tool.name} must set destructiveHint`);+ }+ }+});++test('build_registration is the only offline tool', () => {+ for (const tool of TOOLS) {+ const expectOpenWorld = tool.name !== 'build_registration';+ assert.equal(tool.annotations.openWorldHint, expectOpenWorld, `${tool.name} openWorldHint`);+ }+});++test('buildServer registers without env or network', () => {+ const server = buildServer();+ assert.ok(server, 'buildServer must return a server');+});diff --git a/scripts/publish-mcp-servers.mjs b/scripts/publish-mcp-servers.mjsindex d4e2b2201..fa1f73f81 100644--- a/scripts/publish-mcp-servers.mjs+++ b/scripts/publish-mcp-servers.mjs@@ -80,6 +80,11 @@ const SERVERS = [manifest: 'packages/marketplace-mcp/server.json',},{ key: 'x402-mcp', dir: 'packages/x402-mcp', manifest: 'packages/x402-mcp/server.json' },+ {+ key: 'metaplex-agent-mcp',+ dir: 'packages/metaplex-agent-mcp',+ manifest: 'packages/metaplex-agent-mcp/server.json',+ },// Autonomous-agent control plane + account/discovery + capability surfaces// (the 2025-06 buildout). Each is a stdio npm package with its own server.json.{ key: 'autopilot-mcp', dir: 'packages/autopilot-mcp', manifest: 'packages/autopilot-mcp/server.json' },