A comprehensive Model Context Protocol (MCP) server for Notion integration with enhanced functionality, robust error handling, production-ready features, and bulletproof validation. - โ Search: Find pages and databases with advanced filtering - โ Page Operations: Create, read, update pages with full content support - โ Content Management: Add paragraphs, headings, bullet points, todos, links, and
Add this skill
npx mdskills install ankitmalik84/agentic-longterm-memoryComprehensive MCP server with extensive Notion integration, analytics, and production-ready features
1# Notion MCP Server V2 ๐23A comprehensive **Model Context Protocol (MCP) server** for Notion integration with enhanced functionality, robust error handling, production-ready features, and **bulletproof validation**.45## โจ Features67### ๐ง **Core Operations**89- โ **Search**: Find pages and databases with advanced filtering10- โ **Page Operations**: Create, read, update pages with full content support11- โ **Content Management**: Add paragraphs, headings, bullet points, todos, **links, and bookmarks**12- โ **Database Operations**: List and query databases1314### ๐ **Advanced Content Types** _(NEW)_1516- โ **Bookmarks**: Add external website links with URL validation17- โ **Link to Page**: Create internal links between Notion pages18- โ **Rich Content**: Support for all major Notion block types19- โ **Content Splitting**: Automatic handling of long content (2000+ chars)2021### ๐ **Analytics & Insights**2223- โ **Workspace Analytics**: Total pages, databases, recent activity24- โ **Content Analytics**: Structure analysis and metrics25- โ **Activity Tracking**: Recent edits and usage patterns26- โ **Performance Metrics**: Optimized with configurable timeouts2728### ๐ **Bulk Operations** _(OPTIMIZED)_2930- โ **Smart Pagination**: Prevents timeouts with configurable limits31- โ **Bulk Content Addition**: Add multiple content blocks at once32- โ **Bulk Page Operations**: Create and manage multiple pages33- โ **Performance Controls**: Optional block counts for faster responses3435### ๐ **API Interfaces**3637- โ **FastAPI REST API**: Production-ready HTTP endpoints38- โ **Interactive CLI**: Command-line interface for direct usage39- โ **MCP Compatible**: Full Model Context Protocol support40- โ **Agent Integration**: Unified endpoint for AI agents4142### ๐ก๏ธ **Production Features** _(ENHANCED)_4344- โ **Bulletproof Validation**: Comprehensive input validation and error handling45- โ **Configuration Management**: Environment-based settings46- โ **Smart Error Recovery**: Detailed error messages and recovery guidance47- โ **Health Checks**: Monitoring and status endpoints with feature detection48- โ **Structured Logging**: Configurable logging with performance insights49- โ **CORS Support**: Cross-origin resource sharing50- โ **Timeout Optimization**: Dynamic timeouts based on operation complexity5152### ๐งช **Testing & Quality** _(COMPREHENSIVE)_5354- โ **46KB Test Suite**: 1,158 lines of comprehensive tests55- โ **13+ Test Categories**: Core, content, bulk, links, analytics, edge cases56- โ **Validation Testing**: Tests for all error scenarios and edge cases57- โ **Performance Testing**: Timeout and optimization validation58- โ **Detailed Reporting**: JSON reports with timing and categorization5960## ๐๏ธ Architecture6162```63notion_mcp_server/64โโโ ๐ __init__.py # Package initialization65โโโ ๐ง config.py # Configuration management66โโโ ๐ api_serverV2.py # FastAPI REST API server (49KB)67โโโ ๐ป serverV2.py # Interactive CLI server68โโโ โ๏ธ core_operations.py # Basic CRUD operations69โโโ ๐ analytics_operations.py # Analytics and metrics70โโโ ๐ bulk_operations.py # Bulk processing71โโโ โ๏ธ update_operations.py # Content updates (35KB)72โโโ ๐ ๏ธ notion_utils.py # Utility functions73โโโ ๐งช test_server.py # Comprehensive test suite (48KB)74โโโ ๐ README.md # This file75```7677## ๐ฆ Installation7879### Prerequisites8081- Python 3.8+82- Notion account with integration token83- pip or conda package manager8485### Setup86871. **Install Dependencies**8889```bash90pip install notion-client fastapi uvicorn python-dotenv pydantic requests91```92932. **Environment Configuration**94 Create a `.env` file in your project root:9596```env97# Required98NOTION_TOKEN=ntn_your_integration_token_here99100# Optional Server Settings101HOST=0.0.0.0102PORT=8081103DEBUG=false104105# Optional Feature Settings106MAX_PAGE_SIZE=100107DEFAULT_PAGE_SIZE=20108MAX_CONTENT_LENGTH=2000109ENABLE_ANALYTICS=true110ENABLE_BULK_OPERATIONS=true111112# Optional Logging113LOG_LEVEL=INFO114```1151163. **Get Your Notion Token**117118- Go to [Notion Integrations](https://www.notion.so/profile/integrations)119- Create a new integration120- Copy the token (starts with `ntn_`)121- Share your pages/databases with the integration122123## ๐ Usage124125### 1. FastAPI Server (Production)126127**Start the server:**128129```bash130python -m notion_mcp_server.api_serverV2131```132133**Server will be available at:**134135- API: `http://localhost:8081`136- Documentation: `http://localhost:8081/docs`137- Health Check: `http://localhost:8081/health`138139### 2. Interactive CLI140141```bash142python -m notion_mcp_server.serverV2143```144145### 3. Python Integration146147```python148from notion_mcp_server import ComprehensiveNotionServer149import asyncio150151async def example():152 server = ComprehensiveNotionServer("your_notion_token")153 await server.core_ops.search_content("search term")154155asyncio.run(example())156```157158## ๐ API Documentation159160### ๐ **Search Endpoint**161162```http163POST /api/search164Content-Type: application/json165166{167 "query": "search term",168 "page_size": 10169}170```171172### ๐ **Create Page**173174```http175POST /api/page/create176Content-Type: application/json177178{179 "title": "My New Page",180 "content": "Initial content",181 "parent_id": "optional-parent-page-id"182}183```184185### ๐ **Read Page**186187```http188POST /api/page/read189Content-Type: application/json190191{192 "identifier": "page-id-or-title"193}194```195196### โ๏ธ **Add Content** _(ENHANCED)_197198```http199POST /api/page/add-content200Content-Type: application/json201202{203 "page_id": "page-id",204 "content_type": "paragraph",205 "content": "New paragraph content"206}207```208209**Supported content types:**210211- `paragraph` - Regular text212- `heading_1` - Large heading213- `heading_2` - Medium heading214- `heading_3` - Small heading215- `bulleted_list_item` - Bullet point216- `to_do` - Checkbox item217- `bookmark` - External website link _(NEW)_218- `link_to_page` - Internal page link _(NEW)_219220### ๐ **Link Content Types** _(NEW)_221222**Add Bookmark (External Link):**223224```http225POST /api/page/add-content226Content-Type: application/json227228{229 "page_id": "page-id",230 "content_type": "bookmark",231 "content": "OpenAI Website",232 "url": "https://www.openai.com"233}234```235236**Add Link to Page (Internal Link):**237238```http239POST /api/page/add-content240Content-Type: application/json241242{243 "page_id": "page-id",244 "content_type": "link_to_page",245 "content": "Link to related page",246 "page_reference": "target-page-id-or-title"247}248```249250### ๐ **Bulk Content Addition** _(ENHANCED)_251252```http253POST /api/page/bulk-add-content254Content-Type: application/json255256{257 "page_id": "page-id",258 "items": [259 {260 "content_type": "heading_2",261 "content": "Section Title"262 },263 {264 "content_type": "paragraph",265 "content": "Paragraph content"266 },267 {268 "content_type": "bookmark",269 "url": "https://example.com",270 "content": "External Link"271 },272 {273 "content_type": "link_to_page",274 "page_reference": "other-page-id",275 "content": "Internal Link"276 },277 {278 "content_type": "to_do",279 "content": "Task item",280 "checked": false281 }282 ]283}284```285286### ๐ **Analytics**287288```http289POST /api/analytics290Content-Type: application/json291292{293 "type": "workspace"294}295```296297**Analytics types:** `workspace`, `content`, `activity`, `database`298299### ๐ **Bulk Operations** _(OPTIMIZED)_300301```http302POST /api/bulk303Content-Type: application/json304305{306 "operation": "list",307 "query": "{\"limit\": 10, \"include_block_counts\": false}"308}309```310311**Optimization options:**312313- `limit`: Number of pages to process (1-50)314- `include_block_counts`: Whether to calculate block counts (slower)315316**Operations:** `list`, `analyze`, `create`317318### ๐ค **Agent Integration**319320```http321POST /api/agent/query322Content-Type: application/json323324{325 "action": "search",326 "parameters": {327 "query": "search term",328 "page_size": 10329 }330}331```332333**Available actions:** `search`, `read_page`, `create_page`, `add_content`, `bulk_add_content`, `analytics`, `bulk_operations`334335## ๐งช Testing _(COMPREHENSIVE)_336337Run the comprehensive test suite:338339```bash340# Start the server first341python -m notion_mcp_server.api_serverV2342343# In another terminal, run tests344cd src/notion_mcp_server345python test_server.py346```347348**Test Coverage (1,158 lines, 13+ categories):**349350- โ **Core Operations**: Health checks, search, page creation/reading351- โ **Content Addition**: All content types including links and bookmarks352- โ **Bulk Content**: Multiple content blocks and optimization353- โ **Link Functionality**: Bookmark and link_to_page validation354- โ **Analytics**: All analytics types and performance355- โ **Bulk Operations**: Optimized pagination and limits356- โ **Agent Integration**: All agent query actions357- โ **Edge Cases**: Error handling, validation, timeouts358- โ **Exception Handling**: Network issues, invalid inputs359360**Test Features:**361362- ๐ฏ **Detailed Reporting**: Success rates, timing, categorization363- ๐ **Performance Insights**: Response times and bottlenecks364- ๐ **JSON Reports**: Exportable test results with timestamps365- ๐งน **Cleanup Scripts**: Automatic test data management366367## โ๏ธ Configuration368369### Environment Variables370371| Variable | Default | Description |372| ------------------------ | ------------ | ----------------------------- |373| `NOTION_TOKEN` | _(required)_ | Your Notion integration token |374| `HOST` | `0.0.0.0` | Server host address |375| `PORT` | `8081` | Server port |376| `DEBUG` | `false` | Enable debug mode |377| `MAX_PAGE_SIZE` | `100` | Maximum results per page |378| `DEFAULT_PAGE_SIZE` | `20` | Default results per page |379| `MAX_CONTENT_LENGTH` | `2000` | Maximum content block length |380| `ENABLE_ANALYTICS` | `true` | Enable analytics endpoints |381| `ENABLE_BULK_OPERATIONS` | `true` | Enable bulk operations |382| `LOG_LEVEL` | `INFO` | Logging level |383384### Configuration Validation385386The server automatically validates all configuration on startup and provides clear error messages for invalid settings.387388## ๐ง Integration Examples389390### With AI Agents391392```python393import requests394395# Search for content396response = requests.post("http://localhost:8081/api/agent/query", json={397 "action": "search",398 "parameters": {"query": "project notes"}399})400401# Create a new page with links402response = requests.post("http://localhost:8081/api/agent/query", json={403 "action": "create_page",404 "parameters": {405 "title": "AI Generated Page",406 "content": "This page was created by an AI agent"407 }408})409410# Add bookmark to page411response = requests.post("http://localhost:8081/api/agent/query", json={412 "action": "add_content",413 "parameters": {414 "page_id": "page-id",415 "content_type": "bookmark",416 "content": "Useful Resource",417 "url": "https://example.com"418 }419})420```421422### With Your Chatbot423424```python425# Already integrated in your chatbot_agentic_v3.py!426# Enhanced with ALL new functions:427428# Core functions429server.notion_search_content()430server.notion_read_page()431server.notion_create_page()432433# Content addition with links434server.notion_add_paragraph()435server.notion_add_heading()436server.notion_add_bullet_point()437server.notion_add_todo()438439# Smart content helpers440server.notion_add_structured_content() # Multi-section content441server.notion_add_smart_content() # AI-friendly content parsing442443# Bulk operations444server.notion_bulk_create_pages()445server.notion_bulk_list_pages()446server.notion_bulk_analyze_pages()447448# Analytics449server.notion_workspace_analytics()450server.notion_content_analytics()451server.notion_activity_analytics()452```453454## ๐ Performance Features _(ENHANCED)_455456- **Async Operations**: Non-blocking I/O for better performance457- **Smart Timeouts**: Dynamic timeouts (30s standard, 60s bulk, 45s analytics)458- **Pagination Controls**: Configurable limits to prevent timeouts459- **Connection Pooling**: Efficient Notion API connections460- **Request Validation**: Fast input validation and sanitization461- **Error Recovery**: Graceful handling of API failures462- **Memory Efficient**: Optimized for low memory usage463- **Progress Yielding**: Prevents blocking during bulk operations464465## ๐ก๏ธ Security & Validation Features _(BULLETPROOF)_466467- **Token Validation**: Automatic Notion token validation468- **Input Sanitization**: Protection against malicious input469- **Comprehensive Validation**: All content types validated470 - Bookmark URLs must be valid HTTP/HTTPS471 - Page references must exist472 - Content length limits enforced473 - Required fields validation474- **Rate Limiting Ready**: Framework for rate limiting (configurable)475- **CORS Support**: Secure cross-origin requests476- **Environment Isolation**: Secure environment variable handling477- **HTTP Status Handling**: Proper error code processing478479## ๐ Error Handling _(ENHANCED)_480481The server provides detailed error messages for all scenarios:482483### Validation Errors484485- **Missing URLs**: "URL is required for bookmark content type"486- **Invalid Page References**: "Target page not found: page-name"487- **Empty Content**: "Content cannot be empty"488- **Invalid Content Types**: Clear list of supported types489490### API Errors491492- **Invalid Tokens**: Clear guidance for token setup493- **Missing Pages**: Helpful suggestions for page access494- **API Limits**: Graceful handling of Notion API limits495- **Network Issues**: Automatic retry mechanisms496- **Timeout Prevention**: Smart limits and pagination497498### HTTP Status Codes499500- **200**: Successful operations501- **400**: Validation errors (missing fields, invalid formats)502- **404**: Resource not found (pages, invalid references)503- **500**: Server errors (with detailed diagnostics)504- **503**: Server not initialized505506## ๐ Version History507508### V2.1.0 (Current) _(MAJOR UPDATE)_509510- ๐ **Link Functionality**: Bookmarks and link_to_page support511- ๐ก๏ธ **Bulletproof Validation**: Comprehensive input validation512- โก **Timeout Optimization**: Fixed bulk operations with smart pagination513- ๐งช **Enhanced Test Suite**: 48KB comprehensive testing (1,158 lines)514- ๐ **HTTP Status Handling**: Proper error code processing in tests515- ๐ฏ **Performance Controls**: Configurable timeouts and limits516- ๐ **Smart Content**: AI-friendly content parsing helpers517518### V2.0.0 (Previous)519520- โ Complete rewrite with enhanced features521- โ Configuration management system522- โ Basic test suite523- โ Production-ready error handling524- โ Bulk operations support525- โ Enhanced content management526- โ Agent integration endpoints527528### V1.0.0 (Legacy)529530- โ Basic MCP server functionality531- โ Core operations (search, read, create)532- โ Simple CLI interface533534## ๐ค Contributing5355361. Fork the repository5372. Create a feature branch: `git checkout -b feature-name`5383. Make your changes with tests5394. Run the comprehensive test suite: `python test_server.py`5405. Ensure all tests pass (aim for 90%+ success rate)5416. Submit a pull request542543**Testing Requirements:**544545- All new features must include tests546- Validation scenarios must be covered547- Performance implications should be documented548- Error handling paths must be tested549550## ๐ Support551552If you encounter issues:5535541. **Check Configuration**: Ensure all environment variables are set correctly5552. **Verify Token**: Make sure your Notion token is valid and has proper permissions5563. **Run Health Check**: Visit `/health` endpoint to verify server status5574. **Run Test Suite**: Use `python test_server.py` to identify specific issues5585. **Check Logs**: Review server logs for detailed error messages5596. **Test Validation**: Ensure your content meets validation requirements560561**Common Issues:**562563- **Link validation errors**: Ensure URLs start with http/https564- **Timeout issues**: Use pagination controls for large operations565- **Page not found**: Verify page sharing with integration566- **Content too long**: Content blocks limited to 2000 characters567568### ๐ง **Contact Information**569570For direct support or questions:571572- **๐ฑ Phone**: +918449035579573- **๐ง Email**: ankitmalik844903@gmail.com574- **๐จโ๐ป Developer**: Ankit Malik575576Feel free to reach out for:577578- โ Technical support and troubleshooting579- โ Feature requests and suggestions580- โ Integration assistance581- โ Bug reports and issues582- โ Custom development needs583584## ๐ License585586This project is part of the Agentic Long-Term Memory system.587588---589590**๐ Your Notion MCP Server V2.1 is bulletproof and production-ready!**591592**โก New in V2.1:**593594- ๐ **Link Support** - Bookmarks and internal page links595- ๐ก๏ธ **Bulletproof Validation** - Comprehensive error prevention596- โก **Timeout Optimization** - Smart pagination and limits597- ๐งช **48KB Test Suite** - Comprehensive testing and reporting598- ๐ฏ **Performance Controls** - Configurable timeouts and limits599600**๐ Quality Metrics:**601602- **1,158 lines** of test coverage603- **13+ test categories** including edge cases604- **90%+ success rate** target for all operations605- **Sub-5 second** response times for optimized operations606
Full transparency โ inspect the skill content before installing.