Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions MCP/swagger-doc_notion/python/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Multi-stage build for Python MCP Server
FROM python:3.11-alpine AS builder

# Set working directory
WORKDIR /app

# Copy requirements file
COPY requirements.txt ./

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Install PyInstaller
RUN pip install --no-cache-dir pyinstaller

# Copy source code
COPY . .

# Build the binary
RUN pyinstaller --onefile --name mcp-server main.py

# Final stage
FROM alpine:latest

# Install ca-certificates for HTTPS requests
RUN apk --no-cache add ca-certificates

# Create app directory
WORKDIR /app

# Copy binary from builder stage
COPY --from=builder /app/dist/mcp-server .

# Make binary executable
RUN chmod +x mcp-server

# Expose port (if running in HTTP mode)
EXPOSE 8080

# Set non-sensitive environment variables
ENV PORT="8080"
ENV TRANSPORT="http"

# Run the binary
CMD ["./mcp-server"]
202 changes: 202 additions & 0 deletions MCP/swagger-doc_notion/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
# Notion API - Public Beta MCP Server

This MCP (Model Content Protocol) server provides access to Notion API - Public Beta API functionality through STDIO transport mode with FastMCP.

## Features

- FastMCP-based server with decorator pattern
- Automatic tool registration via @mcp.tool() decorators
- Type-safe parameter handling
- Comprehensive error handling and logging
- Easy configuration through environment variables

## Prerequisites

- Python 3.10 or later
- pip package manager

## Installation

1. Install dependencies:
```bash
pip install -r requirements.txt
```

2. Configure environment variables:
```bash
export API_BASE_URL="https://your-api-base-url"
export BEARER_TOKEN="your-bearer-token"
# Alternative authentication options (use only one):
# export API_KEY="your-api-key"
# export BASIC_AUTH="your-basic-auth-credentials"
```

## Running the MCP Server

### STDIO Mode (Default)

The server runs in STDIO mode by default, which is perfect for direct integration with AI assistants like Cursor:

```bash
python main.py
```

### Configuration for Cursor/Claude Desktop

Add this to your MCP configuration file (e.g., `~/Library/Application Support/Cursor/User/globalStorage/@anthropic/mcp-server-registry/mcp.json`):

```json
{
"mcpServers": {
"notion-api---public-beta-mcp-server": {
"command": "python",
"args": ["/path/to/your/project/main.py"],
"env": {
"API_BASE_URL": "https://your-api-base-url",
"BEARER_TOKEN": "your-bearer-token"
}
}
}
}
```

## Environment Variables

### Required
- `API_BASE_URL`: Base URL for the API endpoint

### Authentication (use one of the following)
- `BEARER_TOKEN`: Bearer token for OAuth2/Bearer authentication
- `API_KEY`: API key for API key authentication
- `BASIC_AUTH`: Basic authentication credentials (base64 encoded)

**Note**: At least one authentication variable should be provided unless the API explicitly doesn't require authentication.

## Development

For development with auto-reload:

```bash
# Install development dependencies
pip install -r requirements.txt

# Run with Python
python main.py
```

## Project Structure

```
.
├── main.py # Entry point with FastMCP server
├── config.py # Configuration management
├── models.py # Pydantic data models
├── tools/ # Auto-generated tools organized by category
│ ├── __init__.py
│ └── [category]/ # Tools grouped by API endpoint category
│ ├── __init__.py
│ └── *.py # Individual tool implementations
├── requirements.txt # Python dependencies
└── README.md # This file
```

## How It Works

This MCP server is built using FastMCP with a decorator-based architecture:

1. **FastMCP Server**: Creates an MCP server instance in `main.py`
2. **Tool Decorators**: Each tool is decorated with `@mcp.tool()` for automatic registration
3. **Auto-Import**: Tools are automatically registered when their modules are imported
4. **Type Safety**: Uses Python type hints for parameter validation
5. **Error Handling**: Comprehensive error handling with JSON error responses

### Example Tool

```python
from main import mcp

@mcp.tool()
def get_users(search: str = None, page: int = None) -> str:
"""
Get users from the API.

Args:
search: Search query for filtering users
page: Page number for pagination

Returns:
JSON string with user data
"""
# Tool implementation...
return json.dumps(result, indent=2)
```

## Authentication Methods

The server supports multiple authentication methods:

### Bearer Token (OAuth2)
```bash
export BEARER_TOKEN="your-bearer-token"
```

### API Key
```bash
export API_KEY="your-api-key"
```

### Basic Authentication
```bash
export BASIC_AUTH="base64-encoded-credentials"
```

## Logging

The server includes comprehensive logging to stderr:
- INFO level: General operations, tool registration
- WARNING level: Skipped operations, missing parameters
- ERROR level: API errors, request failures

View logs in your MCP client's console or stderr output.

## Troubleshooting

### "Missing required parameter" errors
- Check that all required parameters are provided
- Verify parameter names match the tool definition

### Authentication errors
- Ensure the correct authentication environment variable is set
- Verify your credentials are valid and not expired
- Check that the API_BASE_URL is correct

