### Project Setup and Configuration Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Steps to install dependencies, configure environment variables, and fund wallets for agent registration. ```APIDOC ## Project Setup After generating your project: ```bash cd my-agent npm install ``` ### 1. Configure Environment Edit `.env` and fill in: ```env PRIVATE_KEY=... # Auto-generated if you left wallet empty OPENAI_API_KEY=your_openai_key # For LLM responses PINATA_JWT=your_pinata_jwt # If using IPFS storage (requires pinJSONToIPFS scope) ``` **Auto-generated wallet:** If you left the wallet address empty, a new wallet was generated and the private key is already in `.env`. **Back up your .env file** and **fund the wallet with testnet tokens** before registering. - **EVM chains:** Fund with testnet ETH (use faucets for Sepolia, Base Sepolia, etc.) - **Solana Devnet:** Fund with devnet SOL via `solana airdrop` or faucets **Pinata JWT:** Create an API key at [pinata.cloud](https://pinata.cloud) with `pinJSONToIPFS` scope for public IPFS pinning. ``` -------------------------------- ### Install and Run MCP Inspector Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Commands to install the MCP Inspector globally and then test directly with your MCP client by running the start script. ```bash # Install MCP Inspector npx @modelcontextprotocol/inspector # Or test directly with your MCP client npm run start:mcp ``` -------------------------------- ### Starting Servers Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Commands to start the A2A and MCP servers for the agent. ```APIDOC ### 3. Start Your Servers ```bash # Start A2A server npm run start:a2a # Start MCP server (in another terminal) npm run start:mcp ``` ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Install project dependencies after navigating to the generated agent directory. ```bash cd my-agent npm install ``` -------------------------------- ### x402 Payments Setup Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Information on enabling and configuring x402 payments for USDC micropayments. ```APIDOC ## x402 Payments [x402](https://x402.org) payment support enables USDC micropayments for your agent. Available on: | Chain | Facilitator | Status | | ----- | ----------- | ------ | | Base Mainnet | [PayAI](https://facilitator.payai.network) | ✅ Production | | Base Sepolia | PayAI | ✅ Testnet | | Polygon Mainnet | PayAI | ✅ Production | | Polygon Amoy | PayAI | ✅ Testnet | | SKALE Base | PayAI | ✅ Production | | SKALE Base Sepolia | PayAI | ✅ Testnet | When enabled, the A2A server uses x402 middleware for micropayments: - Per-request pricing (default: $0.001 USDC) - Automatic payment verification via facilitator - Payment configuration in `.env`: `X402_PAYEE_ADDRESS`, `X402_PRICE` - 4mica only: `X402_TAB_ENDPOINT` (public tab endpoint advertised to clients) ``` -------------------------------- ### Start A2A Server and Fetch Agent Card (Bash) Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Commands to start the generated A2A server and fetch its agent discovery card using curl. The agent card describes the agent's capabilities and configuration. ```bash # Start the generated server npm run start:a2a # Fetch the agent card curl http://localhost:3000/.well-known/agent-card.json ``` -------------------------------- ### Scaffold an ERC-8004 Agent Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Run this command to start the interactive wizard for creating a new ERC-8004 compliant AI agent. The wizard will guide you through project setup, including optional features like x402 payments. ```bash npx create-8004-agent ``` -------------------------------- ### Start A2A Server Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Start the Agent-to-Agent (A2A) server to handle communication protocols. ```bash # Start A2A server npm run start:a2a ``` -------------------------------- ### Configure Paid Request Tests Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Example of a .env file configuration required for running x402 paid request tests. Ensure the private key is for a wallet funded with testnet USDC. ```env TEST_PAYER_PRIVATE_KEY=0x...your_private_key... ``` -------------------------------- ### Start MCP Server Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Start the Message Communication Protocol (MCP) server in a separate terminal. ```bash # Start MCP server (in another terminal) npm run start:mcp ``` -------------------------------- ### 4mica Setup (Optional Collateral Deposit) Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Details on the optional collateral deposit process for 4mica when setting up x402 payments. ```APIDOC ### 4mica Setup (Optional Collateral Deposit) If you select `x402 payments` and choose `4mica` during the wizard, you will be prompted: `Register with 4mica now (optional collateral deposit)?` If you say **yes**, the CLI will: - Ask for a wallet private key (or use the one it generated). - Ask which asset to deposit (USDC, USDT, or native token) and how much. - Submit an on-chain deposit via the 4mica SDK and print the transaction hash. You can safely skip this step if you are not ready to fund the wallet yet. The agent still generates and runs; you can enable 4Mica later after funding a wallet. ``` -------------------------------- ### Setup x402 Payment Middleware for A2A Server Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Integrates payment middleware into an Express.js server to enforce x402 v2 USDC payments. Requires facilitator client and EVM scheme setup. Returns HTTP 402 if payment is missing. ```typescript import { paymentMiddleware, x402ResourceServer } from '@x402/express'; import { HTTPFacilitatorClient } from '@x402/core/server'; import { ExactEvmScheme } from '@x402/evm/exact/server'; const facilitatorClient = new HTTPFacilitatorClient({ url: 'https://facilitator.payai.network' }); const evmScheme = new ExactEvmScheme(); const x402Server = new x402ResourceServer(facilitatorClient).register('eip155:84532', evmScheme); app.use( paymentMiddleware( { 'POST /a2a': { accepts: [{ scheme: 'exact', price: process.env.X402_PRICE || '$0.001', network: 'eip155:84532', payTo: process.env.X402_PAYEE_ADDRESS }], description: 'My Agent', mimeType: 'application/json', }, }, x402Server, ) ); ``` ```http curl -X POST http://localhost:3000/a2a -d '...' // HTTP/1.1 402 Payment Required // { "accepts": [{ "scheme": "exact", "price": "$0.001", "network": "eip155:84532", "payTo": "0x..." }] } ``` -------------------------------- ### Run create-8004-agent CLI Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Invokes the interactive wizard to generate a new AI agent project. Follow the prompts to configure project details, select features, and choose a blockchain network. The tool will then generate project files, install dependencies, and provide next steps. ```bash # Run the generator interactively npx create-8004-agent # Expected console output: # 🤖 8004 Agent Generator # Create a trustless AI agent with A2A, MCP, and x402 support # # ? Project directory (or . for current): my-agent # ? Agent name: my agent # ... # ✅ ERC-8004 Agent generated successfully! # ✅ Dependencies installed successfully! # # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ # 🚀 NEXT STEPS # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ # 1. Configure .env # 2. Fund your wallet with testnet ETH # 3. Start & deploy your A2A server npm run start:a2a # 4. Register your agent on-chain npm run register ``` -------------------------------- ### Agent Registration File Structure Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Example JSON structure for an agent's registration file, detailing type, name, description, image, endpoints, and supported trust mechanisms. ```json { "type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1", "name": "My Agent", "description": "An AI agent...", "image": "https://example.com/image.png", "endpoints": [ { "name": "A2A", "endpoint": "http://localhost:3000/.well-known/agent-card.json", "version": "0.3.0" }, { "name": "MCP", "endpoint": "http://localhost:3001", "version": "2025-06-18" }, { "name": "agentWallet", "endpoint": "eip155:11155111:0x..." } ], "registrations": [ { "agentId": 123, "agentRegistry": "eip155:11155111:0x8004..." } ], "supportedTrust": ["reputation", "crypto-economic", "tee-attestation"] } ``` -------------------------------- ### Testing A2A Endpoint Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Instructions and examples for testing the A2A server's agent card and JSON-RPC endpoint. ```APIDOC ### Testing Your A2A Endpoint **1. Start the server:** ```bash npm run start:a2a ``` **2. Test the agent card:** ```bash curl http://localhost:3000/.well-known/agent-card.json ``` **3. Test the JSON-RPC endpoint:** ```bash curl -X POST http://localhost:3000/a2a \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "message/send", "params": { "message": { "role": "user", "parts": [{"type": "text", "text": "Hello!"}] } }, "id": 1 }' ``` ``` -------------------------------- ### Generated A2A Client — Programmatic A2A Test Client Source: https://context7.com/eversmile12/create-8004-agent/llms.txt This section provides examples of how to use the TypeScript `A2AClient` class for discovering agent capabilities, sending messages, managing conversations, and handling payment-required errors. ```APIDOC ## A2AClient Class ### Description TypeScript client class for discovering agents, sending messages, streaming responses, and running automated test suites against a live A2A server. ### Methods #### `discover()` - **Description**: Discovers agent capabilities. - **Returns**: A promise that resolves to an object containing agent information, including its name and capabilities. #### `send(message: string)` - **Description**: Sends a single message to the agent and receives a reply. - **Parameters**: - **message** (string) - The message to send to the agent. - **Returns**: A promise that resolves to a task object containing the agent's messages. #### `continue(message: string)` - **Description**: Continues an existing conversation with the agent, maintaining context. - **Parameters**: - **message** (string) - The follow-up message. - **Returns**: A promise that resolves to a task object with messages, preserving the `contextId`. #### `stream(message: string)` - **Description**: Streams the agent's response to a message. Only available if `a2aStreaming` was enabled during client setup. - **Parameters**: - **message** (string) - The message to send for streaming. - **Returns**: An async iterator yielding chunks of the streamed response. #### `newConversation()` - **Description**: Starts a new conversation, clearing the previous context. #### Error Handling - **`PaymentRequiredError`**: This error is thrown when the agent requires payment (HTTP 402). The error object contains `paymentInfo` with details on how to pay. ### Usage Examples 1. **Discover agent capabilities**: ```typescript const card = await client.discover(); console.log(card.name, card.capabilities.streaming); ``` 2. **Single-turn message**: ```typescript const task = await client.send('Hello, what can you do?'); const reply = task.messages.find(m => m.role === 'agent'); console.log(reply?.parts[0].text); ``` 3. **Multi-turn conversation**: ```typescript await client.send("My name is Alice"); const task2 = await client.continue("What's my name?"); // task2.contextId === task.contextId → maintains conversation history ``` 4. **SSE streaming**: ```typescript for await (const chunk of client.stream('Tell me a story')) { process.stdout.write(chunk); } ``` 5. **Handle payment-required (x402)**: ```typescript try { await client.send('Hello'); } catch (e) { if (e instanceof PaymentRequiredError) { console.log('Need to pay:', e.paymentInfo); } } ``` ``` -------------------------------- ### Generated A2A Server — x402 Payment Middleware (PayAI) Source: https://context7.com/eversmile12/create-8004-agent/llms.txt This section describes the server-side setup for the A2A server, which wraps the POST /a2a route with x402 v2 USDC payment enforcement. It returns an HTTP 402 error with payment details if payment is missing. ```APIDOC ## POST /a2a ### Description Wraps the `POST /a2a` route with x402 v2 USDC payment enforcement using the PayAI or 4mica facilitator. Returns HTTP 402 with payment details when payment is missing. ### Method POST ### Endpoint /a2a ### Parameters #### Request Body - **(Implicit)** The request body is expected to be JSON, as indicated by `mimeType: 'application/json'`. ### Request Example ```bash curl -X POST http://localhost:3000/a2a -d '...' ``` ### Response #### Success Response (200) - **(Implicit)** A successful response would typically contain the result of the agent's processing. #### Error Response (402 Payment Required) - **accepts** (array) - Information about accepted payment methods and details. - **scheme** (string) - The payment scheme (e.g., "exact"). - **price** (string) - The required price (e.g., "$0.001"). - **network** (string) - The network identifier (e.g., "eip155:84532"). - **payTo** (string) - The address to pay to. ### Response Example (402) ```json { "accepts": [ { "scheme": "exact", "price": "$0.001", "network": "eip155:84532", "payTo": "0x..." } ] } ``` ``` -------------------------------- ### Send Message via A2A Server (Bash) Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Example curl commands to send a message to the A2A server's /a2a endpoint using JSON-RPC 2.0. Supports single messages and multi-turn conversations using contextId. ```bash # Single message curl -X POST http://localhost:3000/a2a \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "message/send", "params": { "message": { "role": "user", "parts": [{ "type": "text", "text": "What is the capital of France?" }] }, "configuration": {} }, "id": 1 }' # Response: # { # "jsonrpc": "2.0", # "result": { # "id": "550e8400-e29b-41d4-a716-446655440000", # "contextId": "660e8400-e29b-41d4-a716-446655440001", # "status": "completed", # "messages": [ # { "role": "user", "parts": [{ "type": "text", "text": "What is the capital of France?" }] }, # { "role": "agent", "parts": [{ "type": "text", "text": "The capital of France is Paris." }] }, # ], # "artifacts": [] # }, # "id": 1 # } # Continue the conversation using contextId curl -X POST http://localhost:3000/a2a \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "message/send", "params": { "message": { "role": "user", "parts": [{ "type": "text", "text": "What country is it in?" }] }, "configuration": { "contextId": "660e8400-e29b-41d4-a716-446655440001" } }, "id": 2 }' ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Set up your environment by filling in the required API keys and credentials in the .env file. Ensure your wallet is funded if auto-generated. ```env PRIVATE_KEY=... # Auto-generated if you left wallet empty OPENAI_API_KEY=your_openai_key # For LLM responses PINATA_JWT=your_pinata_jwt # If using IPFS storage (requires pinJSONToIPFS scope) ``` -------------------------------- ### Run Interactive Configuration Wizard Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Initiates the interactive wizard to gather all necessary project configurations. This function prompts the user for details such as project directory, agent name, description, image, blockchain network, wallet address, and feature selection. It handles directory name collisions and auto-generates wallets if not provided. ```typescript import { runWizard } from './src/wizard.js'; const answers = await runWizard(); // answers = { // projectDir: "my-agent", // agentName: "my agent", // agentDescription: "test agent created with create-8004-agent", // agentImage: "https://example.com/agent.png", // chain: "base-sepolia", // agentWallet: "0xABCD...1234", // generatedPrivateKey: "0xdeadbeef...", // set if auto-generated // features: ["a2a", "x402"], // a2aStreaming: false, // trustModels: ["reputation"], // x402Provider: "payai", // } ``` -------------------------------- ### Run Project Tests Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Command to execute the project's test suite. ```bash npm test ``` -------------------------------- ### generateProject(answers) Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Creates the full output directory structure and writes all source files based on wizard answers. It routes to specific chain generation functions and writes shared templates. ```APIDOC ## `generateProject(answers)` — Project File Generator **Creates the full output directory structure and writes all source files based on wizard answers.** Routes to `generateEVMProject()`, `generateSolanaProject()`, or `generateMonadProject()` based on chain. Always writes chain-agnostic shared templates (A2A server, MCP server, agent card) when those features are selected. Creates `src/`, `.well-known/` subdirectories automatically. ```typescript import { generateProject } from './src/generator.js'; await generateProject({ projectDir: 'my-agent', agentName: 'My Agent', agentDescription: 'A helpful agent', agentImage: 'https://example.com/agent.png', chain: 'eth-sepolia', agentWallet: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', features: ['a2a', 'mcp'], a2aStreaming: false, trustModels: ['reputation'], x402Provider: undefined, }); // Creates: // my-agent/ // ├── package.json // ├── .env // ├── tsconfig.json // ├── .gitignore // ├── README.md // ├── src/ // │ ├── register.ts // │ ├── agent.ts // │ ├── a2a-server.ts // │ ├── a2a-client.ts // │ ├── mcp-server.ts // │ └── tools.ts // └── .well-known/ // └── agent-card.json ``` ``` -------------------------------- ### Generate Agent Project Structure Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Use `generateProject` to create the full output directory structure and write all source files based on wizard answers. It routes to specific chain generators and includes shared templates. Creates `src/` and `.well-known/` subdirectories automatically. ```typescript import { generateProject } from './src/generator.js'; await generateProject({ projectDir: 'my-agent', agentName: 'My Agent', agentDescription: 'A helpful agent', agentImage: 'https://example.com/agent.png', chain: 'eth-sepolia', agentWallet: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e', features: ['a2a', 'mcp'], a2aStreaming: false, trustModels: ['reputation'], x402Provider: undefined, }); // Creates: // my-agent/ // ↗>↗ package.json // ↗>↗ .env // ↗>↗ tsconfig.json // ↗>↗ .gitignore // ↗>↗ README.md // ↗>↗ src/ // ↗>↗ ↗> register.ts // ↗>↗ ↗> agent.ts // ↗>↗ ↗> a2a-server.ts // ↗>↗ ↗> a2a-client.ts // ↗>↗ ↗> mcp-server.ts // ↗>↗ ↗> tools.ts // ↗> .well-known/ // ↗>↗ ↗> agent-card.json ``` -------------------------------- ### Register EVM Agent with agent0-sdk Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Use agent0-sdk to mint an agent NFT, upload metadata to IPFS, set trust models, and link the agent wallet via EIP-712 on EVM chains. ```typescript // Generated file content — run with: npm run register import 'dotenv/config'; import { SDK } from 'agent0-sdk'; const sdk = new SDK({ chainId: 11155111, // eth-sepolia rpcUrl: process.env.RPC_URL || 'https://ethereum-sepolia-rpc.publicnode.com', signer: process.env.PRIVATE_KEY!, ipfs: 'pinata', pinataJwt: process.env.PINATA_JWT!, }); const agent = sdk.createAgent('My Agent', 'A helpful agent', 'https://example.com/agent.png'); await agent.setA2A('https://my-agent.example.com/.well-known/agent-card.json'); await agent.setMCP('https://my-agent.example.com/mcp'); agent.setTrust(true, false, false); // reputation, crypto-economic, tee-attestation agent.setActive(false); // keep false until production-ready agent.setX402Support(false); // Optional OASF skills/domains for discoverability agent.addSkill('natural_language_processing/natural_language_generation/summarization'); agent.addDomain('technology/software_engineering'); const txHandle = await agent.registerIPFS(); const { result } = await txHandle.waitMined(); // Set agent wallet (ERC-8004 v2 — EIP-712 verified) const walletTx = await agent.setWallet('0x742d35Cc...'); await walletTx.waitMined(); console.log('Agent ID:', result.agentId); // → "eip155:11155111:123" console.log('View: https://www.8004scan.io/agents/sepolia/123'); ``` -------------------------------- ### Register Agent On-Chain Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Execute the registration script to upload metadata to IPFS and mint an NFT on the Identity Registry for EVM chains, or via the 8004 program for Solana. ```bash npm run register ``` -------------------------------- ### Access EVM Chain Configuration Source: https://context7.com/eversmile12/create-8004-agent/llms.txt The `CHAINS` registry provides a centralized map of supported EVM chains, including RPC URLs, chain IDs, x402 support, and USDC addresses. Check `x402Supported` before using payment features. ```typescript import { CHAINS } from './src/config.js'; // Access chain config const sepolia = CHAINS['eth-sepolia']; // { // name: "Ethereum Sepolia (Testnet)", // chainId: 11155111, // rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com", // x402Supported: true, // x402Providers: ["4mica"], // x402DefaultProvider: "4mica", // usdcAddress: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", // ... // } // Check x402 support before using payment features const chain = CHAINS['polygon-amoy']; if (chain.x402Supported) { console.log(`Providers: ${chain.x402Providers}`); // ["payai", "4mica"] console.log(`Default: ${chain.x402DefaultProvider}`); // "payai" console.log(`USDC: ${chain.usdcAddress}`); // "0x41E94Eb019..." } // All available chain keys type ChainKey = keyof typeof CHAINS; // "eth-mainnet" | "base-mainnet" | "avalanche-mainnet" | "polygon-mainnet" // | "monad-mainnet" | "skale-base-mainnet" | "eth-sepolia" | "base-sepolia" // | "avalanche-fuji" | "polygon-amoy" | "monad-testnet" | "skale-base-sepolia" ``` -------------------------------- ### Generated Agent Project Structure Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md This outlines the typical file structure generated by the create-8004-agent tool. Key files include the ERC-8004 metadata (`registration.json`), on-chain registration script (`register.ts`), agent logic (`agent.ts`), and protocol servers (`a2a-server.ts`, `mcp-server.ts`). ```bash my-agent/ ├── package.json ├── .env.example ├── registration.json # ERC-8004 metadata ├── tsconfig.json ├── src/ │ ├── register.ts # On-chain registration script │ ├── agent.ts # LLM agent (OpenAI) │ ├── a2a-server.ts # A2A protocol server (optional) │ ├── mcp-server.ts # MCP protocol server (optional) │ └── tools.ts # MCP tools (optional) └── .well-known/ └── agent-card.json # A2A discovery card ``` -------------------------------- ### Generated A2A Client — CLI Commands Source: https://context7.com/eversmile12/create-8004-agent/llms.txt This section outlines the command-line interface (CLI) commands available for the generated A2A client, including modes for discovery, interactive chat, and automated testing. ```APIDOC ## A2A Client CLI Commands ### Description Command-line interface for the generated `a2a-client.ts` with discover, interactive chat, test suite, and demo modes. ### Commands #### `npm run a2a:discover` - **Description**: Discovers agent capabilities and lists them. - **Example Output**: ``` # --- Agent Discovery --- # Name: My Agent # Capabilities: Streaming: false # Skills: # - Chat # General conversation and question answering ``` #### `npm run a2a:chat` - **Description**: Starts an interactive chat mode (REPL) with the agent. Supports commands like `/help`, `/new`, `/stream`, `/context`, `/exit`. - **Example Interaction**: ``` # Commands: /help /new /stream /context /exit # You: Hello! # Agent: Hello! How can I help you today? ``` #### `npm run a2a:test` - **Description**: Runs an automated test suite against the agent (includes tests for discovery, simple message, multi-turn, context isolation, and streaming). - **Example Output**: ``` # -------------------------------------------------- # [PASS] Agent Discovery (45ms) # [PASS] Simple Message (312ms) # [PASS] Multi-turn Conversation (589ms) # [PASS] Context Isolation (401ms) # [PASS] Streaming Response (skipped - streaming not enabled) # -------------------------------------------------- # 4/5 tests passed ``` #### `npx tsx src/a2a-client.ts --verbose` - **Description**: Runs the A2A client in verbose mode, displaying full JSON-RPC payloads for debugging purposes. ``` -------------------------------- ### A2A Client CLI Commands Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Command-line interface for the A2A client, supporting agent discovery, interactive chat, automated testing, and verbose output. ```bash # Discover agent capabilities npm run a2a:discover # --- Agent Discovery --- # Name: My Agent # Capabilities: Streaming: false # Skills: # - Chat # General conversation and question answering # Interactive chat mode (REPL with /help, /new, /stream, /context, /exit) npm run a2a:chat # Commands: /help /new /stream /context /exit # You: Hello! # Agent: Hello! How can I help you today? # Automated test suite (5 tests: discovery, simple message, multi-turn, context isolation, streaming) npm run a2a:test # -------------------------------------------------- # [PASS] Agent Discovery (45ms) # [PASS] Simple Message (312ms) # [PASS] Multi-turn Conversation (589ms) # [PASS] Context Isolation (401ms) # [PASS] Streaming Response (skipped - streaming not enabled) # -------------------------------------------------- # 4/5 tests passed # Verbose mode — shows full JSON-RPC payloads npx tsx src/a2a-client.ts --verbose ``` -------------------------------- ### Direct Contract Registration on Monad with viem Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Directly calls the Identity Registry contract on Monad using viem, as agent0-sdk does not yet support Monad. Upload metadata to Pinata IPFS, then register. ```typescript // Generated file content — run with: npm run register import 'dotenv/config'; import { createWalletClient, createPublicClient, http, parseAbi } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { defineChain } from 'viem'; const monadTestnet = defineChain({ id: 10143, name: 'Monad Testnet', nativeCurrency: { name: 'Monad', symbol: 'MON', decimals: 18 }, rpcUrls: { default: { http: ['https://testnet-rpc.monad.xyz'] } }, }); const IDENTITY_REGISTRY = '0x8004A818BFB912233c491871b3d84c89A494BD9e'; const IDENTITY_REGISTRY_ABI = parseAbi([ 'function register(string agentURI) external returns (uint256 agentId)', 'function balanceOf(address owner) external view returns (uint256)', ]); const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const walletClient = createWalletClient({ account, chain: monadTestnet, transport: http() }); const publicClient = createPublicClient({ chain: monadTestnet, transport: http() }); // Upload metadata to Pinata IPFS, then register const agentURI = 'ipfs://QmXxx...'; // result of Pinata upload const gasEstimate = await publicClient.estimateContractGas({ address: IDENTITY_REGISTRY, abi: IDENTITY_REGISTRY_ABI, functionName: 'register', args: [agentURI], account: account.address, }); const hash = await walletClient.writeContract({ address: IDENTITY_REGISTRY, abi: IDENTITY_REGISTRY_ABI, functionName: 'register', args: [agentURI], gas: gasEstimate * 120n / 100n, // 20% buffer }); const receipt = await publicClient.waitForTransactionReceipt({ hash }); // agentId parsed from ERC-721 Transfer event topics[3] ``` -------------------------------- ### Agent Registration Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Instructions for registering the agent on-chain for EVM and Solana networks. ```APIDOC ### 2. Register Agent On-Chain ```bash npm run register ``` **EVM chains:** Uploads metadata to IPFS and mints an NFT on the Identity Registry. **Solana:** Validates metadata using `buildRegistrationFileJson()`, uploads to IPFS, and mints a Metaplex Core NFT via the 8004 program. After registration, view your agent on [8004scan.io](https://www.8004scan.io/). ``` -------------------------------- ### SOLANA_CHAINS / isSolanaChain() / getSolanaChain() Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Provides a registry for Solana chains, including a type guard function `isSolanaChain` and an accessor function `getSolanaChain` for safe chain routing and configuration retrieval. ```APIDOC ## `SOLANA_CHAINS` / `isSolanaChain()` / `getSolanaChain()` — Solana Configuration **Solana chain registry with type guard and accessor for safe chain routing.** ```typescript import { SOLANA_CHAINS, isSolanaChain, getSolanaChain } from './src/config-solana.js'; // Type guard used throughout generator for chain routing isSolanaChain('solana-devnet'); // true isSolanaChain('eth-sepolia'); // false // Access typed config const devnet = getSolanaChain('solana-devnet'); // { // name: "Solana Devnet", // cluster: "devnet", // rpcUrl: "https://api.devnet.solana.com", // explorer: "https://explorer.solana.com", // explorerSuffix: "?cluster=devnet", // programId: "HvF3JqhahcX7JfhbDRYYCJ7S3f6nJdrqu5yi9hyTREp", // x402Network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", // } // Combined usage in generator import { CHAINS } from './src/config.js'; function getChainConfig(chain: string) { if (isSolanaChain(chain)) return getSolanaChain(chain as SolanaChainKey); return CHAINS[chain as ChainKey]; } ``` ``` -------------------------------- ### Optional 4mica Collateral Deposit in TypeScript Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Interactively prompts the user to register with the 4mica credit facilitator and handles ERC-20 approval and deposit. This function is called automatically after `generateProject()` in the CLI flow and only activates under specific conditions (x402 feature selected + supported chain). ```typescript import { maybeRegisterWithFourmica } from './src/fourmica.js'; // Called automatically after generateProject() in the CLI flow. // Only activates when: x402 feature selected + chain supports 4mica (eth-sepolia or polygon-amoy) await maybeRegisterWithFourmica(answers); // Console interaction: // ? Register with 4mica now (optional collateral deposit)? (y/N) // ? Collateral asset to deposit: USDC / USDT / Native token // ? Deposit amount (USDC): 1 // // Possible outcomes: // ✅ "4mica registration deposit submitted." // "Deposit tx: 0xabc..." // // ⚠️ "Insufficient USDC balance for 4mica registration." // "Add at least 1 USDC to 0x... and re-run if you want to register." // // ✅ "4mica collateral already funded (>= 1 USDC)." ← if collateral already ≥ amount // Internal: uses @4mica/sdk ConfigBuilder + Client import { Client, ConfigBuilder } from '@4mica/sdk'; const cfg = new ConfigBuilder() .rpcUrl('https://ethereum.sepolia.api.4mica.xyz') .walletPrivateKey('0xdeadbeef...') .build(); const client = await Client.new(cfg); await client.user.approveErc20(usdcAddress, amountBaseUnits); const receipt = await client.user.deposit(amountBaseUnits, usdcAddress); // receipt.transactionHash → "0xabc123..." await client.aclose(); ``` -------------------------------- ### LLM Core Functions (TypeScript) Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Provides low-level chat, high-level response generation, and streaming capabilities using the OpenAI API. Ensure OPENAI_API_KEY is set in your environment. ```typescript // In the generated project: src/agent.ts import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); export interface AgentMessage { role: 'user' | 'assistant' | 'system'; content: string; } // Low-level: raw message array → response text export async function chat(messages: AgentMessage[]): Promise { const response = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages: messages.map(m => ({ role: m.role, content: m.content })), }); return response.choices[0]?.message?.content ?? 'No response'; } // High-level: user text + optional history → response text export async function generateResponse( userMessage: string, history: AgentMessage[] = [] ): Promise { const systemPrompt: AgentMessage = { role: 'system', content: 'You are a helpful AI assistant registered on the ERC-8004 protocol. Be concise and helpful.' }; return chat([systemPrompt, ...history, { role: 'user', content: userMessage }]); } // Streaming variant (generated only when a2aStreaming: true) export async function* streamResponse( userMessage: string, history: AgentMessage[] = [] ): AsyncGenerator { const stream = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages: [ { role: 'system', content: 'You are a helpful AI assistant...' }, ...history.map(m => ({ role: m.role, content: m.content })), { role: 'user', content: userMessage }, ], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content; if (content) yield content; } } ``` -------------------------------- ### Test JSON-RPC Message Send Method Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Send a test message to the agent's JSON-RPC endpoint at /a2a using the message/send method. ```bash curl -X POST http://localhost:3000/a2a \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "message/send", "params": { "message": { "role": "user", "parts": [{"type": "text", "text": "Hello!"}] } }, "id": 1 }' ``` -------------------------------- ### Register Solana Agent with 8004-solana SDK Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Uses the 8004-solana SDK to validate metadata, upload to IPFS via Pinata, and mint an agent NFT via the 8004 Metaplex program on Solana devnet. ```typescript // Generated file content — run with: npm run register import 'dotenv/config'; import fs from 'fs/promises'; import { Keypair } from '@solana/web3.js'; import bs58 from 'bs58'; import { SolanaSDK, IPFSClient, buildRegistrationFileJson } from '8004-solana'; const keypair = Keypair.fromSecretKey(bs58.decode(process.env.SOLANA_PRIVATE_KEY!)); // Read and validate registration.json const registration = JSON.parse(await fs.readFile('registration.json', 'utf-8')); const validatedJson = buildRegistrationFileJson(registration); // validates OASF + adds type/version // Upload to IPFS const ipfsClient = new IPFSClient({ pinataEnabled: true, pinataJwt: process.env.PINATA_JWT! }); const cid = await ipfsClient.add(JSON.stringify(validatedJson)); const metadataUri = `ipfs://${cid}`; // Register on-chain const sdk = new SolanaSDK({ cluster: 'devnet', signer: keypair }); const result = await sdk.registerAgent(metadataUri); console.log('Transaction:', `https://explorer.solana.com/tx/${result.signature}?cluster=devnet`); console.log('Agent ID:', result.agentId?.toString()); console.log('Asset:', result.asset?.toBase58()); // registration.json is updated with { registrations: [{ agentId, asset, signature, cluster }] } ``` -------------------------------- ### Define MCP Tools and Handle Tool Calls in TypeScript Source: https://context7.com/eversmile12/create-8004-agent/llms.txt Defines the 'chat', 'echo', and 'get_time' tools for an MCP agent and implements the `handleToolCall` function to process them. Ensure the agent's response generation logic is correctly implemented in `generateResponse`. ```typescript // Generated in src/tools.ts import { generateResponse } from './agent.js'; export const tools = [ { name: 'chat', description: 'Have a conversation with the AI agent', inputSchema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] }, }, { name: 'echo', description: 'Echo back the input message (for testing)', inputSchema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'] }, }, { name: 'get_time', description: 'Get the current time', inputSchema: { type: 'object', properties: {}, required: [] }, }, ]; export async function handleToolCall(name: string, args: Record): Promise { switch (name) { case 'chat': return { response: await generateResponse(args.message as string) }; // { response: "The capital of France is Paris." } case 'echo': return { echoed: args.message }; // { echoed: "Hello, world!" } case 'get_time': return { time: new Date().toISOString() }; // { time: "2025-07-01T12:00:00.000Z" } default: throw new Error(`Unknown tool: ${name}`); } } // Start MCP server (stdio transport): // npm run start:mcp // 🔧 MCP Server running on stdio // Test with MCP Inspector: // npx @modelcontextprotocol/inspector ``` -------------------------------- ### CHAINS Source: https://context7.com/eversmile12/create-8004-agent/llms.txt A centralized map of all supported EVM chains, providing configuration details such as RPC URLs, chain IDs, and USDC addresses. ```APIDOC ## `CHAINS` — EVM Chain Configuration Registry **Centralized map of all supported EVM chains with RPC URLs, chain IDs, x402 support flags, USDC addresses, and facilitator URLs.** ```typescript import { CHAINS } from './src/config.js'; // Access chain config const sepolia = CHAINS['eth-sepolia']; // { // name: "Ethereum Sepolia (Testnet)", // chainId: 11155111, // rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com", // x402Supported: true, // x402Providers: ["4mica"], // x402DefaultProvider: "4mica", // usdcAddress: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", // ... // } // Check x402 support before using payment features const chain = CHAINS['polygon-amoy']; if (chain.x402Supported) { console.log(`Providers: ${chain.x402Providers}`); // ["payai", "4mica"] console.log(`Default: ${chain.x402DefaultProvider}`); // "payai" console.log(`USDC: ${chain.usdcAddress}`); // "0x41E94Eb019..." } // All available chain keys type ChainKey = keyof typeof CHAINS; // "eth-mainnet" | "base-mainnet" | "avalanche-mainnet" | "polygon-mainnet" // | "monad-mainnet" | "skale-base-mainnet" | "eth-sepolia" | "base-sepolia" // | "avalanche-fuji" | "polygon-amoy" | "monad-testnet" | "skale-base-sepolia" ``` ``` -------------------------------- ### Test Agent Card Endpoint Source: https://github.com/eversmile12/create-8004-agent/blob/main/README.md Fetch the agent's card information from the /.well-known/agent-card.json endpoint to verify the A2A server is running. ```bash curl http://localhost:3000/.well-known/agent-card.json ``` -------------------------------- ### Generated registration.json for Solana Agent Metadata Source: https://context7.com/eversmile12/create-8004-agent/llms.txt A static metadata file used as input for `buildRegistrationFileJson()` in Solana projects. This file is updated in-place with on-chain registration results after running `npm run register`. ```json { "name": "My Agent", "description": "A helpful agent", "image": "https://example.com/agent.png", "active": false, "endpoints": [ { "type": "A2A", "value": "https://my-agent.example.com/.well-known/agent-card.json", "meta": { "version": "0.3.0" } }, { "type": "MCP", "value": "https://my-agent.example.com/mcp", "meta": { "version": "2025-06-18" } }, { "type": "agentWallet", "value": "solana:devnet:8xGt9..." } ], "skills": [], "domains": [], "trustModels": ["reputation"], "registrations": [ { "agentId": "42", "asset": "DYm8K...", "signature": "5Hj9p...", "cluster": "devnet" } ] } ```