Build an agent that uses XMTP
This guide covers how to build agents that communicate with humans and other agents in chats that provide all of XMTP's messaging security properties.
Resources to get started
Quickstart video guide
Agent examples
Explore and run example agents built with the XMTP Node SDK in the xmtp-agent-examples repo.
Cursor rules
You can use these Cursor rules to code agents with AI following XMTP development best practices.
Listen for and send messages
These are the steps to initialize the XMTP listener and send messages.
// 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");
}
To learn more about Client.create
, see Create an XMTP client.
To learn more about conversations.sync
, see Sync new conversations.
To learn more about conversations.streamAllMessages
, see Stream all group chat and DM messages and preferences.
To learn more about conversations.getConversationById
, see Conversation helper methods.
To learn more about conversation.send
, see Send messages.
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, like passkeys and EVM wallet addresses.
const inboxState = await client.preferences.inboxStateFromInboxIds([
message.senderInboxId,
]);
const addressFromInboxId = inboxState[0].identifiers[0].identifier;
To learn more, see View the inbox state.
Try out your agent using xmtp.chat
Test and interact with your agent using xmtp.chat, the official web inbox for developers.