Claude Code Setup Guide for Python Developers: Virtual Environments, CLAUDE.md Rules & MCP Server Configuration

Claude Code Setup Guide for Python Developers

Claude Code is Anthropic’s agentic coding tool that operates directly in your terminal, understanding your codebase and executing tasks autonomously. This guide walks Python developers through setting up Claude Code with virtual environment detection, project-specific rules via CLAUDE.md, and MCP server configuration for database and API integrations.

Step 1: Install Claude Code

Claude Code requires Node.js 18+ and runs in your system terminal. Install it globally using npm: npm install -g @anthropic-ai/claude-code

Verify installation and authenticate: # Verify installation claude —version

Launch and authenticate

claude

First launch will prompt for Anthropic API key or OAuth login

Step 2: Configure Python Virtual Environment Detection

Claude Code automatically detects your project context, but explicit virtual environment configuration ensures consistent behavior across sessions.

Create and Activate Your Virtual Environment

# Create a virtual environment python -m venv .venv

Activate (Linux/macOS)

source .venv/bin/activate

Activate (Windows)

.venv\Scripts\activate

Install project dependencies

pip install -r requirements.txt

Add Environment Context to CLAUDE.md

Create a CLAUDE.md file in your project root so Claude Code automatically recognizes your Python environment: # Project: My Python API

Environment

  • Python 3.12 with virtual environment at .venv/
  • Always activate .venv before running Python commands
  • Package manager: pip with requirements.txt
  • Use python -m pytest for testing (not bare pytest)

Code Style

  • Follow PEP 8 and use type hints on all public functions
  • Use pathlib instead of os.path
  • Prefer f-strings over .format()

Project Structure

  • src/ contains application code
  • tests/ mirrors src/ structure
  • alembic/ for database migrations

    Claude Code reads this file at the start of every session, ensuring it respects your virtual environment and coding standards without repeated instructions.

Step 3: Set Up CLAUDE.md Project Rules

CLAUDE.md files form a hierarchy of instructions that Claude Code follows automatically.

File Hierarchy

File LocationScopeUse Case
~/.claude/CLAUDE.mdGlobal (all projects)Personal preferences, global tool configs
PROJECT_ROOT/CLAUDE.mdProject-wideCoding standards, architecture rules, environment setup
src/CLAUDE.mdDirectory-scopedModule-specific conventions
### Effective CLAUDE.md Example for a FastAPI Project # FastAPI Inventory Service

Commands

  • Run server: uvicorn src.main:app --reload
  • Run tests: python -m pytest tests/ -v --tb=short
  • Run single test: python -m pytest tests/test_items.py::test_create_item -v
  • Lint: ruff check src/ tests/
  • Migrations: alembic upgrade head

Architecture

  • Router files in src/routers/ (one per domain)
  • Service layer in src/services/ (business logic only)
  • Repository pattern in src/repositories/ (all DB access)
  • Pydantic schemas in src/schemas/

Rules

  • Never import from repositories in routers (always go through services)
  • All endpoints must have response_model defined
  • Write integration tests against a real test database, not mocks
  • Use dependency injection for database sessions

Step 4: Configure MCP Servers for Database & API Integrations

The Model Context Protocol (MCP) extends Claude Code with external tool integrations. Configure MCP servers in your project's .mcp.json file at the project root.

Database Integration with PostgreSQL

// .mcp.json { “mcpServers”: { “postgres”: { “command”: “npx”, “args”: [ “-y”, “@modelcontextprotocol/server-postgres”, “postgresql://user:password@localhost:5432/mydb” ] } } }

With this configured, you can ask Claude Code to query your database directly: # In your Claude Code session, you can now say:

Show me all users who signed up in the last 7 days What indexes exist on the orders table? Find the slowest queries based on the schema

REST API Integration

// .mcp.json — adding an API server alongside the database
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://user:password@localhost:5432/mydb"
      ]
    },
    "fetch": {
      "command": "npx",
      "args": [
        "-y",
        "@anthropic-ai/mcp-fetch"
      ]
    },
    "custom-api": {
      "command": "python",
      "args": ["mcp_servers/api_server.py"],
      "env": {
        "API_BASE_URL": "https://api.example.com/v1",
        "API_KEY": "YOUR_API_KEY"
      }
    }
  }
}

Verify MCP Server Status

# Inside a Claude Code session, type:
/mcp

# This shows all configured servers and their connection status

Step 5: Practical Workflow Example

