Servidor MCTS MCP
Un servidor de Protocolo de Contexto de Modelo (MCP) que expone un motor de búsqueda de árbol de Monte Carlo bayesiano avanzado (MCTS) para análisis y razonamiento asistidos por IA.
Descripción general
Este servidor MCP permite a Claude utilizar algoritmos de búsqueda de árbol de Monte Carlo (MCTS) para realizar análisis exploratorios profundos de temas, preguntas o entradas de texto. El algoritmo MCTS utiliza un enfoque bayesiano para explorar sistemáticamente diferentes perspectivas e interpretaciones, generando análisis profundos que evolucionan a través de múltiples iteraciones.
Características
- MCTS bayesiano : utiliza un enfoque probabilístico para equilibrar la exploración frente a la explotación durante el análisis.
- Análisis de múltiples iteraciones : admite múltiples iteraciones de pensamiento con múltiples simulaciones por iteración.
- Persistencia del estado : recuerda resultados clave, enfoques no adecuados y anteriores entre turnos en el mismo chat.
- Taxonomía de enfoques : clasifica los pensamientos generados en diferentes enfoques y familias filosóficas.
- Muestreo de Thompson : se puede utilizar el muestreo de Thompson o UCT para la selección de nodos
- Detección de sorpresas : identifica direcciones de análisis sorprendentes o novedosas
- Clasificación de intención : comprende cuándo los usuarios desean iniciar un nuevo análisis o continuar uno anterior.
Uso
El servidor expone las numerosas herramientas para su LLM que se detallan a continuación en un formato que se puede copiar y pegar para el aviso de su sistema.
Cuando le pides a Claude que realice un análisis profundo sobre un tema o pregunta, aprovechará estas herramientas automáticamente para explorar diferentes ángulos utilizando el algoritmo MCTS y las herramientas de análisis.

