> ## Documentation Index
> Fetch the complete documentation index at: https://base-a060aa97-danc-alpha-docs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Mini Apps & Agents

> Learn how to integrate Mini Apps with chat agents for seamless in-conversation experiences that drive engagement and virality.

> **What you'll learn**\
> By the end of this guide, you'll be able to:
>
> * Integrate Mini Apps with chat agents for seamless in-conversation experiences
> * Share Mini Apps directly through agent messages with rich previews
> * Create engaging group experiences using agents and Mini Apps together
> * Implement user mentions and social features in agent-driven Mini App experiences
> * Build viral, conversational Mini App distribution through chat

## Why Mini Apps & Agents Together?

Mini Apps can live inside conversations, letting friends play, trade, plan, and coordinate together without ever leaving the chat.

This means that you can have virality spread through natural conversation ("try this right here") along with sharing in larger settings. When combined with intelligent agents, you create powerful experiences that spread through natural conversation.

This integration unlocks unique distribution and engagement patterns:

**Natural virality:** "Try this right here" moments spread organically through conversation
**Contextual engagement:** Agents can introduce Mini Apps at the perfect moment
**Group coordination:** Agents orchestrate multiplayer experiences and keep everyone engaged
**Persistent presence:** Agents maintain engagement between Mini App sessions

**Real Examples:**

• **Group Gaming:** Agent coordinates a multiplayer quiz, announces winners, and keeps score across sessions
• **Event Planning:** Agent shares planning Mini App when someone mentions meeting up, handles RSVPs and updates
• **Trading Competitions:** Agent creates trading challenges, shares leaderboards, and celebrates wins
• **Social Polls:** Agent launches polls when decisions need to be made, tallies results, and announces outcomes

## How Integration Works

### 1. Share Mini Apps in App

Every Mini App has a shareable URL that agents can send directly in chat. When dropped into a conversation, the link automatically unfurls into a rich preview card that others can tap to launch instantly.

**Share Flow:**

1. **Agent triggers share** — Based on conversation context or user request
2. **Link generates preview** — Platform fetches Mini App metadata and creates rich embed
3. **Users engage** — Tap preview to launch Mini App directly in conversation
4. **Agent coordinates** — Continues engagement, shares updates, mentions participants

### Technical Implementation

**Basic Mini App Sharing:**

```typescript
import { Client } from "@xmtp/node-sdk";

// Share a Mini App in response to a trigger
async function shareMiniApp(conversation, appUrl, description) {
  await conversation.send(`${description}\n\n${appUrl}`);
}

// Example usage
await shareMiniApp(
  conversation,
  "https://your-miniapp.com/quiz",
  "🎯 Ready for a quick quiz challenge?"
);
```

**Advanced Integration with Context:**

```typescript
// Agent detects conversation context and shares relevant Mini App
async function handleMessage(message, conversation) {
  const text = message.content.toLowerCase();
  
  if (text.includes("game") || text.includes("play")) {
    await shareMiniApp(
      conversation,
      "https://your-miniapp.com/games",
      "🎮 Let's play! Choose your game:"
    );
  } else if (text.includes("vote") || text.includes("decide")) {
    await shareMiniApp(
      conversation,
      "https://your-miniapp.com/poll",
      "🗳️ Let's settle this with a poll:"
    );
  }
}
```

## User Engagement & Mentions

### 2. Engage & Mention Users

Agents on XMTP only have access to the 0x addresses. If you're building a group chat experience with Mini Apps, you'll want to use human-readable mentions like display names (like @jesse) for a more social, intuitive experience.

This API from Neynar will give your agent access to this data:

**Getting Display Names:**

```typescript
import { NeynarAPIClient } from "@neynar/nodejs-sdk";

const neynar = new NeynarAPIClient("YOUR_API_KEY");

async function getDisplayName(address) {
  try {
    const users = await neynar.lookupUserByVerification(address);
    return users.result.users[0]?.display_name || address.slice(0, 8);
  } catch (error) {
    return address.slice(0, 8); // Fallback to truncated address
  }
}

// Usage in agent messages
async function announceWinner(conversation, winnerAddress, gameType) {
  const displayName = await getDisplayName(winnerAddress);
  await conversation.send(`🏆 @${displayName} wins the ${gameType}! Amazing job!`);
}
```