Here is a realistic workflow combining all three components: - **Start your session** — Navigate to your project root and run claude. Claude Code reads CLAUDE.md and connects to MCP servers.- **Ask Claude to scaffold** — Create a new endpoint POST /api/orders that validates inventory before creating an order. Check the products table for current stock levels.- **Claude Code will** — Read your project structure, query the database schema via MCP, generate code following your CLAUDE.md rules (service layer, repository pattern), and run your tests.- **Iterate** — The test for insufficient stock is failing. Debug it. Claude reads the test output, traces the logic, and fixes the issue. ## Pro Tips for Power Users - **Use /init to bootstrap CLAUDE.md** — Run /init inside a Claude Code session and it will analyze your project structure and generate a starter CLAUDE.md file automatically.- **Scope MCP configs** — Use .mcp.json at the project level for shared team configs. Use ~/.claude/.mcp.json for personal servers you want available everywhere.- **Chain commands in CLAUDE.md** — Define composite commands like Full check: ruff check src/ && python -m pytest tests/ -v so Claude can run your entire validation suite in one step.- **Use claude --resume** — Resume your most recent session to maintain context across terminal restarts.- **Headless mode for CI** — Run claude -p "run all tests and fix any failures" --allowedTools bash,edit to integrate Claude Code into automated pipelines. ## Troubleshooting Common Errors

ErrorCauseFix
MCP server disconnectedServer binary not found or crashedRun /mcp to check status. Ensure the command in .mcp.json is installed globally or the path is correct.
CLAUDE.md not detectedFile is in wrong directory or has wrong nameMust be named exactly CLAUDE.md (case-sensitive) and placed in the project root or relevant subdirectory.
Virtual env packages not foundClaude running Python outside .venvAdd explicit activation instructions in CLAUDE.md. Ensure .venv/bin/python is referenced in your run commands.
Permission denied on tool useTool not in the allowed listApprove the tool when prompted, or pre-allow with --allowedTools flag.
Connection refused (PostgreSQL MCP)Database not running or wrong credentialsVerify the connection string in .mcp.json and ensure the database is accessible on the specified port.
## Frequently Asked Questions

Can Claude Code automatically activate my Python virtual environment?

Claude Code executes shell commands in your terminal context. If you activate your virtual environment before launching claude, all Python commands it runs will use that environment. You can also add explicit instructions in CLAUDE.md such as “Always use .venv/bin/python for running scripts” to ensure the correct interpreter is used even if activation is missed.

How do I share MCP server configuration with my team without exposing credentials?

Use environment variables in your .mcp.json configuration with the env field, and store actual secrets in a .env file that is listed in .gitignore. Commit the .mcp.json with placeholder values or env var references. Each developer sets their own credentials locally. For CI pipelines, inject secrets through your CI platform’s secret management.

Can I use multiple MCP servers simultaneously in one Claude Code session?

Yes. Define all servers in your .mcp.json file and Claude Code connects to all of them at session start. You can have a database server, a fetch server, and custom API servers running simultaneously. Claude Code intelligently selects which MCP tool to use based on your request context. Use the /mcp command to verify all servers are connected and healthy.

Explore More Tools

Grok Best Practices for Real-Time News Analysis and Fact-Checking with X Post Sourcing Best Practices Devin Best Practices: Delegating Multi-File Refactoring with Spec Docs, Branch Isolation & Code Review Checkpoints Best Practices Bolt Case Study: How a Solo Developer Shipped a Full-Stack SaaS MVP in One Weekend Case Study Midjourney Case Study: How an Indie Game Studio Created 200 Consistent Character Assets with Style References and Prompt Chaining Case Study How to Install and Configure Antigravity AI for Automated Physics Simulation Workflows Guide How to Set Up Runway Gen-3 Alpha for AI Video Generation: Complete Configuration Guide Guide Replit Agent vs Cursor AI vs GitHub Copilot Workspace: Full-Stack Prototyping Compared (2026) Comparison How to Build a Multi-Page SaaS Landing Site in v0 with Reusable Components and Next.js Export How-To Kling AI vs Runway Gen-3 vs Pika Labs: Complete AI Video Generation Comparison (2026) Comparison Claude 3.5 Sonnet vs GPT-4o vs Gemini 1.5 Pro: Long-Document Summarization Compared (2025) Comparison Midjourney v6 vs DALL-E 3 vs Stable Diffusion XL: Product Photography Comparison 2025 Comparison Runway Gen-3 Alpha vs Pika 1.0 vs Kling AI: Short-Form Video Ad Creation Compared (2026) Comparison BMI Calculator - Free Online Body Mass Index Tool Calculator Retirement Savings Calculator - Free Online Planner Calculator 13-Week Cash Flow Forecasting Best Practices for Small Businesses: Weekly Updates, Collections Tracking, and Scenario Planning Best Practices 30-60-90 Day Onboarding Plan Template for New Marketing Managers Template Amazon PPC Case Study: How a Private Label Supplement Brand Lowered ACOS With Negative Keyword Mining and Exact-Match Campaigns Case Study Accounts Payable Automation Case Study: How a Multi-Location Restaurant Group Cut Invoice Processing Time With OCR and Approval Routing Case Study ATS-Friendly Resume Formatting Best Practices for Career Changers Best Practices How to Build Automated Client Onboarding Workflows in Antigravity with Intake Forms, Document Generation & CRM Sync How-To