Competitive Programming Mentor MCP Server
This server provides 23 modular AI-powered competitive programming tools for analyzing, planning, generating, verifying, testing, reviewing, and learning from problems and code.
Analyze problems – detect algorithmic patterns, extract constraints, estimate difficulty, and identify topics.
Plan solutions – suggest, compare, and choose the best algorithm, plus estimate runtime feasibility.
Generate code – produce contest-ready solutions in Python/C++/Java/Rust, pseudocode, or multi-language output.
Verify correctness – trace execution with dry runs, prove correctness, and analyze time/space complexity.
Test solutions – generate standard testcases, edge cases, and randomized stress-testing setups.
Review and debug – review code for bugs/TLE risks, locate logical errors, and optimize performance.
Learn and improve – get progressive hints, algorithm explanations, and recommended next problems.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Competitive Programming Mentor MCP Server suggest algorithm for 'Median of Two Sorted Arrays'"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
https://m8ven.ai/mcp/sami-codeai-mcp-server-for-competitive-programming-6880al?utm_source=new_listing&utm_medium=email&utm_campaign=new_listing https://glama.ai/mcp/servers/SAMI-CODEAI/MCP-Server-For-Competitive-Programming
📋 Table of Contents
Related MCP server: DevToolkit MCP Server
🤔 Why MCP?
Traditional AI coding assistants force all reasoning through one massive prompt. This approach suffers from:
Problem | Impact |
Monolithic prompts | Impossible to test, cache, or reuse individual capabilities |
Provider lock-in | Switching from OpenAI → Ollama requires rewriting everything |
No structured output | Raw text responses require fragile regex parsing |
Redundant LLM calls | Identical problems re-analyzed every time |
This MCP server solves all four. Each capability is an independent tool with its own schema, prompt template, cache key, and validation pipeline.
┌──────────────────┐ MCP Protocol ┌──────────────────────────┐
│ Claude Desktop │◄─────────────────────►│ CP Mentor MCP Server │
│ Cursor IDE │ JSON-RPC / stdio │ │
│ Claude CLI │ │ 23 Tools · 3 Resources │
│ Any MCP Client │ │ 3 Prompts · 2-Tier Cache│
└──────────────────┘ └────────────┬─────────────┘
│
┌────────────▼─────────────┐
│ LLM Provider Layer │
│ ┌────────┐ ┌─────────┐ │
│ │ OpenAI │ │ Ollama │ │
│ │gpt-4o │ │llama3.1 │ │
│ └────────┘ └─────────┘ │
└──────────────────────────┘🏗 Architecture
graph TD
Client["MCP Client<br/>(Cursor · Claude Desktop · CLI)"]
Server["FastMCP Server<br/>server.py"]
Cache{"Two-Tier Cache<br/>Memory TTL + SQLite Disk"}
Prompt["Jinja2 Prompt Manager<br/>prompts/*.md"]
Provider["LLM Provider Factory<br/>OpenAI | Ollama"]
Validator{"Self-Correcting Validator<br/>Pydantic v2 Schemas"}
Formatter["Response Formatter<br/>+ _meta tracing"]
Client -->|"tool call (JSON-RPC)"| Server
Server -->|"check cache"| Cache
Cache -->|"HIT"| Formatter
Cache -->|"MISS"| Prompt
Prompt -->|"rendered prompt"| Provider
Provider -->|"raw JSON"| Validator
Validator -->|"schema fail → retry prompt"| Provider
Validator -->|"schema pass"| Cache
Cache -->|"store result"| Formatter
Formatter -->|"structured response"| ClientCore Design Principles
Principle | Implementation |
Tool-Service Decoupling | Tools contain zero business logic — they delegate to |
Provider Independence |
|
Schema-First Validation | Every tool has a dedicated Pydantic |
Two-Tier Caching | In-memory |
Fail-Safe Registration | Each tool module is |
🔧 Tool Catalog (23 Tools)
🔍 Analysis (4 tools)
Tool | Description | Schema |
| Identifies algorithmic patterns (DP, Graph, Greedy, Math, etc.) from problem text |
|
| Parses numeric bounds (N, M, K, Q) and system limits (time/memory) |
|
| Approximates competitive programming difficulty rating |
|
| Tags primary/secondary topic categories |
|
📐 Planning (4 tools)
Tool | Description | Schema |
| Recommends candidate algorithms based on constraints |
|
| Builds a trade-off comparison matrix across candidates |
|
| Selects the optimal algorithm with justification |
|
| Calculates operation count vs. time budget feasibility |
|
💻 Code Generation (3 tools)
Tool | Description | Schema |
| Produces optimized, contest-ready code in the target language |
|
| Outputs language-agnostic structural pseudocode |
|
| Generates C++, Java, and Rust implementations simultaneously |
|
✅ Verification (3 tools)
Tool | Description | Schema |
| Traces variable states step-by-step through sample inputs |
|
| Provides formal correctness proofs (loop invariants, induction) |
|
| Computes asymptotic time/space complexity with justification |
|
🧪 Testing (3 tools)
Tool | Description | Schema |
| Creates input/output test pairs covering standard scenarios |
|
| Targets boundary conditions, zero-cases, and overflow scenarios |
|
| Generates randomized brute-force stress test configurations |
|
🔎 Code Review (3 tools)
Tool | Description | Schema |
| Full code review with correctness, efficiency, and style feedback |
|
| Pinpoints logical, runtime, or compile-time bugs |
|
| Suggests constant-factor and algorithmic optimizations |
|
📚 Learning (3 tools)
Tool | Description | Schema |
| Progressive hint system (nudge → approach → partial solution) |
|
| Educational breakdown with examples, when-to-use heuristics |
|
| Suggests follow-up problems to reinforce learned concepts |
|
📁 Project Structure
Competitive Programming Mentor MCP Server/
│
├── app.py # Entry point — mcp.run()
├── server.py # FastMCP app, tool/resource/prompt registration
├── config.py # Pydantic-settings configuration from .env
├── pyproject.toml # Dependencies & build config
├── .env.example # Environment template
│
├── services/ # Core business logic layer
│ ├── llm/
│ │ ├── base_provider.py # Abstract LLM interface
│ │ ├── openai_provider.py # OpenAI gpt-4o-mini adapter
│ │ ├── ollama_provider.py # Ollama local LLM adapter
│ │ └── provider_factory.py # Factory: .env → Provider instance
│ ├── prompt_manager.py # Jinja2 template renderer
│ ├── validator.py # Pydantic validation + self-correcting retry
│ ├── cache.py # Two-tier cache (TTLCache + diskcache)
│ ├── problem_parser.py # Regex constraint extractor (N, M, K, Q)
│ └── formatter.py # Response normalization + _meta tags
│
├── tools/ # MCP tool implementations (23 tools)
│ ├── analysis/ # detect_patterns, extract_constraints, ...
│ ├── planning/ # suggest_algorithms, compare_algorithms, ...
│ ├── generation/ # generate_solution, generate_pseudocode, ...
│ ├── verification/ # dry_run, prove_correctness, ...
│ ├── testing/ # generate_testcases, generate_edge_cases, ...
│ ├── review/ # review_solution, find_bug, optimize_solution
│ └── learning/ # get_hint, explain_algorithm, recommend_problem
│
├── schemas/ # Pydantic response models (one per tool)
├── prompts/ # Jinja2 markdown templates (one per tool + personas)
├── resources/ # Static knowledge base (Markdown files)
│ ├── algorithms/graphs/ # dijkstra.md
│ ├── data_structures/ # segment_tree.md
│ └── patterns/ # sliding_window.md
│
├── tests/ # Pytest test suite
│ ├── test_parser.py # Constraint parsing tests
│ ├── test_cache.py # Two-tier cache tests
│ └── test_validator.py # Schema validation + retry tests
│
└── docs/
├── ARCHITECTURE.md # System design documentation
└── TOOLS.md # Tool reference catalog🚀 Getting Started
Prerequisites
Installation
# Clone the repository
git clone https://github.com/your-username/competitive-programming-mcp.git
cd competitive-programming-mcp
# Install dependencies with uv
uv sync --all-extras
# Copy and configure environment
cp .env.example .env
# Edit .env with your API keys / Ollama settingsQuick Start
# Start the MCP server (stdio transport)
uv run app.py
# Or run in development mode with auto-reload
fastmcp dev app.py
# Run tests
uv run pytest⚙ Configuration
All settings are managed via .env and loaded through Pydantic Settings:
# ─── LLM Provider ────────────────────────────────────
LLM_PROVIDER=openai # "openai" or "ollama"
# ─── OpenAI (when LLM_PROVIDER=openai) ───────────────
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o-mini # ~$0.15/1M input tokens
OPENAI_MAX_TOKENS=4096
OPENAI_TEMPERATURE=0.2 # Low = deterministic code
# ─── Ollama (when LLM_PROVIDER=ollama) ────────────────
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama3.1:8b # Run: ollama pull llama3.1:8b
# ─── Cache ────────────────────────────────────────────
CACHE_ENABLED=true
CACHE_TTL_SECONDS=3600 # 1-hour TTL
CACHE_DISK_DIR=.cache # SQLite-backed persistent cache
# ─── Server ──────────────────────────────────────────
LOG_LEVEL=INFO # DEBUG | INFO | WARNING | ERROR📖 Workflows
Workflow 1: Claude Desktop Integration
Add the following to your claude_desktop_config.json:
{
"mcpServers": {
"cp-mentor": {
"command": "uv",
"args": [
"--directory",
"YOUR_ABSOLUTE_PATH\\Competitive Programming Mentor MCP Server",
"run",
"app.py"
]
}
}
}Note on Config Locations:
Standard Windows:
%APPDATA%\Claude\claude_desktop_config.jsonWindows Store App:
C:\Users\YOUR_NAME\AppData\Local\Packages\Claude_pzs8sxrjxfjjc\LocalCache\Roaming\Claude\claude_desktop_config.json
Restart Claude Desktop completely. Note: In the latest versions of Claude Desktop, the plug (🔌) icon has been removed from the UI. MCP tools are simply loaded silently in the background. Just ask Claude to "Use your cp-mentor tools to solve X" and you will see an approval pop-up!
Workflow 2: Claude CLI Integration
If you use the claude terminal tool, run:
claude mcp add cp-mentor uv --directory "/path/to/project" run app.py
claude # Start a sessionImportant for local models: If you are using
ollamawith the Claude CLI, make sure you launch it with a large enough model (e.g., 9B+ parameters) that supports tool calling. Small models (like 4B or 1B) will crash or fail to invoke MCP tools properly. Example:ollama launch claude --model qwen2.5:14b
Workflow 3: Cursor IDE Integration
Open Cursor → Settings → Features → MCP
Click + Add New MCP Server
Set Name:
cp-mentorSet Type:
commandSet Command:
uv --directory "/path/to/project" run app.py
Workflow 4: Full Problem-Solving Pipeline
User provides a problem (e.g., LeetCode / Codeforces)
│
▼
┌─────────────┐
│ Step 1 │ detect_patterns(problem)
│ Analyze │ extract_constraints(problem)
│ │ identify_topics(problem)
└──────┬──────┘
│
▼
┌─────────────┐
│ Step 2 │ suggest_algorithms(problem)
│ Plan │ compare_algorithms(problem, candidates)
│ │ choose_best_algorithm(problem, candidates)
└──────┬──────┘
│
▼
┌─────────────┐
│ Step 3 │ generate_solution(problem, approach, language)
│ Generate │ generate_pseudocode(problem)
└──────┬──────┘
│
▼
┌─────────────┐
│ Step 4 │ dry_run(problem, code)
│ Verify │ prove_correctness(problem)
│ │ analyze_complexity(problem, code)
└──────┬──────┘
│
▼
┌─────────────┐
│ Step 5 │ generate_testcases(problem)
│ Test │ generate_edge_cases(problem)
│ │ stress_testing(problem)
└──────┬──────┘
│
▼
┌─────────────┐
│ Step 6 │ review_solution(problem, code)
│ Review │ optimize_solution(problem, code)
└─────────────┘🔬 How It Works (Deep Dive)
1. Request Flow
When a client invokes detect_patterns(problem="..."), the following pipeline executes:
1. FastMCP receives JSON-RPC call via stdio transport
2. Tool function in tools/analysis/detect_patterns.py is invoked
3. CacheService.get("detect_patterns", {problem: "..."}) → checks memory, then disk
4. On MISS: PromptManager renders prompts/detect_patterns.md with Jinja2
5. ProviderFactory returns OpenAIProvider or OllamaProvider
6. Provider.structured_output(prompt, PatternResponse) calls the LLM API
7. Validator checks response against PatternResponse Pydantic schema
8. On validation failure: auto-correcting retry with error feedback prompt
9. CacheService.set() stores result in both memory and disk tiers
10. Formatter wraps response with _meta (tool name, model, cache status, latency)
11. Structured JSON returned to client2. Self-Correcting Validator
The validator implements a retry loop that feeds Pydantic validation errors back to the LLM:
# Simplified flow
for attempt in range(max_retries):
raw_json = await provider.structured_output(prompt, schema)
try:
return schema.model_validate_json(raw_json) # Success
except ValidationError as e:
prompt = f"Fix these errors: {e.errors()}\nOriginal: {raw_json}"
# Retry with corrective context3. Two-Tier Cache
┌─────────────────┐
get(key) ────────►│ Memory (TTL) │──── HIT ────► return value
│ ~256 entries │
│ μs latency │
└───────┬─────────┘
│ MISS
┌───────▼─────────┐
│ Disk (SQLite) │──── HIT ────► promote to memory
│ Persistent │ + return value
│ ms latency │
└───────┬─────────┘
│ MISS
▼
Call LLM ProviderCache keys are deterministic: f"{tool_name}:{sha256(sorted_json(inputs))[:16]}"
4. Provider Abstraction
class BaseLLMProvider(ABC):
@abstractmethod
async def generate(self, prompt: str, system: str = "") -> str: ...
@abstractmethod
async def structured_output(self, prompt: str, response_model: type[T], system: str = "") -> T: ...
@property
@abstractmethod
def model_name(self) -> str: ...OpenAIProvider: Uses
client.beta.chat.completions.parse()for native JSON schema generationOllamaProvider: Uses
openai-compatible endpoint with regex JSON extraction fallback
🧪 Testing
# Run all tests
$env:PYTHONPATH="." # PowerShell
uv run pytest
# Run with verbose output
uv run pytest -v
# Test specific module
uv run pytest tests/test_parser.py
uv run pytest tests/test_cache.py
uv run pytest tests/test_validator.pyTest Coverage
Module | Tests | What's Verified |
| 2 | Constraint regex parsing (including |
| 2 | Memory/disk hit/miss, tier promotion, Windows file lock cleanup |
| 2 | Schema compliance on first try, self-correcting retry on malformed JSON |
🛠 Tech Stack
Component | Technology | Purpose |
MCP Framework |
| Server SDK, tool registration, stdio transport |
LLM Client |
| OpenAI + Ollama-compatible API calls |
Validation |
| Typed schemas for all 23 tool outputs |
Configuration |
|
|
Templating |
| Prompt template rendering |
Memory Cache |
| In-memory TTL cache |
Disk Cache |
| SQLite-backed persistent cache |
Retry Logic |
| Exponential backoff for LLM API calls |
Testing |
| Async-compatible test framework |
📄 License
This project is provided as-is for educational and competitive programming purposes.
Available Tools
23 toolsanalyze_complexityB
Rigorously calculate time and space complexity of code.
Inputs: code (required), problem (required). Returns: object
choose_best_algorithmB
Select the single absolute best algorithm to implement for a problem.
Inputs: problem (required), candidates (required). Returns: object
compare_algorithmsB
Compare multiple candidate algorithms in a detailed pros/cons comparison.
Inputs: problem (required), candidates (required). Returns: object
detect_patternsC
Analyze problem text to detect patterns, difficulty, and complexity hints.
Inputs: problem (required), context. Returns: object
dry_runC
Perform a step-by-step trace execution of the code against test cases.
Inputs: code (required), problem (required). Returns: object
estimate_difficultyB
Estimate target audience and difficulty rating for the problem.
Inputs: problem (required). Returns: object
estimate_runtimeC
Estimate runtime safety by validating loops/nodes against constraints.
Inputs: problem (required), algorithm (required). Returns: object
explain_algorithmC
Explain the mechanics of a specific algorithm / data structure.
Inputs: problem (required), algorithm (required). Returns: object
extract_constraintsB
Extract variable constraints and time/memory limits.
Inputs: problem (required). Returns: object
find_bugB
Search for logical errors, boundary flaws, or runtime bugs in the code.
Inputs: code (required), problem (required). Returns: object
generate_edge_casesC
Identify critical edge case configurations and remedies.
Inputs: problem (required). Returns: object
generate_multi_languageA
Generate code solutions in C++, Java, and Rust.
Inputs: problem (required). Returns: object
generate_pseudocodeB
Generate language-agnostic pseudocode for the problem.
Inputs: problem (required). Returns: object
generate_solutionB
Generate an optimal solution for the problem in the requested language.
Inputs: problem (required), context, language. Returns: object
generate_testcasesC
Generate sample test cases (input/output/explanation) for the problem.
Inputs: problem (required). Returns: object
get_hintC
Provide progressive hints for the problem.
Inputs: problem (required), hint_level. Returns: object
identify_topicsA
Identify topics, tags, and prerequisites for the problem.
Inputs: problem (required). Returns: object
optimize_solutionC
Refactor solutions to reduce runtime complexity and improve performance.
Inputs: code (required), problem (required). Returns: object
prove_correctnessB
Verify correctness of an approach using loop invariants or mathematical proofs.
Inputs: problem (required). Returns: object
recommend_next_problemB
Recommend next problems that build upon this problem.
Inputs: problem (required). Returns: object
review_solutionB
Review user code for correctness, time complexity, bugs, TLE risk, etc.
Inputs: code (required), problem (required), language, error_message. Returns: object
stress_testingB
Generate stress testing script, random generator, and brute-force checker.
Inputs: problem (required). Returns: object
suggest_algorithmsB
Suggest multiple viable candidate algorithms or structures for the problem.
Inputs: problem (required). Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 23 tools
Each tool has a clear, distinct purpose, covering various aspects of competitive programming from analysis to code generation and debugging. No two tools appear to do the same thing.
All tool names follow a consistent snake_case verb_noun pattern (e.g., analyze_complexity, generate_solution, recommend_next_problem), making it easy for an agent to predict functionality.
23 tools is slightly above the typical ideal range, but given the broad scope of competitive programming mentoring (analysis, generation, testing, debugging, learning), it is justified and not excessive.
The tool set covers the full lifecycle of problem solving: understanding constraints, detecting patterns, selecting algorithms, generating solutions, testing, debugging, optimizing, and even recommending further practice. No obvious gaps.
Maintenance
Related MCP Connectors
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
33 tools that make AI write, implement, and verify intent against explicit, testable constraints.
30+ deterministic dev and delivery tools: linting, metrics, diagrams, model advice, AI-text checks.
AI-native git hosting — repos, PRs, issues, CI gates, and AI code review over MCP (60 tools).
Related MCP Servers
- AlicenseBqualityBmaintenanceA comprehensive development toolkit with 23 tools covering code quality analysis, development efficiency, and project management. Enables AI-assisted code review, test generation, performance analysis, SQL generation, UI component creation, and automated project documentation.829137 npm41MIT
- AlicenseNot gradedqualityDmaintenanceProvides AI assistants with 28 developer tools across file, git, code analysis, HTTP, and system domains, enabling tasks like file editing, repository management, code analysis, and shell command execution.2MIT
- FlicenseAqualityCmaintenanceEnables coding agents to discover unsolved Codeforces practice problems, analyze tag performance, and inspect submissions, profiles, rating history, and upcoming contests through MCP-compatible clients.6-
- AlicenseAqualityBmaintenanceConnects AI assistants to the Repovive competitive-programming platform, enabling them to browse problems and contests, judge and submit code for real verdicts, track ratings, communicate with users, and author verified problems and rounds.102MIT