### Creating Social Group Experiences

**Example: Multiplayer Game Coordination**

```typescript
class GameAgent {
  private activeGames = new Map();
  
  async handleGameMessage(message, conversation) {
    const gameId = conversation.id;
    
    if (message.content.includes("/start")) {
      await this.startGame(conversation, gameId);
    } else if (message.content.includes("/join")) {
      await this.joinGame(conversation, gameId, message.senderAddress);
    } else if (message.content.includes("/results")) {
      await this.shareResults(conversation, gameId);
    }
  }
  
  async startGame(conversation, gameId) {
    const gameUrl = `https://your-miniapp.com/game/${gameId}`;
    this.activeGames.set(gameId, { players: [], started: Date.now() });
    
    await conversation.send(
      `🎮 New game starting! Tap to join:\n\n${gameUrl}\n\nType /join to register`
    );
  }
  
  async joinGame(conversation, gameId, playerAddress) {
    const game = this.activeGames.get(gameId);
    if (!game.players.includes(playerAddress)) {
      game.players.push(playerAddress);
      
      const displayName = await getDisplayName(playerAddress);
      await conversation.send(`✅ @${displayName} joined the game! ${game.players.length} players ready`);
    }
  }
  
  async shareResults(conversation, gameId) {
    const game = this.activeGames.get(gameId);
    const results = await fetchGameResults(gameId); // Your game API
    
    let message = "🏆 Game Results:\n\n";
    for (let i = 0; i < results.length; i++) {
      const displayName = await getDisplayName(results[i].address);
      message += `${i + 1}. @${displayName} - ${results[i].score} points\n`;
    }
    
    await conversation.send(message);
  }
}
```

## Agent Spotlight

[Squabble](https://github.com/builders-garden/squabble) uses Mini Apps in a social, fun way, with the agent coordinating the multiplayer experience. Check out their GitHub repo for guidance!

The agent sends a Mini App to the group, and broadcasts to the group updates as people join and compete in the game. They mention the usernames of the people who have joined the game and won the game. The game happens inside the Mini App, which provides a more interactive, visual experience.

### How Squabble Works

<Steps>
  <Step title="Agent initiates game">
    Agent detects gaming context in conversation and shares the Squabble Mini App URL, which unfurls as a rich preview card.
  </Step>

  <Step title="Players join through Mini App">
    Users tap the preview to launch the Mini App, join the game, and start playing the interactive word game.
  </Step>

  <Step title="Agent coordinates experience">
    Agent monitors game progress and broadcasts updates to the group as players join and compete.
  </Step>

  <Step title="Agent celebrates results">
    Agent mentions winners by username, shares final scores, and encourages replay for ongoing engagement.
  </Step>
</Steps>

**Key Features:**

* **Rich mentions** — Agent uses display names (@username) instead of wallet addresses
* **Real-time updates** — Broadcasts join notifications and game progress to maintain group engagement
* **Social celebration** — Announces winners and achievements to drive continued participation
* **Contextual triggers** — Responds to gaming-related conversation with relevant Mini App shares

## Content Types for Mini App Integration

### Quick Actions for Mini App Engagement

Use Quick Actions to create interactive buttons that guide users to your Mini Apps:

```typescript
// Quick Actions for Mini App discovery
const gameActions = {
  id: "game_selection",
  description: "Choose your game mode:",
  actions: [
    { 
      id: "solo_game", 
      label: "Solo Challenge", 
      style: "primary" 
    },
    { 
      id: "group_game", 
      label: "Group Battle", 
      style: "secondary" 
    },
    { 
      id: "tournament", 
      label: "Join Tournament", 
      style: "danger" 
    }
  ]
};