### Import errors
- Run `pip install -r requirements.txt` to ensure all dependencies are installed
- Check that you're using Python 3.10 or later

### Tool not found
- Verify the tool name matches what's shown in your MCP client
- Check the tools directory structure
- Ensure all `__init__.py` files are present

## Generated Tools

This server was automatically generated from an OpenAPI specification. Each API endpoint is exposed as an MCP tool with:
- Automatic parameter extraction and validation
- Type-safe parameter handling
- Comprehensive error handling
- JSON response formatting

Use your MCP client's tool listing feature to see all available tools.

## Contributing

This is a generated MCP server. To modify tool behavior:
1. Edit the tool implementation in `tools/[category]/[tool_name].py`
2. Maintain the `@mcp.tool()` decorator for registration
3. Keep the function signature for parameter validation
4. Test changes by running the server locally

## License

This generated MCP server follows the same license as the generator tool.
75 changes: 75 additions & 0 deletions MCP/swagger-doc_notion/python/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/bin/bash

# Build script for Python MCP server binary
# Usage: ./build.sh

set -e

echo "Building Python MCP Server Binary..."

# Create bin directory if it doesn't exist
mkdir -p bin

# Create virtual environment if it doesn't exist
if [ ! -d "venv" ]; then
echo "Creating virtual environment..."
python3 -m venv venv
fi

# Activate virtual environment
echo "Activating virtual environment..."
source venv/bin/activate

# Install dependencies if requirements.txt exists
if [ -f "requirements.txt" ]; then
echo "Installing dependencies..."
pip install -r requirements.txt
fi

# Check if PyInstaller is installed, if not install it
if ! command -v pyinstaller &> /dev/null; then
echo "Installing PyInstaller..."
pip install pyinstaller
fi

# Build the binary
pyinstaller --onefile --name mcp-server --distpath bin main.py

# Clean up build artifacts
rm -rf build/ *.spec

# Make binary executable
chmod +x bin/mcp-server

# Get current directory path
CURRENT_DIR=$(pwd)

# Update mcp-stdio.json with current directory
if [ -f "mcp-stdio.json" ]; then
echo "Updating mcp-stdio.json with current directory: $CURRENT_DIR"
sed -i.bak "s|\"/path/to/your/python/mcp/server/directory\"|\"$CURRENT_DIR\"|g" mcp-stdio.json
sed -i.bak "s|\"python\"|\"$CURRENT_DIR/python\"|g" mcp-stdio.json
sed -i.bak "s|\"main.py\"|\"$CURRENT_DIR/main.py\"|g" mcp-stdio.json
rm -f mcp-stdio.json.bak
echo "mcp-stdio.json updated successfully!"
else
echo "mcp-stdio.json not found, creating with current directory: $CURRENT_DIR"
cat > mcp-stdio.json << EOF
{
"mcpServers": {
"mcp-server-stdio": {
"command": "python",
"args": ["$CURRENT_DIR/main.py"],
"env": {
"API_BASE_URL": "https://your.api.url",
"BEARER_TOKEN": "your-token-here"
}
}
}
}
EOF
fi

echo "Binary built successfully!"
echo "Usage: ./bin/mcp-server or python main.py"
echo "MCP Config: mcp-stdio.json (updated with current directory)"
52 changes: 52 additions & 0 deletions MCP/swagger-doc_notion/python/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""API configuration for notion_api_public_beta."""
import os
from typing import Dict, Any


class APIConfig:
"""API configuration."""

def __init__(
self,
base_url: str = "",
bearer_token: str = "",
api_key: str = "",
basic_auth: str = "",
port: str = ""
):
self.base_url = base_url
self.bearer_token = bearer_token
self.api_key = api_key
self.basic_auth = basic_auth
self.port = port


def load_api_config() -> Dict[str, Any]:
"""
Load API configuration from environment variables.

Returns:
Configuration dictionary

Raises:
ValueError: If required configuration is missing
"""
# Check port environment variable
port = os.getenv("PORT") or os.getenv("port", "")

base_url = os.getenv("API_BASE_URL", "")

# Check transport environment variable
transport = os.getenv("TRANSPORT") or os.getenv("transport", "")

# For STDIO mode (not HTTP/HTTPS), API_BASE_URL is required
if transport not in ["http", "HTTP", "https", "HTTPS"] and not base_url:
raise ValueError("API_BASE_URL environment variable not set")

return {
"base_url": base_url,
"bearer_token": os.getenv("BEARER_TOKEN", ""),
"api_key": os.getenv("API_KEY", ""),
"basic_auth": os.getenv("BASIC_AUTH", ""),
"port": port,
}
14 changes: 14 additions & 0 deletions MCP/swagger-doc_notion/python/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
version: '3.8'

services:
mcp-server:
build:
context: .
dockerfile: Dockerfile
platforms:
- linux/amd64
environment:
- PORT=8080
- TRANSPORT=http
ports:
- "8080:8080"
Loading
Loading