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.