# How to integrate Habitica MCP with Pydantic AI

```json
{
  "title": "How to integrate Habitica MCP with Pydantic AI",
  "toolkit": "Habitica",
  "toolkit_slug": "habitica",
  "framework": "Pydantic AI",
  "framework_slug": "pydantic-ai",
  "url": "https://composio.dev/toolkits/habitica/framework/pydantic-ai",
  "markdown_url": "https://composio.dev/toolkits/habitica/framework/pydantic-ai.md",
  "updated_at": "2026-05-12T10:14:30.940Z"
}
```

## Introduction

This guide walks you through connecting Habitica to Pydantic AI using the Composio tool router. By the end, you'll have a working Habitica agent that can add a new daily task for exercise, create a challenge for team productivity, delete an outdated task from your challenge through natural language commands.
This guide will help you understand how to give your Pydantic AI agent real control over a Habitica account through Composio's Habitica MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Habitica with

- [OpenAI Agents SDK](https://composio.dev/toolkits/habitica/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/habitica/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/habitica/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/habitica/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/habitica/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/habitica/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/habitica/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/habitica/framework/cli)
- [Google ADK](https://composio.dev/toolkits/habitica/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/habitica/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/habitica/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/habitica/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/habitica/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/habitica/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- How to set up your Composio API key and User ID
- How to create a Composio Tool Router session for Habitica
- How to attach an MCP Server to a Pydantic AI agent
- How to stream responses and maintain chat history
- How to build a simple REPL-style chat interface to test your Habitica workflows

## What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.
Key features include:
- Type Safety: Built on Pydantic for automatic data validation
- MCP Support: Native support for Model Context Protocol servers
- Streaming: Built-in support for streaming responses
- Async First: Designed for async/await patterns

## What is the Habitica MCP server, and what's possible with it?

The Habitica MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Habitica account. It provides structured and secure access to your tasks, challenges, and groups, so your agent can create tasks, manage challenges, organize groups, and automate productivity routines on your behalf.
- Automated task creation and management: Let your agent create new tasks, set up habits, or add to-dos to keep your productivity on track—no manual entry needed.
- Challenge and group organization: Easily create, edit, or delete Habitica challenges and groups so you can coordinate goals and activities with teams or friends.
- Tag and webhook automation: Have your agent generate new tags for smarter task sorting or set up webhooks for real-time notifications when tasks change or are completed.
- Subscription and group membership management: Direct your agent to check or cancel subscriptions, leave parties, or delete groups as your needs change.
- Seamless challenge task updates: Effortlessly add or remove tasks within challenges, helping you keep group goals relevant and up to date.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `HABITICA_ADD_CHALLENGE_TASK` | Add Task to Challenge | Tool to add a new task to a specified challenge. Use when you need to programmatically create a challenge task after the challenge is set up and you have its ID. |
| `HABITICA_ADD_PUSH_DEVICE` | Add Push Device | Tool to register a push notification device for the authenticated user. Use when you need to enable push notifications for mobile devices or UnifiedPush clients. |
| `HABITICA_ADD_TAG_TO_TASK` | Add Tag to Task | Tool to add a tag to a task. Use when you need to categorize or label a task with an existing tag. |
| `HABITICA_CLONE_CHALLENGE` | Clone Challenge | Tool to clone an existing challenge. Use when you need to duplicate a challenge to a different group with a new name. |
| `HABITICA_CREATE_CHALLENGE` | Create Challenge | Tool to create a new challenge. Use when you need to start a challenge in a specific group with title, summary, and optional tasks. |
| `HABITICA_CREATE_GROUP` | Create Habitica Party | Create a new Habitica party for collaborative gameplay. Use this tool to create a party where users can: - Participate in quests together - Chat with party members - Share achievements and progress **Important Notes:** - A user can only be in one party at a time. If already in a party, they must leave first. - Guilds are no longer supported by Habitica (removed August 2023). Only 'party' type works. - The authenticated user automatically becomes the party leader. |
| `HABITICA_CREATE_TAG` | Create Tag | Tool to create a new tag. Use after determining the desired tag name. |
| `HABITICA_CREATE_TASK` | Create Task | Create a new task in Habitica. Supports four task types: - 'habit': Recurring positive/negative actions (use up/down to enable +/- buttons) - 'daily': Scheduled tasks that repeat on a schedule (configure with frequency, repeat, startDate) - 'todo': One-time tasks with optional due date (use date field) - 'reward': Custom rewards that cost gold (set value for the gold cost) Required fields: text (task title), type (habit/daily/todo/reward). Optional: notes, priority (0.1=Trivial, 1=Easy, 1.5=Medium, 2=Hard), tags, checklist. |
| `HABITICA_CREATE_WEBHOOK` | Create Webhook | Tool to create a new webhook for taskActivity events. Use when you need real-time notifications of task creation, updates, deletion, or scoring. |
| `HABITICA_DELETE_CHALLENGE` | Delete Habitica Challenge | Permanently delete a Habitica challenge. Only the challenge leader (creator) or an admin can delete a challenge. This action is irreversible - once deleted, the challenge and all associated tasks are permanently removed. Use HABITICA_GET_USER_CHALLENGES to find challenge IDs you own. |
| `HABITICA_DELETE_GROUP` | Leave or Delete Habitica Group | Leave or delete a Habitica group (party or guild). This tool allows you to: 1. Leave a party: Pass 'party' as groupId or the party's UUID to leave your current party. 2. Leave a guild: Pass the guild's UUID to leave the guild. 3. Delete a guild: If you are the leader and there are no other members, passing the guild's UUID will delete it (DELETE endpoint is tried if leave fails). Note: The Habitica API endpoint used is POST /groups/:groupId/leave. Only if that fails (e.g., you're the leader trying to delete an empty guild), the DELETE /groups/:groupId endpoint is attempted. |
| `HABITICA_DELETE_GROUP_CHAT_MESSAGE` | Delete Group Chat Message | Tool to delete a chat message from a Habitica group (party, guild, or Tavern). Use when you need to remove a specific chat message. Note that only the message author or group moderators can delete messages. |
| `HABITICA_DELETE_TAG` | Delete Habitica Tag | Tool to delete a tag for the authenticated user. Use when you need to remove an obsolete tag after confirming it’s no longer applied to any tasks. |
| `HABITICA_DELETE_TASK` | Delete Task | Permanently deletes a user's task (habit, daily, todo, or reward) by its ID. The task cannot be recovered after deletion. Use get_tasks to list tasks and their IDs first. |
| `HABITICA_DELETE_TASK_CHECKLIST_ITEM` | Delete Task Checklist Item | Tool to delete a checklist item from a task. Use when you need to remove a specific checklist item from a todo or daily task. |
| `HABITICA_DELETE_USER_MESSAGE_BY_ID` | Delete User Message | Tool to delete a message from the authenticated user's inbox by its ID. Use when you need to remove a specific message from the user's Habitica inbox. |
| `HABITICA_DELETE_USER_PUSH_DEVICE` | Delete User Push Device | Tool to remove a push device registration from the authenticated user's account. Use when you need to unregister a device that should no longer receive push notifications. |
| `HABITICA_EQUIP_ITEM` | Equip Item | Tool to equip or unequip gear, pets, mounts, or costume items in Habitica. Use when you need to change the user's equipped items. Equipping an already-equipped item will unequip it. |
| `HABITICA_EXPORT_CHALLENGE_CSV` | Export Challenge to CSV | Tool to export a Habitica challenge to CSV format. Use when you need to download challenge data as a CSV file. The CSV contains all challenge tasks and participant information. |
| `HABITICA_GET_CHALLENGE` | Get Challenge | Tool to retrieve details of a specific challenge. Use when you have the challenge ID and need its full data. |
| `HABITICA_GET_CHALLENGES` | Get Group Challenges | Tool to retrieve challenges available in a specific group (guild, party, or tavern). |
| `HABITICA_GET_CHALLENGE_TASK` | Get Task by ID | Retrieve a task by its unique ID. Works for any Habitica task type (habit, daily, todo, reward) whether it belongs to a challenge or is a personal user task. Returns full task details including type-specific properties like completion status, streaks, and scheduling information. |
| `HABITICA_GET_CHALLENGE_TASKS` | Get Challenge Tasks | Tool to get all tasks for a specified challenge. Use when you have a challenge ID and need to list its defined tasks, including challenge metadata per task. |
| `HABITICA_GET_CONTENT` | Get Content | Retrieves all Habitica game content definitions in a single request. Returns ~9MB of static game data including achievements, quests, gear, pets, mounts, eggs, hatching potions, food, backgrounds, spells, and more. Use cases: - Loading full game content to cache for local lookups - Getting all available items, quests, or equipment for reference - Building item pickers or content browsers Note: For specific content types, prefer get_content_by_type to reduce payload size. This endpoint requires no authentication but returns localized English text by default. |
| `HABITICA_GET_CONTENT_BY_TYPE` | Get Content By Type | Retrieves Habitica game content data filtered by a specific category type. Use this tool to fetch game definitions like quest details, equipment stats, pet/mount info, backgrounds, spells, or other static game content. Useful when you need specific category data without fetching all content at once. |
| `HABITICA_GET_EXPORT_HISTORY_CSV` | Get Export History CSV | Tool to export user tasks history in CSV format. Returns CSV data with task completions and updates over time. |
| `HABITICA_GET_EXPORT_INBOX_HTML` | Get Export Inbox HTML | Tool to export inbox data in HTML format from Habitica. Use when you need to retrieve the user's private messages and inbox content as an HTML document. |
| `HABITICA_GET_EXPORT_USERDATA_JSON` | Export User Data JSON | Exports the authenticated user's complete data in JSON format. Use when you need a full backup or comprehensive snapshot of all user data. Returns the raw internal data structure with all fields and nested objects. |
| `HABITICA_GET_GROUP` | Get Group | Retrieves detailed information about a Habitica group (guild or party). Use 'party' as groupId to get the user's current party, or provide a specific group UUID obtained from HABITICA_GET_GROUPS. |
| `HABITICA_GET_GROUP_MEMBERS` | Get Group Members | Retrieve members of a Habitica group (guild or party). Supports pagination via lastId parameter and optional search filtering. Use 'party' as groupId to get members of the current user's party. |
| `HABITICA_GET_GROUPS` | Get Habitica Groups | Retrieves Habitica groups based on type. Use 'guilds' to get all guilds the authenticated user belongs to, 'party' to get the user's current party, or 'tavern' to get the global Tavern (the main public chat). |
| `HABITICA_GET_GROUPS_HABITRPG` | Get Habitica Tavern Group | Tool to retrieve the Habitica Tavern (habitrpg) group details. The Tavern is the main public group where all Habitica users can chat and participate in community discussions. |
| `HABITICA_GET_GROUPS_PARTY_CHAT` | Get Party Chat Messages | Tool to retrieve party chat messages from Habitica. Use when you need to fetch recent chat messages from the authenticated user's party. |
| `HABITICA_GET_MODELS_MODEL_PATHS` | Get Model Paths | Retrieves all available field paths and their data types for a specified Habitica model. Use this to discover the structure and available fields for user, group, challenge, tag, or task models. Helpful for understanding what fields can be queried or updated. |
| `HABITICA_GET_NEWS` | Get News | Tool to retrieve the latest Bailey announcement from Habitica. Use when you need to check current news, events, or updates posted by Bailey. |
| `HABITICA_GET_PARTY` | Get Party | Retrieves the authenticated user's party details from Habitica. Returns information about the user's current party including: - Party name, description, and member count - Party leader information - Current quest status and progress - Recent chat messages - Leader-only permissions Note: Returns an error if the user is not currently in a party. No parameters required - automatically fetches the party for the authenticated user. |
| `HABITICA_GET_SHOPS_MARKET_GEAR` | Get Shops Market Gear | Tool to retrieve the available gear for purchase in the market shop. Use when you need to check what equipment is available for each character class. Returns gear organized by class: healer, wizard, rogue, and warrior. |
| `HABITICA_GET_SHOPS_TIME_TRAVELERS` | Get Time Travelers Shop | Tool to retrieve available items in the Time Travelers shop. Use when you need to see what quests, backgrounds, pets, or mounts can be purchased with hourglasses. |
| `HABITICA_GET_STATUS` | Get Habitica API Status | Tool to check Habitica API server status. Use when you need to verify if the Habitica service is operational before making other API calls. |
| `HABITICA_GET_TAGS` | Get Tags | Retrieve all tags for the authenticated Habitica user. Tags are labels that can be attached to tasks for organization. Returns both user-created tags and challenge-related tags. Use this to get tag IDs for filtering tasks or assigning tags to new tasks. |
| `HABITICA_GET_TASKS` | Get Tasks | Tool to retrieve all tasks for the authenticated user. Use when you need the user's current tasks list after authenticating. |
| `HABITICA_GET_USER_CHALLENGES` | Get User Challenges | Tool to retrieve challenges the authenticated user participates in. Use when you need a paginated list of user challenges. |
| `HABITICA_GET_USER_PROFILE` | Get User Profile | Retrieves the authenticated user's complete Habitica profile. Returns comprehensive user data including: - Stats: HP, MP, level, experience, gold, and character class - Inventory: gear, pets, mounts, eggs, potions, and quest items - Achievements: unlocked achievements and completed quests - Party: current party membership and quest progress - Preferences: language, timezone, notification settings - Tasks: order of habits, dailies, todos, and rewards - Tags: user-created tags for task organization This is a read-only endpoint that requires no parameters. The user is identified automatically via the API credentials. |
| `HABITICA_GET_WEBHOOKS` | Get Webhooks | Retrieves all webhooks configured for the authenticated Habitica user. Returns a list of webhooks including their URLs, types, enabled status, and task activity options. Use this to check existing webhook configurations, monitor webhook health via failure counts, or get webhook IDs for updates/deletions. |
| `HABITICA_GET_WORLD_STATE` | Get World State | Retrieves the current state of the Habitica game world including active events, world boss status, and seasonal NPC visual themes. Use when checking for active world events, monitoring world boss progress, or determining current seasonal themes. |
| `HABITICA_INVITE_TO_GROUP` | Invite To Group | Tool to invite users to a specific group. Use when you need to send invitations by user UUID, email, or username. |
| `HABITICA_INVITE_TO_QUEST` | Invite To Quest | Tool to invite party members to a quest. Use when you want to start a quest with a specific quest key in a group. The user must own the quest scroll to invite others. |
| `HABITICA_JOIN_CHALLENGE` | Join Challenge | Tool to join a challenge. Use after confirming the challenge ID to participate in a specific challenge. |
| `HABITICA_LEAVE_CHALLENGE` | Leave Challenge | Tool to leave a Habitica challenge. Use when you need to remove yourself from a specific challenge and decide whether to keep or remove its tasks. |
| `HABITICA_LOCAL_LOGIN` | Local Login | Tool to authenticate a user via local credentials. Use when needing an API token for subsequent Habitica requests. |
| `HABITICA_LOCAL_REGISTER` | Local User Registration | Tool to register a new Habitica user via email and password. Use when creating a fresh account before authentication. |
| `HABITICA_MARK_GROUP_CHAT_SEEN` | Mark Group Chat Seen | Tool to mark all chat messages as read/seen for a specific group. Use when you need to clear unread message notifications in a group chat. Requires a valid group ID ('party' for user's party, 'habitrpg' for Tavern). |
| `HABITICA_MARK_NOTIFICATION_SEEN` | Mark Notification Seen | Tool to mark a single notification as seen in Habitica. Use this when you need to mark one specific notification as read after the user has viewed it. |
| `HABITICA_MARK_NOTIFICATIONS_SEEN` | Mark Notifications Seen | Marks specific notifications as read/seen in Habitica. Use this after getting notifications to clear unread notification badges. Requires valid notification IDs from the Get Notifications action. Returns updated notification state. |
| `HABITICA_MOVE_PINNED_ITEM` | Move Pinned Item | Tool to move a pinned item in the rewards column to a new position. Use when you need to reorder pinned items after sorting them. |
| `HABITICA_MOVE_TASK_TO_POSITION` | Move Task To Position | Move a Habitica task to a new position in the task list. Use this when you need to reorder tasks by moving a specific task to the top (position=0), bottom (position=-1), or any specific position. The response returns the updated task order for the task type (habit, daily, todo, or reward) that the moved task belongs to. |
| `HABITICA_POST_NEWS_TELL_ME_LATER` | Dismiss Bailey Announcement | Tool to dismiss the latest Bailey announcement in Habitica, allowing it to be read later. Use this when the user wants to clear the current news notification without reading it. The announcement will reappear later. |
| `HABITICA_POST_USER_RESET` | Reset User Account | Resets the authenticated user's account to starting state. This permanently deletes all tasks, resets character to level 1, and clears progress while retaining some items and achievements. Use with caution as this action is irreversible. |
| `HABITICA_READ_CARD` | Read Card | Tool to mark a card as read in Habitica. Use when a user receives a special card (birthday, greeting, nye, thankyou, or valentine) and wants to acknowledge it. Updates user.flags.cardReceived and returns updated user.items.special. |
| `HABITICA_REMOVE_FROM_PARTY` | Remove Party Member | Removes a member from the authenticated user's party. Requirements: - You must be the party leader to remove members - You cannot remove yourself (use Leave Party instead) - The member must be currently in your party Use Get Party Members first to obtain member IDs. This action is typically used to remove inactive members or those who no longer wish to participate. |
| `HABITICA_SCORE_TASK` | Score Task | Score a Habitica task to mark it as completed or incomplete. Use this tool to: - Mark a todo as complete ('up') or incomplete ('down') - Check off a daily task ('up') or uncheck it ('down') - Record a positive habit action ('up') or negative habit action ('down') - Redeem a reward (use 'up' direction for rewards) Returns updated user stats including health, mana, experience, gold, and level. Scoring tasks can trigger drops (food, eggs, potions) and quest progress. |
| `HABITICA_SOCIAL_AUTH` | Social Auth | Tool to authenticate a user via a social provider. Use after obtaining an OAuth token or code from Facebook, Google, GitHub, or Apple. |
| `HABITICA_SUBSCRIBE_WEBHOOK` | Subscribe Webhook | Tool to enable (subscribe) an existing webhook by ID for the authenticated user. This aligns with Habitica's documented API by updating the webhook resource to ensure it is enabled. Usage: obtain the webhook ID (e.g., via Get Webhooks or after creating a webhook) and call this action to set enabled=true. |
| `HABITICA_UNLINK_ALL_CHALLENGE_TASKS` | Unlink All Challenge Tasks | Tool to unlink all tasks from a Habitica challenge. Use when you need to disconnect all tasks associated with a challenge and decide whether to keep or remove them. |
| `HABITICA_UPDATE_GROUP` | Update Group | Tool to update a Habitica group (party or guild) by modifying its properties. Use when you need to change the name, description, or summary of an existing group. Only the group leader can update group properties. |
| `HABITICA_UPDATE_TAG` | Update Tag | Tool to update an existing tag's name. Use when you need to rename a tag after identifying its ID. |
| `HABITICA_UPDATE_TASK` | Update Task | Update an existing task in Habitica. Use this to modify task properties like title, notes, priority, or other attributes. Only include fields you want to update - all body parameters are optional. |
| `HABITICA_UPDATE_TASK_CHECKLIST_ITEM` | Update Task Checklist Item | Tool to update a checklist item in a task. Use when you need to modify the text of a specific checklist item in a todo or daily task. |
| `HABITICA_UPDATE_USER` | Update User | Update the authenticated user's profile, preferences, flags, and other settings in Habitica. Use dot notation for nested fields (e.g., profile.name, preferences.language). Note: Some paths are protected and cannot be modified (e.g., stats.class will be rejected). |
| `HABITICA_VALIDATE_COUPON_CODE` | Validate Coupon Code | Validate a Habitica coupon code to check if it is valid and active. Use this tool to verify coupon codes before attempting to apply them to a user account. Returns information about the coupon's validity and type (e.g., subscription, gems). |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Habitica MCP server is an implementation of the Model Context Protocol that connects your AI agent to Habitica. It provides structured and secure access so your agent can perform Habitica operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Python 3.9 or higher
- A Composio account with an active API key
- Basic familiarity with Python and async programming

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install dependencies

Install the required libraries.
What's happening:
- composio connects your agent to external SaaS tools like Habitica
- pydantic-ai lets you create structured AI agents with tool support
- python-dotenv loads your environment variables securely from a .env file
```bash
pip install composio pydantic-ai python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your agent to Composio's API
- USER_ID associates your session with your account for secure tool access
- OPENAI_API_KEY to access OpenAI LLMs
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key
```

### 4. Import dependencies

What's happening:
- We load environment variables and import required modules
- Composio manages connections to Habitica
- MCPServerStreamableHTTP connects to the Habitica MCP server endpoint
- Agent from Pydantic AI lets you define and run the AI assistant
```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
```

### 5. Create a Tool Router Session

What's happening:
- We're creating a Tool Router session that gives your agent access to Habitica tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned session.mcp.url is the MCP server URL that your agent will use
```python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Habitica
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["habitica"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
```

### 6. Initialize the Pydantic AI Agent

What's happening:
- The MCP client connects to the Habitica endpoint
- The agent uses GPT-5 to interpret user commands and perform Habitica operations
- The instructions field defines the agent's role and behavior
```python
# Attach the MCP server to a Pydantic AI Agent
habitica_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[habitica_mcp],
    instructions=(
        "You are a Habitica assistant. Use Habitica tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
```

### 7. Build the chat interface

What's happening:
- The agent reads input from the terminal and streams its response
- Habitica API calls happen automatically under the hood
- The model keeps conversation history to maintain context across turns
```python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Habitica.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
```

### 8. Run the application

What's happening:
- The asyncio loop launches the agent and keeps it running until you exit
```python
if __name__ == "__main__":
    asyncio.run(main())
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Habitica
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["habitica"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    habitica_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[habitica_mcp],
        instructions=(
            "You are a Habitica assistant. Use Habitica tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Habitica.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())
```

## Conclusion

You've built a Pydantic AI agent that can interact with Habitica through Composio's Tool Router. With this setup, your agent can perform real Habitica actions through natural language.
You can extend this further by:
- Adding other toolkits like Gmail, HubSpot, or Salesforce
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Habitica for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

## How to build Habitica MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/habitica/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/habitica/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/habitica/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/habitica/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/habitica/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/habitica/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/habitica/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/habitica/framework/cli)
- [Google ADK](https://composio.dev/toolkits/habitica/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/habitica/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/habitica/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/habitica/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/habitica/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/habitica/framework/crew-ai)

## Related Toolkits

- [Google Sheets](https://composio.dev/toolkits/googlesheets) - Google Sheets is a cloud-based spreadsheet tool for real-time collaboration and data analysis. It lets teams work together from anywhere, updating information instantly.
- [Notion](https://composio.dev/toolkits/notion) - Notion is a collaborative workspace for notes, docs, wikis, and tasks. It streamlines team knowledge, project tracking, and workflow customization in one place.
- [Airtable](https://composio.dev/toolkits/airtable) - Airtable combines the flexibility of spreadsheets with the power of a database for easy project and data management. Teams use Airtable to organize, track, and collaborate with custom views and automations.
- [Asana](https://composio.dev/toolkits/asana) - Asana is a collaborative work management platform for teams to organize and track projects. It streamlines teamwork, boosts productivity, and keeps everyone aligned on goals.
- [Google Tasks](https://composio.dev/toolkits/googletasks) - Google Tasks is a to-do list and task management tool integrated into Gmail and Google Calendar. It helps you organize, track, and complete tasks across your Google ecosystem.
- [Linear](https://composio.dev/toolkits/linear) - Linear is a modern issue tracking and project planning tool for fast-moving teams. It helps streamline workflows, organize projects, and boost productivity.
- [Jira](https://composio.dev/toolkits/jira) - Jira is Atlassian’s platform for bug tracking, issue tracking, and agile project management. It helps teams organize work, prioritize tasks, and deliver projects efficiently.
- [Clickup](https://composio.dev/toolkits/clickup) - ClickUp is an all-in-one productivity platform for managing tasks, docs, goals, and team collaboration. It streamlines project workflows so teams can work smarter and stay organized in one place.
- [Monday](https://composio.dev/toolkits/monday) - Monday.com is a customizable work management platform for project planning and collaboration. It helps teams organize tasks, automate workflows, and track progress in real time.
- [Addressfinder](https://composio.dev/toolkits/addressfinder) - Addressfinder is a data quality platform for verifying addresses, emails, and phone numbers. It helps you ensure accurate customer and contact data every time.
- [Agiled](https://composio.dev/toolkits/agiled) - Agiled is an all-in-one business management platform for CRM, projects, and finance. It helps you streamline workflows, consolidate client data, and manage business processes in one place.
- [Ascora](https://composio.dev/toolkits/ascora) - Ascora is a cloud-based field service management platform for service businesses. It streamlines scheduling, invoicing, and customer operations in one place.
- [Basecamp](https://composio.dev/toolkits/basecamp) - Basecamp is a project management and team collaboration tool by 37signals. It helps teams organize tasks, share files, and communicate efficiently in one place.
- [Beeminder](https://composio.dev/toolkits/beeminder) - Beeminder is an online goal-tracking platform that uses monetary pledges to keep you motivated. Stay accountable and hit your targets with real financial incentives.
- [Boxhero](https://composio.dev/toolkits/boxhero) - Boxhero is a cloud-based inventory management platform for SMBs, offering real-time updates, barcode scanning, and team collaboration. It helps businesses streamline stock tracking and analytics for smarter inventory decisions.
- [Breathe HR](https://composio.dev/toolkits/breathehr) - Breathe HR is cloud-based HR software for SMEs to manage employee data, absences, and performance. It simplifies HR admin, making it easy to keep employee records accurate and up to date.
- [Breeze](https://composio.dev/toolkits/breeze) - Breeze is a project management platform designed to help teams plan, track, and collaborate on projects. It streamlines workflows and keeps everyone on the same page.
- [Bugherd](https://composio.dev/toolkits/bugherd) - Bugherd is a visual feedback and bug tracking tool for websites. It helps teams and clients report website issues directly on live sites for faster fixes.
- [Canny](https://composio.dev/toolkits/canny) - Canny is a platform for managing customer feedback and feature requests. It helps teams prioritize product decisions based on real user insights.
- [Chmeetings](https://composio.dev/toolkits/chmeetings) - Chmeetings is a church management platform for events, members, donations, and volunteers. It streamlines church operations and improves community engagement.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Habitica MCP?

With a standalone Habitica MCP server, the agents and LLMs can only access a fixed set of Habitica tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Habitica and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with Pydantic AI?

Yes, you can. Pydantic AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Habitica tools.

### Can I manage the permissions and scopes for Habitica while using Tool Router?

Yes, absolutely. You can configure which Habitica scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Habitica data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
