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 migrationsClaude 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 Location | Scope | Use Case |
|---|---|---|
~/.claude/CLAUDE.md | Global (all projects) | Personal preferences, global tool configs |
PROJECT_ROOT/CLAUDE.md | Project-wide | Coding standards, architecture rules, environment setup |
src/CLAUDE.md | Directory-scoped | Module-specific conventions |
# 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
| Error | Cause | Fix |
|---|---|---|
MCP server disconnected | Server binary not found or crashed | Run /mcp to check status. Ensure the command in .mcp.json is installed globally or the path is correct. |
CLAUDE.md not detected | File is in wrong directory or has wrong name | Must be named exactly CLAUDE.md (case-sensitive) and placed in the project root or relevant subdirectory. |
Virtual env packages not found | Claude running Python outside .venv | Add explicit activation instructions in CLAUDE.md. Ensure .venv/bin/python is referenced in your run commands. |
Permission denied on tool use | Tool not in the allowed list | Approve the tool when prompted, or pre-allow with --allowedTools flag. |
Connection refused (PostgreSQL MCP) | Database not running or wrong credentials | Verify the connection string in .mcp.json and ensure the database is accessible on the specified port. |
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.