Skip to content

Tutorial: Build an agent that uses XMTP

This tutorial provides a map to building agents with the XMTP Node SDK. These agents can communicate with humans and other agents in chats built with XMTP.

Building with XMTP gives your agent access to:

  • The most secure, decentralized messaging network
  • The building blocks of AI + money + secure chat
  • Users on apps built with XMTP, including Coinbase Wallet, Convos, and more

Resources to get started

Quickstart video guide

Agent examples

From a simple agent that replies "GM" to one that supports onchain transactions, explore and run a dozen xmtp-agent-examples built with the XMTP Node SDK.

Cursor rules

You can use these Cursor rules to code agents with AI following XMTP development best practices.

Build an agent

Listen for and send messages

These are the steps to initialize the XMTP listener and send messages.

Node
// import the xmtp sdk
import { Client, type XmtpEnv, type Signer } from "@xmtp/node-sdk";
 
// encryption key, must be consistent across runs
const encryptionKey: Uint8Array = ...;
const signer: Signer = ...;
const env: XmtpEnv = "dev";
 
// create the client
const client = await Client.create(signer, { encryptionKey, env });
// sync the client to get the latest messages
await client.conversations.sync();
 
// listen to all messages
const stream = await client.conversations.streamAllMessages();
for await (const message of stream) {
  // ignore messages from the agent
  if (message?.senderInboxId === client.inboxId) continue;
  // get the conversation by id
  const conversation = await client.conversations.getConversationById(message.conversationId);
  // send a message from the agent
  await conversation.send("gm");
}

Get the address of a user

Each user has a unique inboxId used to retrieve their associated addresses (identities). One inboxId can have multiple identities, such as EOAs and SCWs.

Node
const inboxState = await client.preferences.inboxStateFromInboxIds([
  message.senderInboxId,
]);
const addressFromInboxId = inboxState[0].identifiers[0].identifier;

Support onchain transactions and transaction references

To learn more, see the example xmtp-transactions agent, as well as the Support onchain transactions and Support onchain transaction references (receipts) documentation.

Support attachments

To learn more, see the example xmtp-attachments agent and Support attachments documentation.

Support replies

To learn more, see Support replies documentation.

Support reactions

To learn more, see Support reactions documentation.

Observe rate limits

XMTP enforces separate rate limits for read and write operations per client.

To learn more, see Observe rate limits

Follow security best practices

To learn more, see Follow agent security best practices

Manage agent installations

To learn more, see Manage agent installations.

Debug an agent

To learn more, see Debug an agent

Deploy an agent

To learn more, see Deploy an agent.

Get featured