• unwind ai
  • Posts
  • Build a Terminal-Based Notion Agent with MCP

Build a Terminal-Based Notion Agent with MCP

Fully functional CLI MCP agent with step-by-step instructions (100% opensource)

Picture this: you're deep in a coding session when you need to update your project documentation in Notion. Instead of context-switching to a browser, navigating through pages, and manually editing content, you simply type "Add deployment notes to the API docs" in your terminal. The magic happens instantly—your Notion page updates without you ever leaving your development environment.

In this tutorial, we'll build a terminal-based Notion agent using the Model Context Protocol (MCP) and Agno framework. This agent will allow you to interact with your Notion pages through natural language commands directly from your terminal, enabling operations like content updates, searches, block creation, and comment addition.

Using MCP here eliminates the complexity of building custom Notion API integrations from scratch. Instead of writing dozens of lines of authentication code, request handlers, and error management, MCP provides a pre-built Notion server that handles all the API intricacies.

Don’t forget to share this tutorial on your social channels and tag Unwind AI (X, LinkedIn, Threads, Facebook) to support us!

What We’re Building

This application implements a terminal-based agent that provides direct access to your Notion workspace from simple prompts. The agent uses MCP to securely connect to Notion's API and perform various operations on your pages.

Features:

  • Terminal-based interface for Notion page interactions

  • Full CRUD operations (Create, Read, Update, Delete) on Notion content from simple prompts

  • Block-level operations including text, lists, tables, and comments

  • Intelligent search capabilities across your Notion pages

  • Session management with conversation memory

  • Multi-turn conversations with context retention

  • Secure authentication through Notion Integration tokens

Prerequisites

Before we begin, make sure you have the following:

  1. Python installed on your machine (version 3.10 or higher is recommended)

  2. A Notion account with admin permissions

  3. A Notion Integration token

  4. An OpenAI API key

  5. A code editor of your choice (we recommend VS Code or PyCharm for their excellent Python support)

  6. Basic familiarity with Python programming

Setting Up Notion Integration

Creating a Notion Integration

  1. Go to Notion Integrations

  2. Click "New integration"

  3. Name your integration (e.g., "Notion Assistant")

  4. Select the capabilities needed (Read & Write content)

  5. Submit and copy your "Internal Integration Token"

Sharing Your Notion Page with the Integration

  1. Open your Notion page

  2. Click the three dots (⋮) in the top-right corner of the page

  3. Select "Add connections" from the dropdown menu

  4. Search for your integration name in the search box

  5. Click on your integration to add it to the page

  6. Confirm by clicking "Confirm" in the dialog that appears

Alternatively, you can also share via the "Share" button:

  1. Click "Share" in the top right

  2. In the sharing dialog, search for your integration name (preceded by "@")

  3. Click on your integration to add it

  4. Click "Invite" to grant it access to your page

Both methods will grant your integration full access to the page and its content.

Finding Your Notion Page ID

  1. Open your Notion page in a browser

  2. Copy the URL, which looks like: https://www.notion.so/workspace/Your-Page-1f5b8a8ba283...

  3. The ID is the part after the last dash and before any query parameters Example: 1f5b8a8bad058a7e39a6

Code Walkthrough

Setting Up the Environment

First, let's get our development environment ready:

  1. Clone the GitHub repository:

git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
  1. Go to the notion_mcp_agent folder:

cd mcp_ai_agents/notion_mcp_agent
pip install -r requirements.txt
  1. You can configure the agent using environment variables:

    • NOTION_API_KEY: Your Notion Integration token

    • OPENAI_API_KEY: Your OpenAI API key

    • NOTION_PAGE_ID: The ID of your Notion page

    Alternatively, you can set these values directly in the script.

Creating the Streamlit App

Let’s create our app. Create a new file notion_mcp_agent.py and add the following code:

  1. Import necessary libraries:
    • Agno framework for agent creation
    • MCP tools for Notion integration
    • OpenAI for LLM

import asyncio
import json
import os
import sys
import uuid
from textwrap import dedent
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.mcp import MCPTools
from agno.memory.v2 import Memory
from mcp import StdioServerParameters
from dotenv import load_dotenv
  1. Environment Configuration:

