# How to integrate Notion MCP with OpenAI Agents SDK

```json
{
  "title": "How to integrate Notion MCP with OpenAI Agents SDK",
  "toolkit": "Notion",
  "toolkit_slug": "notion",
  "framework": "OpenAI Agents SDK",
  "framework_slug": "open-ai-agents-sdk",
  "url": "https://composio.dev/toolkits/notion/framework/open-ai-agents-sdk",
  "markdown_url": "https://composio.dev/toolkits/notion/framework/open-ai-agents-sdk.md",
  "updated_at": "2026-05-06T08:21:42.664Z"
}
```

## Introduction

This guide walks you through connecting Notion to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Notion agent that can add meeting notes to project wiki page, create a new task database for q3, archive completed sprint summary pages through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Notion account through Composio's Notion MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Notion with

- [ChatGPT](https://composio.dev/toolkits/notion/framework/chatgpt)
- [Claude Agent SDK](https://composio.dev/toolkits/notion/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/notion/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/notion/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/notion/framework/codex)
- [Cursor](https://composio.dev/toolkits/notion/framework/cursor)
- [VS Code](https://composio.dev/toolkits/notion/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/notion/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/notion/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/notion/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/notion/framework/cli)
- [Google ADK](https://composio.dev/toolkits/notion/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/notion/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/notion/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/notion/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/notion/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/notion/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Notion
- Configure an AI agent that can use Notion as a tool
- Run a live chat session where you can ask the agent to perform Notion operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

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

The Notion MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Notion account. It provides structured and secure access to your notes, docs, wikis, and tasks, so your agent can perform actions like creating pages, managing databases, adding content, commenting, and organizing your Notion workspace for you.
- Bulk content creation and formatting: Let your agent efficiently add and format multiple blocks of text, lists, or markdown content to Notion pages in one go.
- Automated page and database management: Have your agent create new pages, duplicate existing ones, or set up entire databases with custom properties—no manual setup required.
- Smart commenting and collaboration: Enable your agent to add comments to pages or discussion threads, making real-time collaboration smoother.
- Workspace organization and cleanup: Ask your agent to archive, delete, or restore pages and blocks, keeping your workspace tidy and up to date.
- Deep block and structure retrieval: Direct your agent to fetch metadata, list child blocks, or dig into nested content for analysis, reporting, or workflow automation.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `NOTION_ADD_MULTIPLE_PAGE_CONTENT` | Add multiple content blocks (bulk, user-friendly) | Efficiently adds multiple standard content blocks to a notion page in a single api call with automatic markdown parsing. the 'content' field in notionrichtext blocks now automatically detects and parses markdown formatting including headers (# ## ###), bold (**text**), italic (*text*), strikethrough (~~text~~), inline code (`code`), links ([text](url)), and more. ideal for bulk content creation, ai agents, and replacing multiple individual add page content calls. supports automatic text formatting, content splitting, and up to 100 blocks per request. |
| `NOTION_APPEND_BLOCK_CHILDREN` | Append complex blocks (advanced, full control) | Appends complex blocks with full notion block structure to a parent block or page. use for advanced scenarios requiring precise control: code blocks, tables, embeds, nested children within blocks, or when working with pre-built notion block objects. requires full notion api block schema - use add multiple page content for simpler content creation. |
| `NOTION_ARCHIVE_NOTION_PAGE` | Archive Notion Page | Archives (moves to trash) or unarchives (restores from trash) a specified notion page. |
| `NOTION_CREATE_COMMENT` | Create comment | Adds a comment to a notion page (via `parent page id`) or to an existing discussion thread (via `discussion id`); cannot create new discussion threads on specific blocks (inline comments). |
| `NOTION_CREATE_DATABASE` | Create Notion Database | Creates a new notion database as a subpage under a specified parent page with a defined properties schema; use this action exclusively for creating new databases. |
| `NOTION_CREATE_NOTION_PAGE` | Create Notion page | Creates a new empty page in a notion workspace. |
| `NOTION_DELETE_BLOCK` | Delete a block | Archives a notion block, page, or database using its id, which sets its 'archived' property to true (like moving to "trash" in the ui) and allows it to be restored later. |
| `NOTION_DUPLICATE_PAGE` | Duplicate page | Duplicates a notion page, including all its content, properties, and nested blocks, under a specified parent page or workspace. |
| `NOTION_FETCH_BLOCK_CONTENTS` | Fetch Notion Block Children | Retrieves a paginated list of direct, first-level child block objects along with contents for a given parent notion block or page id; use block ids from the response for subsequent calls to access deeply nested content. |
| `NOTION_FETCH_BLOCK_METADATA` | Fetch Notion block metadata | Fetches metadata for a notion block (or page, as pages are blocks) using its valid uuid; if the block has children, use fetch block contents to fetch their contents. |
| `NOTION_FETCH_COMMENTS` | Fetch comments | Fetches unresolved comments for a specified notion block or page id. |
| `NOTION_FETCH_DATA` | Fetch Notion Data | Fetches notion items (pages and/or databases) from the notion workspace, use this to get minimal data about the items in the workspace with a query or list all items in the workspace with minimal data |
| `NOTION_FETCH_DATABASE` | Fetch Database | Fetches a notion database's structural metadata (properties, title, etc.) via its `database id`, not the data entries; `database id` must reference an existing database. |
| `NOTION_FETCH_ROW` | Fetch database row | Retrieves a notion database row's properties and metadata; use fetch block contents for page content blocks. |
| `NOTION_GET_ABOUT_ME` | Get About Me | Retrieves the user object for the bot associated with the current notion integration token, typically to obtain the bot's user id for other api operations. |
| `NOTION_GET_ABOUT_USER` | Get about user | Retrieves detailed information about a specific notion user, such as their name, avatar, and email, based on their unique user id. |
| `NOTION_GET_PAGE_PROPERTY_ACTION` | Get page property | Call this to get a specific property from a notion page when you have a valid `page id` and `property id`; handles pagination for properties returning multiple items. |
| `NOTION_INSERT_ROW_DATABASE` | Insert row database | Creates a new page (row) in a specified notion database. |
| `NOTION_LIST_USERS` | List users | Retrieves a paginated list of users (excluding guests) from the notion workspace; the number of users returned per page may be less than the requested `page size`. |
| `NOTION_QUERY_DATABASE` | Query database | Queries a notion database for pages (rows), where rows are pages and columns are properties; ensure sort property names correspond to existing database properties. |
| `NOTION_RETRIEVE_COMMENT` | Retrieve Comment | Tool to retrieve a specific comment by its id. use when you have a comment id and need to fetch its details. |
| `NOTION_RETRIEVE_DATABASE_PROPERTY` | Retrieve Database Property | Tool to retrieve a specific property object of a notion database. use when you need to get details about a single database column/property. |
| `NOTION_SEARCH_NOTION_PAGE` | Search Notion page | Searches notion pages and databases by title; an empty query lists all accessible items, useful for discovering ids or as a fallback when a specific query yields no results. |
| `NOTION_UPDATE_BLOCK` | Update block | Updates an existing notion block's textual content or type-specific properties (e.g., 'checked' status, 'color'), using its `block id` and the specified `block type`. |
| `NOTION_UPDATE_PAGE` | Update Page | Tool to update the properties, icon, cover, or archive status of a page. use when you need to modify existing page attributes. |
| `NOTION_UPDATE_ROW_DATABASE` | Update row database | Updates or archives an existing notion database row (page) using its `row id`, allowing modification of its icon, cover, and/or properties; ensure the target page is accessible and property details (names/ids and values) align with the database schema and specified formats. |
| `NOTION_UPDATE_SCHEMA_DATABASE` | Update database schema | Updates an existing notion database's title, description, and/or properties; at least one of these attributes must be provided to effect a change. |

## Supported Triggers

| Trigger slug | Name | Description |
|---|---|---|
| `NOTION_ALL_PAGE_EVENTS_TRIGGER` | All Page Events | Triggers when any Notion page is created or updated across the workspace. |
| `NOTION_COMMENT_CREATED` | Comment Created | Triggers when a new comment is created in Notion. Optional `page_id` filter scopes to comments on a specific page. When omitted, fires for any new comment in the workspace the integration has access to. Requires the 'Read comments' capability on the Notion integration. If a connection was authorized before that capability was enabled, the user must re-authorize the connection for comment events to flow. |
| `NOTION_COMMENTS_ADDED_TRIGGER` | New Comment | Triggers when a new comment is added to a specified Notion block or page. |
| `NOTION_DATABASE_CREATED` | Database Created | Triggers when a new Notion database (the container) is created. A database is the post-2025-09-03 container that holds one or more data sources. This trigger fires for the container's creation event (`database.created`), distinct from `NOTION_DATASOURCE_CREATED` which fires when a new data source is added to an existing database. Most customers calling Notion's `POST /v1/databases` (the legacy API) or creating a database via the Notion UI will see this event. Adding a new data source to an existing database fires `data_source.created` instead — use `NOTION_DATASOURCE_CREATED` for that. Notion's payload puts `entity.type: "block"` (the container is a `child_database` block in the content tree) and `entity.id` is the database id. |
| `NOTION_DATASOURCE_CREATED` | Data Source Created | Triggers when a new Notion data source is created. Fires workspace-wide. The payload's `data.parent` carries the data source's tree parent (typically the teamspace) for downstream filtering. A single template-based database creation can fire multiple `data_source.created` events at once — one per data source the template instantiates. |
| `NOTION_DATASOURCE_SCHEMA_UPDATED` | Data Source Schema Updated | Triggers when a Notion data source's schema is updated. Fires on column add / remove / rename. Payload includes `data.updated_properties: [{id, name, action}]` so consumers can discriminate the kind of change downstream. Optional `data_source_id` filter scopes to schema changes on a single data source. When omitted, fires for any schema change in the workspace the integration has access to. Note: adding a column also fires `page.properties_updated` once per existing row in the data source. Customers wanting a single structural-change signal should use this trigger. |
| `NOTION_PAGE_ADDED_TO_DATABASE` | New Page | Triggers when a new page is added to a Notion database. |
| `NOTION_PAGE_ADDED_TRIGGER` | Page Added to Page | Fires when a new subpage (a `child_page` type block) is added under a specified parent Notion page. |
| `NOTION_PAGE_CONTENT_UPDATED` | Page Content Updated | Triggers when the body content of a Notion page is updated. Customer optionally scopes with at most one of: - data_source_id: any row in this data source - page_id: this specific page - parent_page_id: any page whose immediate parent is this page With none set, fires for any page content edit in the workspace the integration has access to. Notion aggregates content edits within a short window (~60s typical). |
| `NOTION_PAGE_CREATED` | Page Created | Triggers when a new Notion page is created. Customer optionally scopes with at most one of: - data_source_id: new row in this data source - parent_page_id: new sub-page under this page (immediate parent only) With neither set, fires for any new page in the workspace the integration has access to. Notion sends ~60s aggregation latency on most events. |
| `NOTION_PAGE_PROPERTIES_UPDATED` | Page Properties Updated | Triggers when properties of a Notion page are updated. Customer optionally scopes with at most one of: - data_source_id: any row in this data source - page_id: this specific page - parent_page_id: any page whose immediate parent is this page With none set, fires for any property change in the workspace the integration has access to. Adding a column to a data source fires this trigger once per existing row. Customers can branch on `data.updated_properties` (array of property IDs) to filter downstream. |
| `NOTION_PAGE_UPDATED_TRIGGER` | Page Updated | Triggers when any block within a specified Notion page is updated. |
| `NOTION_VIEW_CREATED` | View Created | Triggers when a new Notion view is created. Fires workspace-wide. The payload includes `data.view_type` (`table`, `board`, `gallery`, `calendar`, `list`, `timeline`, `gantt`) and `data.parent` pointing at the view's tree parent (typically the teamspace), so customers can filter downstream. |

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

The Notion MCP server is an implementation of the Model Context Protocol that connects your AI agent to Notion. It provides structured and secure access so your agent can perform Notion 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:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Notion project
- Some knowledge of Python or Typescript

### 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).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Notion.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only notion.
- The router checks the user's Notion connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Notion.
- This approach keeps things lightweight and lets the agent request Notion tools only when needed during the conversation.
```python
# Create a Notion Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["notion"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Notion
const session = await composio.create(userId as string, {
  toolkits: ['notion'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Notion. "
        "Help users perform Notion operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Notion. Help users perform Notion operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["notion"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Notion. "
        "Help users perform Notion operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['notion'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Notion. Help users perform Notion operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Notion MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Notion.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Notion MCP Agent with another framework

- [ChatGPT](https://composio.dev/toolkits/notion/framework/chatgpt)
- [Claude Agent SDK](https://composio.dev/toolkits/notion/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/notion/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/notion/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/notion/framework/codex)
- [Cursor](https://composio.dev/toolkits/notion/framework/cursor)
- [VS Code](https://composio.dev/toolkits/notion/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/notion/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/notion/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/notion/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/notion/framework/cli)
- [Google ADK](https://composio.dev/toolkits/notion/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/notion/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/notion/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/notion/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/notion/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/notion/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.
- [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.
- [ClickSend](https://composio.dev/toolkits/clicksend) - ClickSend is a cloud-based SMS and email marketing platform for businesses. It streamlines communication by enabling quick message delivery and contact management.

## Frequently Asked Questions

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

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

### Can I use Tool Router MCP with OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK 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 Notion tools.

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

Yes, absolutely. You can configure which Notion 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 Notion data and credentials are handled as safely as possible.

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