The Mega MCP tutorial in Python

Step 1 – Project Setup & Environment

What You’ll Achieve

By the end of this tutorial, you’ll have a working Flask web application with:

  • A clean Python virtual environment with all necessary dependencies
  • A basic Flask server running on http://localhost:5000
  • Environment variable configuration for secure API key management
  • A simple “Hello, Flask!” endpoint and health check
  • Proper project structure for a production-ready application

This forms the foundation for building a multi-provider chat application that can work with OpenAI, Ollama, and other LLM providers.

How We’ll Get There

We’ll build this foundation in 4 key steps:

  1. Environment Setup: Create an isolated Python environment to avoid dependency conflicts
  2. Dependency Management: Install Flask and other core libraries we’ll need throughout the tutorial series
  3. Basic Flask App: Create a minimal web server with health monitoring
  4. Configuration System: Set up secure environment variable handling for API keys and settings

This approach ensures you have a solid, secure foundation that can scale as we add more features in subsequent tutorials.

Setting Up Your Development Environment

First, let’s create a clean workspace for our chat application:

mkdir python-chat-app
cd python-chat-app

Create and activate a Python virtual environment:

# Create virtual environment
# This isolates our project dependencies from system Python packages
python -m venv venv

# Activate it (Linux/Mac)
source venv/bin/activate

# Activate it (Windows)
venv\Scripts\activate

Why Virtual Environments? Virtual environments prevent dependency conflicts between different Python projects. Each project gets its own isolated space for packages.

Installing Core Dependencies

Create a requirements.txt file with our initial dependencies:

Flask==2.3.3
openai==1.3.0
python-dotenv==1.0.0
prometheus-client==0.17.1

Install the dependencies:

pip install -r requirements.txt

Dependency Breakdown:

  • Flask: Our web framework for handling HTTP requests
  • openai: Client library for OpenAI API integration
  • python-dotenv: Safely loads environment variables from .env files
  • prometheus-client: Metrics collection for monitoring (used in later tutorials)

Creating the Basic Flask Application

Create app.py with a simple Flask setup:

from flask import Flask, render_template
import os
from dotenv import load_dotenv

# Load environment variables from .env file
# This must be called before accessing environment variables
load_dotenv()

# Initialize Flask application
app = Flask(__name__)

@app.route('/')
def hello():
    """
    Root endpoint that confirms the application is running.
    This will be replaced with our chat interface in the next tutorial.
    """
    return "Hello, Flask! Your Python chat app is running."

@app.route('/health')
def health():
    """
    Health check endpoint for monitoring.
    Returns JSON to indicate server status - useful for load balancers
    and monitoring tools in production.
    """
    return {"status": "healthy", "service": "python-chat-app"}

if __name__ == '__main__':
    # Run the development server
    # debug=True enables auto-reload when code changes
    # host='0.0.0.0' allows connections from any IP (useful for Docker later)
    # port=5000 is the standard Flask development port
    app.run(debug=True, host='0.0.0.0', port=5000)

Environment Configuration

Create a .env file to store your configuration:

OPENAI_API_KEY=your_openai_api_key_here
FLASK_ENV=development
FLASK_DEBUG=true

Security Note: The .env file contains sensitive information like API keys. Never commit this to version control.

Important: Add .env to your .gitignore file to keep your API keys secure:

# Environment and sensitive files
.env

# Python virtual environment
venv/

# Python cache files
__pycache__/
*.pyc

# Operating system files
.DS_Store

Why .gitignore? This file tells Git which files to ignore when committing code. This prevents accidentally sharing sensitive information like API keys.

Testing Your Setup

Run your Flask application:

python app.py

You should see output like:

 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://[::1]:5000

Visit http://localhost:5000 in your browser. You should see “Hello, Flask! Your Python chat app is running.”

Also test the health endpoint at http://localhost:5000/health to confirm everything is working properly.

Project Structure

Your project should now look like this:

python-chat-app/
├── venv/                 # Virtual environment (don't commit)
├── app.py               # Main Flask application
├── requirements.txt     # Python dependencies
├── .env                # Environment variables (don't commit)
└── .gitignore          # Git ignore rules

Next Steps

With your basic Flask application running, you’re ready to move on to Step 2: Building the Jinja2 Frontend where we’ll create the user interface for our chat application.

Troubleshooting

Common Issues:

  1. Virtual environment activation fails:

    # Make sure you're in the right directory
    pwd
    # Try creating the virtual environment again
    python -m venv venv --clear
    
  2. Dependencies won’t install:

    # Upgrade pip first
    pip install --upgrade pip
    # Try installing requirements again
    pip install -r requirements.txt
    
  3. Flask app won’t start:

    • Check that you’re in the virtual environment
    • Verify Python version: python --version
    • Check for syntax errors in app.py

Next: Step 2: Building the Jinja2 Frontend

Leave a Reply

Your email address will not be published. Required fields are marked *