This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Quantum Code is a multi-model AI orchestration server that provides advanced code analysis capabilities through the Model Context Protocol (MCP). It orchestrates multiple LLM providers via LiteLLM to deliver systematic code review and analysis tools.
The server is built with FastMCP and uses a streamlined workflow architecture optimized for fast, cost-effective analysis with models like gpt-5-mini.
Production Ready ✅
- Unit Tests: ✅ 511 tests passing (~2s) - All tests passing (includes 24 mocked CLI tests for parsing/error handling)
- Integration Tests: ✅ 93 tests passing (~8-10min) - All tests passing (includes 6 CLI smoke tests, 8 CLI workflow tests)
- Total Coverage: ✅ 604 tests passing (~85% code coverage)
- Model Config: YAML-based model configuration with aliases and use-case defaults
- Logging: MCP tool request/response logging enabled
- Implementation: Checklist-based workflow with expert validation enabled
- File Limit Enforcement: ✅
settings.max_files_per_reviewis enforced
# Type checking (required before commits)
uv run pyright
# Linting and formatting (required before commits)
uv run ruff check .
uv run ruff format .
# Run all unit tests (511 tests, ~2s, all passing ✅)
uv run pytest tests/unit/ -v
# Run integration tests (93 tests, ~5-7min with parallel, all passing ✅)
# Note: Requires real API keys (OPENAI_API_KEY, etc.)
# CLI tests will skip gracefully if CLIs not installed
RUN_E2E=1 uv run pytest tests/integration/ -n auto -v
# Or run sequentially (slower, ~15min)
RUN_E2E=1 uv run pytest tests/integration/ -v
# Run all tests (604 total)
RUN_E2E=1 uv run pytest tests/ -v
# Run the MCP server
./scripts/run_server.sh
# or: uv run python quantum_code/server.py
# View MCP logs (request/response)
ls -lh logs/*.mcp.json
cat logs/*.mcp.json | jq .Package: https://pypi.org/project/quantum-code/
# Build package (creates dist/*.whl and dist/*.tar.gz)
make build
# Publish to TestPyPI (for testing)
make publish-test
# Publish to PyPI (production)
make publish
# Clean build artifacts before rebuilding
make cleanVersion Management:
- Version is in
pyproject.toml(line 3):version = "X.Y.Z" - Bump version before publishing (PyPI doesn't allow re-uploading same version)
- Entry points:
quantum(CLI),quantum-server(MCP server),quantum-code(MCP server alias for uvx)
User Installation:
pip install quantum-code
claude mcp add quantum -- uvx quantum-codeAutomated Publishing: See docs/github-pypi-v1.md for GitHub Actions workflow plan.
See README.md for installation instructions and environment setup.
See README.md for CLI usage examples. Note: CLI is experimental.
quantum_code/server.py: FastMCP server implementation with factory-generated tool wrappers
- Uses
create_mcp_wrapper()factory to auto-generate tools from schemas - Tool wrappers decorated with
@mcp.tool()and@mcp_monitorfor logging - Calls
*_impl()functions fromquantum_code/tools/for actual implementation
quantum_code/tools/: Tool implementation functions
codereview.py- Code review workflow with checklist guidance and expert validationchat.py- Interactive chat for development questionscompare.py- Multi-model parallel analysisdebate.py- Two-step debate workflow (independent + critique)models.py- Model listing implementation
quantum_code/models/: Model configuration and LLM integration
config.py- YAML-based model config with Pydantic validation (ModelConfig,ModelsConfiguration,PROVIDERS)resolver.py- Model alias resolution with LiteLLM fallback (ModelResolver)litellm_client.py- API model execution via LiteLLM responses API (~260 lines)cli_executor.py- CLI model execution via subprocess (~270 lines)
quantum_code/config/config.yaml: Model definitions
- Canonical model names with LiteLLM model strings
- Aliases (e.g.,
mini→gpt-5-mini,sonnet→claude-sonnet-4.5) - Temperature constraints per model
- User overrides:
~/.quantum_code/config.yaml(optional)
quantum_code/settings.py: Environment-based configuration using Pydantic Settings
- API keys loaded from
.envfiles (cascading: project .env > ~/.quantum_code/.env) - Runtime defaults (
default_model,default_model_list,default_temperature) - Server settings (
max_retries,model_timeout_seconds, etc.) default_model_list: Default models for multi-model compare (comma-separated or JSON array in .env)
quantum_code/schemas/: Pydantic models for request validation
base.py- BaseBaseToolRequest,SingleToolRequest,ModelResponseMetadatacodereview.py-CodeReviewRequest,CodeReviewResponsechat.py-ChatRequest,ChatResponsecompare.py-CompareRequest,CompareResponsedebate.py-DebateRequest,DebateResponse- Single source of truth: Field descriptions defined once in Pydantic models
- DRY principle: Factory auto-generates tools from schemas
quantum_code/memory/: Conversation state management
store.py-ThreadStoreclass for in-memory conversation storage
quantum_code/prompts/: System prompts loaded from markdown files
codereview.md- Code review instructions with OWASP Top 10, performance patternschat.md- Chat system prompt for development assistancecompare.md- Multi-model compare instructionsdebate-step1.md- Independent answer phase instructionsdebate-step2.md- Debate and voting phase instructions__init__.py- Loads prompts into constants
quantum_code/utils/: Utility functions
context.py- ContextVar-based request context management (thread_id, workflow, step_number, base_path)mcp_decorator.py- MCP tool decorator that sets context at request entrymcp_factory.py- Factory for auto-generating MCP tools from Pydantic schemasmcp_logger.py- MCP tool request/response loggingrequest_logger.py- LLM API call loggingrepository.py- Repository context builder (loads CLAUDE.md/AGENTS.md from context base_path)artifacts.py- Unified artifact saving (uses base_path from context)llm_runner.py- LLM execution helpers with_route_model_execution()(routes API models →litellm_client.execute(), CLI models →cli_executor.execute())message_builder.py- Message construction for LLM API callspaths.py- Path resolution and validation (security)prompts.py- Expert context builder for code reviewfiles.py- File operations utilitiesjson_parser.py- Robust JSON parsing with repair capabilitieshelpers.py- Version retrieval, field description extractionlog_helpers.py- Log file writing, timestamp formatting
Factory-Based Tool Generation: Tools are auto-generated from Pydantic schemas using create_mcp_wrapper() factory (quantum_code/utils/mcp_factory.py).
Process: Define Pydantic schema → Use factory to generate wrapper → Factory auto-generates function signature
Benefits: Single source of truth, zero boilerplate, full type safety, easy to add tools (3 lines)
Uses Python's contextvars module for request-scoped data (thread_id, workflow, step_number, base_path).
- Implementation:
quantum_code/utils/context.py - Entry:
mcp_decoratorsets context from request params - Usage: Utility functions call
get_thread_id(),get_base_path(), etc. - Cleanup:
clear_context()prevents leaks - Benefits: Cleaner APIs, thread-safe, fallback pattern for explicit params
- Line Length: 120 characters maximum
- Type Hints: Required for all function signatures
- Async-First: All I/O operations must be async (
async def,await) - Test Coverage: Minimum 80% overall
- Error Handling: Return structured error dicts with context
- Logging: Use
logger.info()for model calls with thread_id, model name, token usage
Models are defined in quantum_code/config/config.yaml. See README.md for model aliases.
Key Features:
- Aliases resolve to full model names (e.g.,
mini→gpt-5-mini) - Temperature constraints enforced per model
- LiteLLM fallback for unknown models
- User overrides via
~/.quantum_code/config.yaml(optional, merged with package defaults) - Runtime defaults (model, temperature) in Settings class via
.envfiles
LiteLLM Responses API:
- Uses
litellm.aresponses()instead oflitellm.acompletion()for unified web search across providers - Unified
tools=[{"type": "web_search"}]parameter works with OpenAI, Azure, Anthropic, Gemini - Limitation: Only
total_tokensavailable (noprompt_tokens/completion_tokensbreakdown) - Web search enabled via
enable_web_search=Trueparameter inlitellm_client.execute()
Location: tests/unit/
- Mock LiteLLM with fixtures, test
*_impl()functions directly - No real API calls, Runtime: ~2 seconds, Coverage: ~85%
- Tests: schemas, tools (codereview/chat/compare/debate), models, MCP factory, CLI, utils
Location: tests/integration/
- End-to-end tests with real APIs (codereview, chat, compare, debate, web search)
- MCP server integration, CLI workflows, error handling, thread management
- Requires: Real API keys,
RUN_E2E=1, Runtime: ~8-10 minutes - VCR: Currently disabled (see
tests/cassettes/README.md)
- MCP Tools:
logs/TIMESTAMP.THREAD_ID.mcp.json(requests/responses) - LLM API:
logs/TIMESTAMP.THREAD_ID.llm.json(model calls, usage stats) - Console:
logs/server.logwith structured tags[CODEREVIEW],[CHAT], etc. - View:
cat logs/*.mcp.json | jq .orcat logs/*.llm.json | jq .
- Create Pydantic schema in
quantum_code/schemas/ - Create
*_impl()function inquantum_code/tools/ - Add factory wrapper in
quantum_code/server.py:create_mcp_wrapper(Schema, impl, "Description") - Add tests in
tests/unit/andtests/integration/ - Add system prompt (if needed) in
quantum_code/prompts/
Debugging: Check logs in logs/ directory, use LOG_LEVEL=DEBUG in .env
Prompts: Edit quantum_code/prompts/*.md, changes take effect on server restart
- DRY (Don't Repeat Yourself): Field descriptions, validation rules, and documentation defined once in Pydantic models
- Single Source of Truth: Schema models are the authoritative source for parameter definitions
- Type Safety: Full type checking with Pydantic and Pyright
- YAGNI: Don't add complexity until actually needed
- KISS: Keep it simple, stupid!
- Clean Code: No dead code, all imports used, all tests passing
- Greenfield project: No worries about backward compatibility
- Architecture: Clean, streamlined workflow design with FastMCP and LiteLLM
- Current State: Production-ready with expert validation enabled
- Breaking Changes Allowed: Greenfield project, no backward compatibility concerns
- Documentation: New documentation should be saved to
docs/ - Temporary Files: Use
tmp/for experiments, spikes, complex bash scripts - Reference Projects:
ref/contains reference projects to check documentation - DO NOT modify these - File Operations: Use Claude Code's Read/Write tools, NOT Bash(cat > dir/file.ex << 'EOF')
- Running Python scripts: Use Claude Code's Read/Write tools to generate files in
tmp/and execute withuv run python tmp/file_name.py - Complex Scripts: Write to
tmp/directory first, then execute - Live Testing: Always use low-cost models (gpt-5-mini, claude-haiku-4-5-20251001, gemini-3-flash) for rapid iteration
- Deterministic Patterns: Prefer checklist-based guidance over LLM-generated suggestions for intermediate steps
- Testing: ALWAYS test after making bigger changes - run
uv run pytest tests/unit/(fast) orRUN_E2E=1 uv run pytest(full) - Git Commits: Ensure all tests pass
make test-alland code is lintedmake checkbefore committing