load_dotenv()
NOTION_TOKEN = os.getenv("NOTION_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
  1. Create the main async function and display banner:

async def main():
    print("\n========================================")
    print("      Notion MCP Terminal Agent")
    print("========================================\n")
    
    # Get configuration from environment or use defaults
    notion_token = NOTION_TOKEN
    openai_api_key = OPENAI_API_KEY
  1. Handle Notion page ID input:

if len(sys.argv) > 1:
    # Use command-line argument if provided
    page_id = sys.argv[1]
    print(f"Using provided page ID from command line: {page_id}")
else:
    # Ask the user for the page ID
    print("Please enter your Notion page ID:")
    print("(You can find this in your page URL, e.g., https://www.notion.so/workspace/Your-Page-1f5b8a8ba283...)")
    print("The ID is the part after the last dash and before any query parameters")
    
    user_input = input("> ")
    
    # If user input is empty, use default
    if user_input.strip():
        page_id = user_input.strip()
        print(f"Using provided page ID: {page_id}")
    else:
        print(f"Using default page ID: {page_id}")
  1. Generate unique session identifiers:

# Generate unique user and session IDs for this terminal session
user_id = f"user_{uuid.uuid4().hex[:8]}"
session_id = f"session_{uuid.uuid4().hex[:8]}"
print(f"User ID: {user_id}")
print(f"Session ID: {session_id}")

print("\nConnecting to Notion MCP server...\n")
  1. Configure the MCP server parameters:

# Configure the MCP Tools
server_params = StdioServerParameters(
    command="npx",
    args=["-y", "@notionhq/notion-mcp-server"],
    env={
        "OPENAPI_MCP_HEADERS": json.dumps(
            {"Authorization": f"Bearer {notion_token}", "Notion-Version": "2022-06-28"}
        )
    }
)
  1. Initialize MCP tools and create the agent:

# Start the MCP Tools session
async with MCPTools(server_params=server_params) as mcp_tools:
    print("Connected to Notion MCP server successfully!")
    
    # Create the agent
    agent = Agent(
        name="NotionDocsAgent",
        model=OpenAIChat(id="gpt-4o", api_key=openai_api_key),
        tools=[mcp_tools],
        description="Agent to query and modify Notion docs via MCP",
  1. Configure agent instructions and memory settings:

instructions=dedent(f"""
    You are an expert Notion assistant that helps users interact with their Notion pages.
    
    IMPORTANT INSTRUCTIONS:
    1. You have direct access to Notion documents through MCP tools - make full use of them.
    2. ALWAYS use the page ID: {page_id} for all operations unless the user explicitly provides another ID.
    3. When asked to update, read, or search pages, ALWAYS use the appropriate MCP tool calls.
    4. Be proactive in suggesting actions users can take with their Notion documents.
    5. When making changes, explain what you did and confirm the changes were made.
    6. If a tool call fails, explain the issue and suggest alternatives.

Example tasks you can help with:
    - Reading page content
    - Searching for specific information
    - Adding new content or updating existing content
    - Creating lists, tables, and other Notion blocks
    - Explaining page structure
    - Adding comments to specific blocks
    
    The user's current page ID is: {page_id}
"""),
markdown=True,
show_tool_calls=True,
retries=3,
memory=Memory(),  # Use Memory v2 for better multi-session support
add_history_to_messages=True,  # Include conversation history
num_history_runs=5,  # Keep track of the last 5 interactions
  1. Start the interactive CLI session:

print("\n\nNotion MCP Agent is ready! Start chatting with your Notion pages.\n")
print("Type 'exit' or 'quit' to end the conversation.\n")

# Start interactive CLI session with memory and proper session management
await agent.acli_app(
    user_id=user_id,
    session_id=session_id,
    user="You",
    emoji="🤖",
    stream=True,
    markdown=True,
    exit_on=["exit", "quit", "bye", "goodbye"]
)
  1. Add the main execution block:

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

Running the App

With our code in place, it's time to launch the app.

  • Run the agent from the command line:

python notion_mcp_agent.py
  • When you start the agent, it will prompt you to enter your Notion page ID. You can:

    1. Enter your page ID at the prompt

    2. Press Enter without typing anything to use the default page ID (if set)

    3. Provide the page ID directly as a command-line argument (bypassing the prompt):

      python notion_mcp_agent.py your-page-id-here

  • Conversation Flow

    Each time you start the agent, it creates a unique user ID and session ID to maintain conversation context. This allows the agent to remember previous interactions and continue coherent conversations even after you close and restart the application.

    You can exit the conversation at any time by typing exit, quit, bye, or goodbye.

Example Queries

  • "What's on my Notion page?"

  • "Add a new paragraph saying 'Meeting notes for today'"

  • "Create a bullet list with three items: Apple, Banana, Orange"

  • "Add a comment to the first paragraph saying 'This looks good!'"

  • "Search for any mentions of meetings"

  • "Summarize our conversation so far"

Working Application Demo

Conclusion

You've just built a Notion MCP agent that lets you control your documentation without ever leaving your development environment. No more browser tab switching, no more clicking through Notion's interface. Just type what you want and watch it happen.

We share hands-on tutorials like this 2-3 times a week, to help you stay ahead in the world of AI. If you're serious about leveling up your AI skills and staying ahead of the curve, subscribe now and be the first to access our latest tutorials.

Don’t forget to share this tutorial on your social channels and tag Unwind AI (X, LinkedIn, Threads, Facebook) to support us!

Reply

or to participate.