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 Academic Research and Literature Discovery: Leveraging X/Twitter for Scholarly Intelligence Best Practices Grok Best Practices for Content Strategy: Identify Trending Topics Before They Peak and Create Content That Captures Demand Best Practices Grok Case Study: How a DTC Beauty Brand Used Real-Time Social Listening to Save Their Product Launch Case Study Grok Case Study: How a Pharma Company Tracked Patient Sentiment During a Drug Launch and Caught a Safety Signal 48 Hours Before the FDA Case Study Grok Case Study: How a Disaster Relief Nonprofit Used Real-Time X/Twitter Monitoring to Coordinate Emergency Response 3x Faster Case Study Grok Case Study: How a Political Campaign Used X/Twitter Sentiment Analysis to Reshape Messaging and Win a Swing District Case Study How to Use Grok for Competitive Intelligence: Track Product Launches, Pricing Changes, and Market Positioning in Real Time How-To Grok vs Perplexity vs ChatGPT Search for Real-Time Information: Which AI Search Tool Is Most Accurate in 2026? Comparison How to Use Grok for Crisis Communication Monitoring: Detect, Assess, and Respond to PR Emergencies in Real Time How-To How to Use Grok for Product Improvement: Extract Customer Feedback Signals from X/Twitter That Your Support Team Misses How-To How to Use Grok for Conference Live Monitoring: Extract Event Insights and Identify Networking Opportunities in Real Time How-To How to Use Grok for Influencer Marketing: Discover, Vet, and Track Influencer Partnerships Using Real X/Twitter Data How-To How to Use Grok for Job Market Analysis: Track Industry Hiring Trends, Layoff Signals, and Salary Discussions on X/Twitter How-To How to Use Grok for Investor Relations: Track Earnings Sentiment, Analyst Reactions, and Shareholder Concerns in Real Time How-To How to Use Grok for Recruitment and Talent Intelligence: Identifying Hiring Signals from X/Twitter Data How-To How to Use Grok for Startup Fundraising Intelligence: Track Investor Sentiment, VC Activity, and Funding Trends on X/Twitter How-To How to Use Grok for Regulatory Compliance Monitoring: Real-Time Policy Tracking Across Industries How-To NotebookLM Best Practices for Financial Analysts: Due Diligence, Investment Research & Risk Factor Analysis Across SEC Filings Best Practices NotebookLM Best Practices for Teachers: Build Curriculum-Aligned Lesson Plans, Study Guides, and Assessment Materials from Your Own Resources Best Practices NotebookLM Case Study: How an Insurance Company Built a Claims Processing Training System That Cut Errors by 35% Case Study