Cómo funciona
El servidor MCP de MCTS utiliza un enfoque de inferencia local en lugar de intentar llamar directamente al LLM. Esto es compatible con el protocolo MCP, diseñado para que las herramientas sean llamadas por un asistente de IA (como Claude), en lugar de que las herramientas llamen al modelo de IA por sí mismas.
Cuando Claude le pide al servidor que realice un análisis, el servidor:
- Inicializa el sistema MCTS con la pregunta
- Ejecuta múltiples iteraciones de exploración utilizando el algoritmo MCTS
- Genera respuestas deterministas para diversas tareas analíticas.
- Devuelve el mejor análisis encontrado durante la búsqueda.
Instalación
Clonar el repositorio:
La configuración utiliza UV (Astral UV), una alternativa más rápida a pip que ofrece una resolución de dependencia mejorada.
- Asegúrese de tener instalado Python 3.10+
- Ejecute el script de configuración:
Esto hará lo siguiente:
- Instalar UV si aún no está instalado
- Crea un entorno virtual con UV
- Instale los paquetes necesarios mediante UV
- Crear el directorio de estado necesario
Alternativamente, puede configurar manualmente:
# Install UV if not already installed
curl -fsSL https://astral.sh/uv/install.sh | bash
# Create and activate a virtual environment
uv venv .venv
source .venv/bin/activate
# Install dependencies
uv pip install -r requirements.txt
Integración de escritorio de Claude
Para integrar con Claude Desktop:
- Copia el contenido de
claude_desktop_config.json
desde este repositorio - Agréguelo a su configuración de Claude Desktop (normalmente ubicado en
~/.claude/claude_desktop_config.json
) - Si el archivo de configuración aún no existe, créelo y agregue el contenido de
claude_desktop_config.json
de este proyecto - Reiniciar Claude Desktop
Ejemplo de configuración:
{
"mcpServers": {
"MCTSServer": {
"command": "uv",
"args": [
"run",
"--directory", "/home/ty/Repositories/ai_workspace/mcts-mcp-server/src/mcts_mcp_server",
"server.py"
],
"env": {
"PYTHONPATH": "/home/ty/Repositories/ai_workspace/mcts-mcp-server"
}
}
}
}
Asegúrese de actualizar las rutas para que coincidan con la ubicación del servidor MCTS MCP en su sistema.
Mensaje de sistema sugerido y herramientas actualizadas , incluida la integración de Ollama, es decir, coloque el siguiente bloque en las instrucciones de su proyecto:
MCTS server and usage instructions:
MCTS server and usage instructions:
list_ollama_models() # Check what models are available
set_ollama_model("cogito:latest") # Set the model you want to use
initialize_mcts(question="Your question here", chat_id="unique_id") # Initialize analysis
run_mcts(iterations=1, simulations_per_iteration=5) # Run the analysis
After run_mcts is called it can take wuite a long time ie minutes to hours
- so you may discuss any ideas or questions or await user confirmation of the process finishing,
- then proceed to synthesis and analysis tools on resumption of chat.
## MCTS-MCP Tools Overview
### Core MCTS Tools:
- `initialize_mcts`: Start a new MCTS analysis with a specific question
- `run_mcts`: Run the MCTS algorithm for a set number of iterations/simulations
- `generate_synthesis`: Generate a final summary of the MCTS results
- `get_config`: View current MCTS configuration parameters
- `update_config`: Update MCTS configuration parameters
- `get_mcts_status`: Check the current status of the MCTS system
Default configuration prioritizes speed and exploration, but you can customize parameters like exploration_weight, beta_prior_alpha/beta, surprise_threshold.
## Configuration
You can customize the MCTS parameters in the config dictionary or through Claude's `update_config` tool. Key parameters include:
- `max_iterations`: Number of MCTS iterations to run
- `simulations_per_iteration`: Number of simulations per iteration
- `exploration_weight`: Controls exploration vs. exploitation balance (in UCT)
- `early_stopping`: Whether to stop early if a high-quality solution is found
- `use_bayesian_evaluation`: Whether to use Bayesian evaluation for node scores
- `use_thompson_sampling`: Whether to use Thompson sampling for selection
Articulating Specific Pathways:
Delving into the best_path nodes (using mcts_instance.get_best_path_nodes() if you have the instance) and examining the sequence of thought and content
at each step can provide a fascinating micro-narrative of how the core insight evolved.
Visualizing the tree (even a simplified version based on export_tree_summary) could also be illuminating and I will try to set up this feature.
Modifying Parameters: This is a great way to test the robustness of the finding or explore different "cognitive biases" of the system.
Increasing Exploration Weight: Might lead to more diverse, less obviously connected ideas.
Decreasing Exploration Weight: Might lead to deeper refinement of the initial dominant pathways.
Changing Priors (if Bayesian): You could bias the system towards certain approaches (e.g., increase alpha for 'pragmatic') to see how it influences the
outcome.
More Iterations/Simulations: Would allow for potentially deeper convergence or exploration of more niche pathways.
### Ollama Integration Tools:
- `list_ollama_models`: Show all available local Ollama models
- `set_ollama_model`: Select which Ollama model to use for MCTS
- `run_model_comparison`: Run the same MCTS process across multiple models
### Results Collection:
- Automatically stores results in `/home/ty/Repositories/ai_workspace/mcts-mcp-server/results`
- Organizes by model name and run ID
- Stores metrics, progress info, and final outputs
# MCTS Analysis Tools
This extension adds powerful analysis tools to the MCTS-MCP Server, making it easy to extract insights and understand results from your MCTS runs.
The MCTS Analysis Tools provide a suite of integrated functions to:
1. List and browse MCTS runs
2. Extract key concepts, arguments, and conclusions
3. Generate comprehensive reports
4. Compare results across different runs
5. Suggest improvements for better performance
## Available Run Analysis Tools
### Browsing and Basic Information
- `list_mcts_runs(count=10, model=None)`: List recent MCTS runs with key metadata
- `get_mcts_run_details(run_id)`: Get detailed information about a specific run
- `get_mcts_solution(run_id)`: Get the best solution from a run
### Analysis and Insights
- `analyze_mcts_run(run_id)`: Perform a comprehensive analysis of a run
- `get_mcts_insights(run_id, max_insights=5)`: Extract key insights from a run
- `extract_mcts_conclusions(run_id)`: Extract conclusions from a run
- `suggest_mcts_improvements(run_id)`: Get suggestions for improvement
### Reporting and Comparison
- `get_mcts_report(run_id, format='markdown')`: Generate a comprehensive report (formats: 'markdown', 'text', 'html')
- `get_best_mcts_runs(count=5, min_score=7.0)`: Get the best runs based on score
- `compare_mcts_runs(run_ids)`: Compare multiple runs to identify similarities and differences
## Usage Examples
# To list your recent MCTS runs:
list_mcts_runs()
# To get details about a specific run:
get_mcts_run_details('cogito:latest_1745979984')
### Extracting Insights
# To get key insights from a run:
get_mcts_insights(run_id='cogito:latest_1745979984')
### Generating Reports
# To generate a comprehensive markdown report:
get_mcts_report(run_id='cogito:latest_1745979984', format='markdown')
### Improving Results
# To get suggestions for improving a run:
suggest_mcts_improvements(run_id='cogito:latest_1745979984')
### Comparing Runs
To compare multiple runs:
compare_mcts_runs(['cogito:latest_1745979984', 'qwen3:0.6b_1745979584'])
## Understanding the Results
The analysis tools extract several key elements from MCTS runs:
1. **Key Concepts**: The core ideas and frameworks in the analysis
2. **Arguments For/Against**: The primary arguments on both sides of a question
3. **Conclusions**: The synthesized conclusions or insights from the analysis
4. **Tags**: Automatically generated topic tags from the content
## Troubleshooting
If you encounter any issues with the analysis tools:
1. Check that your MCTS run completed successfully (status: "completed")
2. Verify that the run ID you're using exists and is correct
3. Try listing all runs to see what's available: `list_mcts_runs()`
4. Make sure the `.best_solution.txt` file exists in the run's directory
## Advanced Example Usage
### Customizing Reports
You can generate reports in different formats:
# Generate a markdown report
report = get_mcts_report(run_id='cogito:latest_1745979984', format='markdown')
# Generate a text report
report = get_mcts_report(run_id='cogito:latest_1745979984', format='text')
# Generate an HTML report
report = get_mcts_report(run_id='cogito:latest_1745979984', format='html')
### Finding the Best Runs
To find your best-performing runs:
best_runs = get_best_mcts_runs(count=3, min_score=8.0)
This returns the top 3 runs with a score of at least 8.0.
## Simple Usage Instructions
1. **Changing Models**:
list_ollama_models() # See available models
set_ollama_model("qwen3:0.6b") # Set to fast small model
2. **Starting a New Analysis**:
initialize_mcts(question="Your question here", chat_id="unique_identifier")
3. **Running the Analysis**:
run_mcts(iterations=3, simulations_per_iteration=10)
4. **Comparing Performance**:
run_model_comparison(question="Your question", iterations=2)
5. **Getting Results**:
generate_synthesis() # Final summary of results
get_mcts_status() # Current status and metrics
Ejemplos de indicaciones
- Analizar las implicaciones de la inteligencia artificial en la creatividad humana.
- "Seguir explorando las dimensiones éticas de este tema"
- "¿Cuál fue el mejor análisis que encontraste en la última ejecución?"
- ¿Cómo funciona este proceso MCTS?
- "Muéstrame la configuración actual de MCTS"

Para desarrolladores
# Activate virtual environment
source .venv/bin/activate
# Run the server directly (for testing)
uv run server.py
# OR use the MCP CLI tools
uv run -m mcp dev server.py
Probando el servidor
Para probar que el servidor está funcionando correctamente:
# Activate the virtual environment
source .venv/bin/activate
# Run the test script
python test_server.py
Esto probará el adaptador LLM para garantizar que funcione correctamente.
Contribuyendo
Se agradecen las contribuciones para mejorar el servidor MCP de MCTS. Algunas áreas de mejora potenciales:
- Mejorar el adaptador de inferencia local para un análisis más sofisticado
- Añadir patrones de pensamiento y estrategias de evaluación más sofisticados
- Mejorar la visualización del árbol y los informes de resultados
- Optimización de los parámetros del algoritmo MCTS
Licencia: MIT