await conversation.send("🎮 Ready to play?", gameActions);
```

### Transaction Integration

Combine Mini Apps with transaction capabilities for seamless onchain experiences:

```typescript
// Example: In-game purchase or reward distribution
const rewardTransaction = {
  version: "1.0",
  from: agentAddress,
  chainId: 8453, // Base
  calls: [{
    to: rewardContractAddress,
    data: "0x...", // Encoded function call
    value: "0"
  }],
  metadata: {
    description: "Claim your game rewards",
    hostname: "your-miniapp.com",
    faviconUrl: "https://your-miniapp.com/favicon.ico",
    title: "Game Rewards"
  }
};
```

## Best Practices

### Agent Behavior

<AccordionGroup>
  <Accordion title="Timing and Context">
    * **Smart triggers** — Share Mini Apps when conversation context suggests engagement opportunity
    * **Avoid spam** — Don't share the same Mini App repeatedly in short timeframes
    * **Read the room** — Gauge group interest before introducing games or activities
    * **Natural integration** — Make Mini App shares feel like helpful suggestions, not advertisements
  </Accordion>

  <Accordion title="Group vs. Direct Messages">
    * **Direct messages** — Automatically share relevant Mini Apps based on user requests
    * **Group messages** — Only share Mini Apps when mentioned (@agentname) or when replying to agent messages
    * **React to acknowledge** — Use emoji reactions (👀, ⌛) to show message received while processing
    * **Coordinate experience** — In groups, act as facilitator for multiplayer Mini App experiences
  </Accordion>

  <Accordion title="User Experience">
    * **Use display names** — Always resolve addresses to human-readable names for mentions
    * **Celebrate achievements** — Announce wins, completions, and milestones to drive engagement
    * **Maintain context** — Remember ongoing games/activities and provide relevant updates
    * **Enable discovery** — Suggest related Mini Apps based on user interests and behavior
  </Accordion>
</AccordionGroup>

### Technical Implementation

* **Error handling** — Gracefully handle Mini App load failures or API timeouts
* **Rate limiting** — Respect XMTP message limits and avoid overwhelming conversations
* **State management** — Track active Mini App sessions and user participation across conversations
* **Privacy** — Only access necessary user data and respect privacy preferences

## Implementation Guide

### Setting Up Mini App Integration

<Steps>
  <Step title="Configure agent with Mini App URLs">
    Set up your agent with a catalog of Mini App URLs and their associated triggers or contexts.

    ```typescript
    const miniApps = {
      games: "https://your-miniapp.com/games",
      polls: "https://your-miniapp.com/polls", 
      trading: "https://your-miniapp.com/trading",
      events: "https://your-miniapp.com/events"
    };
    ```
  </Step>

  <Step title="Implement context detection">
    Create logic to detect when sharing a Mini App would be valuable based on conversation content.

    ```typescript
    function detectMiniAppContext(message) {
      const content = message.content.toLowerCase();
      if (content.includes("game") || content.includes("play")) return "games";
      if (content.includes("vote") || content.includes("poll")) return "polls";
      return null;
    }
    ```
  </Step>

  <Step title="Add user mention capabilities">
    Integrate with Neynar API or similar service to resolve addresses to display names for better UX.
  </Step>

  <Step title="Test integration">
    Verify Mini App previews render correctly and agent coordination works across different conversation types.
  </Step>
</Steps>

### Next Steps

Ready to build your Mini App & Agent integration?

* **Study the [Squabble example](https://github.com/builders-garden/squabble)** — See real implementation patterns
* **Review [Chat Agents guide](/base-app/agents/chat-agents)** — Understand XMTP agent fundamentals
* **Explore [Mini Apps documentation](/base-app/miniapps/mini-apps)** — Learn Mini App development
* **Join [XMTP community](https://community.xmtp.org/)** — Get help and share your builds

By combining Mini Apps with intelligent agents, you create engaging, viral experiences that spread naturally through conversation while providing rich, interactive functionality that keeps users coming back.
