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

Antigravity AI Content Pipeline Automation Guide: Google Docs to WordPress Publishing Workflow Guide Bolt.new Case Study: Marketing Agency Built 5 Client Dashboards in One Day Case Study Bolt.new Best Practices: Rapid Full-Stack App Generation from Natural Language Prompts Best Practices ChatGPT Advanced Data Analysis (Code Interpreter) Complete Guide: Upload, Analyze, Visualize Guide ChatGPT Custom GPTs Advanced Guide: Actions, API Integration, and Knowledge Base Configuration Guide ChatGPT Voice Mode Guide: Build Voice-First Customer Service and Internal Workflows Guide Claude API Production Chatbot Guide: System Prompt Architecture for Reliable AI Assistants Guide Claude Artifacts Best Practices: Create Interactive Dashboards, Documents, and Code Previews Best Practices Claude Code Hooks Guide: Automate Custom Workflows with Pre and Post Execution Hooks Guide Claude MCP Server Setup Guide: Build Custom Tool Integrations for Claude Code and Claude Desktop Guide Cursor Composer Complete Guide: Multi-File Editing, Inline Diffs, and Agent Mode Guide Cursor Case Study: Solo Founder Built a Next.js SaaS MVP in 2 Weeks with AI-Assisted Development Case Study Cursor Rules Advanced Guide: Project-Specific AI Configuration and Team Coding Standards Guide Devin AI Team Workflow Integration Best Practices: Slack, GitHub, and Code Review Automation Best Practices Devin Case Study: Automated Dependency Upgrade Across 500-Package Python Monorepo Case Study ElevenLabs Case Study: EdTech Startup Localized 200 Course Hours to 8 Languages in 6 Weeks Case Study ElevenLabs Multilingual Dubbing Guide: Automated Video Localization Workflow for Global Content Guide ElevenLabs Voice Design Complete Guide: Create Consistent Character Voices for Games, Podcasts, and Apps Guide Gemini 2.5 Pro vs Claude Sonnet 4 vs GPT-4o: AI Code Generation Comparison 2026 Comparison Gemini API Multimodal Developer Guide: Image, Video, and Document Analysis with Code Examples Guide