https://github.com/1999azzar/trmengine
TrmEngine is a recursive reasoning server that implements logic validation using latent space computation. It provides structured reasoning capabilities through recursive refinement of logical arguments.
https://github.com/1999azzar/trmengine
Last synced: 2 months ago
JSON representation
TrmEngine is a recursive reasoning server that implements logic validation using latent space computation. It provides structured reasoning capabilities through recursive refinement of logical arguments.
- Host: GitHub
- URL: https://github.com/1999azzar/trmengine
- Owner: 1999AZZAR
- Created: 2026-01-10T08:52:37.000Z (6 months ago)
- Default Branch: master
- Last Pushed: 2026-01-10T09:23:41.000Z (6 months ago)
- Last Synced: 2026-01-11T02:53:59.471Z (6 months ago)
- Language: Python
- Homepage:
- Size: 81.1 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# TrmEngine
TrmEngine is a recursive reasoning server that implements logic validation using latent space computation. It provides structured reasoning capabilities through recursive refinement of logical arguments.
[](https://www.python.org/downloads/)
[](https://onnxruntime.ai/)
[](https://modelcontextprotocol.io/)
## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Architecture](#architecture)
- [Installation](#installation)
- [Configuration](#configuration)
- [API Reference](#api-reference)
- [Tool Specifications](#tool-specifications)
- [MCP Resources](#mcp-resources)
- [REST API Endpoints](#rest-api-endpoints)
- [Integration Options](#integration-options)
- [Usage Examples](#usage-examples)
- [Model Training](#model-training)
- [Performance](#performance)
- [Troubleshooting](#troubleshooting)
- [Research Foundation](#research-foundation)
- [Contributing](#contributing)
- [License](#license)
## Overview
TrmEngine is a comprehensive recursive reasoning server that implements logic validation using latent space computation. It provides structured reasoning capabilities through recursive refinement of logical arguments and serves as a complete MCP (Model Context Protocol) server.
## Features
### π§ **Core Capabilities**
- **Recursive Reasoning**: Advanced logical validation through latent space computation
- **Confidence Scoring**: Quantitative assessment of reasoning quality and convergence
- **Domain Adaptation**: Specialized reasoning for mathematical, logical, and causal domains
- **Action Verification**: Gatekeeper functionality for proposed conclusions
### π οΈ **MCP Integration**
- **3 Specialized Tools**: `logical_recursion`, `state_verification`, `latent_projection`
- **5 Rich Resources**: Documentation, configuration, health status, examples, and model information
- **JSON-RPC 2.0**: Full protocol compliance with proper error handling
- **Cursor Compatible**: Seamless integration with Cursor and other MCP clients
### π **Performance**
- **Low Latency**: 150-300ms typical response times
- **Memory Efficient**: < 100MB memory usage
- **Scalable**: Configurable recursion depth and embedding dimensions
- **Reliable**: Comprehensive error handling and validation
### π― **Use Cases**
- **LLM Validation**: Verify reasoning accuracy in language models
- **Mathematical Proofs**: Validate logical consistency in mathematical arguments
- **Research Analysis**: Assess quality of logical arguments in academic work
- **Decision Support**: Provide confidence scores for critical reasoning tasks
## Architecture
### System Design
TrmEngine implements the official Model Context Protocol (MCP) with structured reasoning tools:
```
Language Model β MCP Protocol β Validation Engine β Recursive Reasoning β Response
```
The system uses JSON-RPC 2.0 for communication, providing three specialized reasoning tools with comprehensive input validation and recursive logic processing.
### Core Components
#### MCPServer
- **Protocol Implementation**: Official MCP specification with JSON-RPC 2.0
- **Transport Layer**: Stdio-based communication with proper message framing
- **Tool Registry**: Manages 3 specialized reasoning tools with schema validation
- **Resource System**: Provides 5 rich resources for documentation and monitoring
- **Client Management**: Handles capability negotiation and connection lifecycle
- **Error Handling**: Robust error responses with proper JSON-RPC formatting
#### TRMLogicCore
- **Recursive Engine**: Implements Tiny Recursive Model logic for reasoning
- **Latent Computation**: Vector-based processing with convergence analysis
- **Confidence Metrics**: Quantitative assessment using stability and entropy measures
- **Performance Optimization**: Efficient numpy-based operations
- **Flexible Configuration**: Adjustable recursion depth and embedding dimensions
#### TextLatentBridge
- **Text Encoding**: Converts natural language to semantic vector representations
- **Feature Extraction**: Identifies logical structures and reasoning patterns
- **Latent Decoding**: Transforms vector states to human-readable assessments
- **Domain Adaptation**: Specialized processing for mathematical, logical, and causal reasoning
- **Quality Analysis**: Automated evaluation of argument coherence and validity
#### Validation Layer
- **Schema Validation**: Zod-inspired input validation with detailed error messages
- **Type Safety**: Comprehensive type checking for all API parameters
- **Constraint Enforcement**: Business logic validation and bounds checking
- **Security**: Input sanitization and safe parameter handling
- **Recovery**: Graceful error handling with informative feedback
## Installation
### System Requirements
- Python 3.13 or higher
- uv package manager
- Linux distribution (tested on Debian 13)
- MCP-compatible client (Claude Desktop, etc.)
### Package Manager Installation
Install uv if not already available:
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
### Project Setup
1. Clone or download the project files:
```bash
cd /path/to/TrmEngine
```
2. Install dependencies:
```bash
uv sync
```
3. Verify installation:
```bash
uv run python -c "import trmengine; print('Installation successful')"
```
### MCP Server Setup
The TrmEngine MCP server uses stdio transport for communication with MCP clients. Configure your MCP client (like Claude Desktop) to use the server:
```json
{
"mcpServers": {
"trm-engine": {
"command": "uv",
"args": ["run", "--project", "/path/to/TrmEngine", "python", "-m", "trmengine.server"],
"env": {
"TRM_MODEL_PATH": "./models/trm_v1.onnx",
"RECURSION_LIMIT": "16",
"EMBEDDING_DIM": "512"
}
}
}
}
```
### Alternative Installation Methods
#### Editable Installation
For development work:
```bash
uv pip install -e .
```
#### Distribution Build
To create distributable packages:
```bash
uv build
```
This creates wheel and source distribution files in the `dist/` directory.
## Configuration
### Environment Variables
TrmEngine behavior can be customized through environment variables:
| Variable | Default | Description |
| ------------------- | ------------------------ | ------------------------------------ |
| `TRM_MODEL_PATH` | `./models/trm_v1.onnx` | Path to ONNX model file (optional) |
| `RECURSION_LIMIT` | `16` | Number of recursive refinement steps |
| `EMBEDDING_DIM` | `512` | Dimension of latent embedding space |
### Claude Desktop Integration
To integrate with Claude Desktop via MCP:
1. Locate your MCP configuration file:
- Linux/macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%/Claude/claude_desktop_config.json`
2. Add the TrmEngine server configuration:
```json
{
"mcpServers": {
"trm-engine": {
"command": "uv",
"args": ["run", "--project", "/absolute/path/to/TrmEngine", "python", "-m", "trmengine.main"],
"env": {
"TRM_MODEL_PATH": "./models/trm_v1.onnx",
"RECURSION_LIMIT": "16",
"EMBEDDING_DIM": "512"
}
}
}
}
```
3. Restart Claude Desktop to load the configuration.
### Model Configuration
TrmEngine uses a functional implementation by default. To use a custom ONNX model:
1. Place your model file in the project directory or set the `TRM_MODEL_PATH` environment variable
2. Ensure the model accepts inputs: `x` (512), `y` (512), `z` (512)
3. The model should output: `z_new` (512), `y_new` (512)
If no model file is found, TrmEngine automatically uses its built-in functional implementation.
## API Reference
### Tool Specifications
#### logical_recursion
Performs recursive reasoning validation on logical arguments.
**Input Parameters:**
| Parameter | Type | Required | Default | Description |
| ------------------- | ------- | -------- | ------- | ------------------------------------ |
| `thought` | string | Yes | - | The logical argument to validate |
| `context` | string | No | null | Additional context for the reasoning |
| `recursion_depth` | integer | No | 16 | Number of recursive refinement steps |
**Response Format:**
```json
{
"original_thought": "input argument text",
"context": "provided context",
"refined_state": {
"status": "LOGIC_VERIFIED | LOGIC_WARNING | LOGIC_UNCERTAIN",
"confidence": 0.0,
"convergence_score": 0.0,
"magnitude": 0.0,
"stability": 0.0,
"entropy": 0.0,
"logical_quality": 0.0
},
"assessment": "textual assessment of reasoning quality",
"recursion_steps": 16,
"latent_dimensions": 512
}
```
**Status Values:**
- `LOGIC_VERIFIED`: High confidence in logical validity
- `LOGIC_WARNING`: Moderate confidence, potential issues
- `LOGIC_UNCERTAIN`: Low confidence, significant concerns
#### state_verification
Validates proposed actions against previously verified reasoning states.
**Input Parameters:**
| Parameter | Type | Required | Default | Description |
| --------------------- | ------ | -------- | ------- | ------------------------------ |
| `proposed_action` | string | Yes | - | Action or conclusion to verify |
| `trm_refined_state` | object | Yes | - | Output from logical_recursion |
| `threshold` | float | No | 0.85 | Minimum confidence threshold |
**Response Format:**
```json
{
"proposed_action": "action description",
"verification_result": "VERIFIED | CONDITIONAL | REJECTED",
"approved": true,
"confidence_score": 0.0,
"threshold_used": 0.85,
"message": "human-readable verification result",
"trm_state_summary": {
"status": "original reasoning status",
"original_assessment": "original assessment text"
}
}
```
#### latent_projection
Applies logical constraints to reasoning processes within specific domains.
**Input Parameters:**
| Parameter | Type | Required | Default | Description |
| ----------------------- | ------ | -------- | ------- | ------------------------------------- |
| `constraints` | string | Yes | - | Logical constraints to apply |
| `target_domain` | string | No | null | Domain: mathematical, logical, causal |
| `projection_strength` | float | No | 0.8 | Strength of constraint application |
**Response Format:**
```json
{
"constraints": "constraint text",
"target_domain": "domain name",
"projection_strength": 0.8,
"projected_latent": {
"shape": [512],
"magnitude": 0.0,
"stability": 0.0
},
"refined_state": {
"status": "constraint validation status",
"confidence": 0.0,
"convergence_score": 0.0
},
"proven_path": "textual summary of constraint validation",
"assessment": "detailed assessment of constraint application"
}
```
### MCP Resources
TrmEngine provides 5 rich resources for enhanced discoverability and documentation access:
#### Available Resources
| URI | MIME Type | Description |
|-----|-----------|-------------|
| `trm://docs/readme` | `text/markdown` | Complete TrmEngine documentation |
| `trm://config/current` | `application/json` | Current server configuration |
| `trm://status/health` | `application/json` | Server health and performance metrics |
| `trm://examples/basic` | `application/json` | Usage examples and test cases |
| `trm://model/info` | `application/json` | Model capabilities and information |
#### Resource Access
**List Resources:**
```bash
# Via MCP
{"jsonrpc": "2.0", "id": 1, "method": "resources/list"}
# Response
{
"result": {
"resources": [
{
"uri": "trm://docs/readme",
"mimeType": "text/markdown",
"name": "TrmEngine README",
"description": "Complete TrmEngine documentation and usage guide"
}
// ... more resources
]
}
}
```
**Read Resource:**
```bash
# Via MCP
{"jsonrpc": "2.0", "id": 2, "method": "resources/read", "params": {"uri": "trm://config/current"}}
# Response
{
"result": {
"contents": [{
"uri": "trm://config/current",
"mimeType": "application/json",
"text": "{\"model_path\": \"default (functional)\", \"recursion_limit\": 16, ...}"
}]
}
}
```
#### Resource Content Examples
**Configuration Resource:**
```json
{
"model_path": "default (functional)",
"recursion_limit": 16,
"embedding_dim": 512,
"server_version": "0.1.0",
"capabilities": ["tools", "resources", "prompts"],
"tools_count": 3,
"resources_count": 5
}
```
**Health Status Resource:**
```json
{
"status": "healthy",
"timestamp": "2026-01-10T16:00:00Z",
"uptime": "00:30:00",
"memory_usage": "85MB",
"active_connections": 1,
"total_requests": 42,
"error_rate": 0.0,
"last_error": null
}
```
### REST API Endpoints
When running the API server (`uv run python -m trmengine.api_server`), the following HTTP endpoints are available:
- `GET /health` - Server health check
- `GET /docs` - Interactive API documentation
- `POST /logical-recursion` - Logical reasoning validation
- `POST /state-verification` - Action verification
- `POST /latent-projection` - Constraint projection
All POST endpoints accept JSON request bodies matching the parameter specifications above.
## Integration Options
TrmEngine supports multiple integration approaches depending on your use case and platform requirements.
### MCP Protocol (Cursor & Claude Desktop) β **RECOMMENDED**
**Best for:** Native integration with Cursor, Claude Desktop, and other MCP-compatible clients
**Capabilities:**
- β
**3 Tools**: `logical_recursion`, `state_verification`, `latent_projection`
- β
**5 Resources**: Documentation, configuration, health status, examples, model info
- β
**Full MCP Support**: JSON-RPC 2.0 with proper error handling
**Setup:**
1. Copy the `mcp.json` configuration file to your MCP config directory:
- **Cursor**: `~/.cursor/mcp.json`
- **Claude Desktop**: `~/Library/Application Support/Claude/claude_desktop_config.json`
2. The configuration file should contain:
```json
{
"mcpServers": {
"trm-engine": {
"command": "uv",
"args": ["run", "--project", "/path/to/TrmEngine", "python", "-m", "trmengine.main"],
"env": {
"TRM_MODEL_PATH": "/path/to/models/trm_v1.onnx",
"RECURSION_LIMIT": "16",
"EMBEDDING_DIM": "512"
}
}
}
}
```
**What Cursor/Claude Will See:**
- **Tools**: 3 reasoning tools with full schema documentation
- **Resources**: 5 discoverable resources for documentation and status
- **Health**: Real-time server monitoring and diagnostics
- **Examples**: Built-in usage examples and test cases
**Usage:**
```bash
# Tools are automatically available in Cursor/Claude conversations
# Resources can be accessed via MCP resource browsing
```
### Python Client Library
**Best for:** Direct integration in Python applications
**Setup:**
```python
from trmengine.standalone_client import get_trm_client
```
**Usage:**
```python
import asyncio
from trmengine.standalone_client import get_trm_client
async def validate_reasoning():
client = get_trm_client()
result = await client.logical_recursion(
thought="If all humans are mortal and Socrates is human, then Socrates is mortal",
context="syllogistic reasoning"
)
print(f"Status: {result['refined_state']['status']}")
print(f"Confidence: {result['refined_state']['confidence']:.3f}")
asyncio.run(validate_reasoning())
```
### REST API Server
**Best for:** Integration with any programming language or web application
**Setup:**
```bash
uv run python -m trmengine.api_server
```
**Usage:**
```python
import requests
# Validate logical reasoning
response = requests.post("http://localhost:8000/logical-recursion", json={
"thought": "All men are mortal. Socrates is a man. Therefore Socrates is mortal.",
"context": "syllogistic logic"
})
result = response.json()
print(f"Status: {result['refined_state']['status']}")
print(f"Confidence: {result['refined_state']['confidence']:.3f}")
```
### Direct Component Usage
**Best for:** Custom implementations and advanced use cases
**Setup:**
```python
from trmengine.core import TRMLogicCore, TextLatentBridge
core = TRMLogicCore()
bridge = TextLatentBridge()
```
## Usage Examples
### Basic Reasoning Validation
Validate a logical argument:
```python
from trmengine.standalone_client import get_trm_client
import asyncio
async def example():
client = get_trm_client()
# Validate syllogistic reasoning
result = await client.logical_recursion(
thought="All mammals are animals. Dogs are mammals. Therefore dogs are animals.",
context="categorical syllogism"
)
print(f"Validation: {result['refined_state']['status']}")
print(f"Confidence: {result['refined_state']['confidence']:.3f}")
asyncio.run(example())
```
### Multi-Step Reasoning Chain
Combine multiple validation steps:
```python
async def reasoning_chain():
client = get_trm_client()
# Step 1: Validate premise
premise_result = await client.logical_recursion(
thought="All mathematical theorems require proof.",
context="mathematical logic"
)
# Step 2: Apply domain constraints
constraints = await client.latent_projection(
constraints="Proofs must use valid logical inference rules",
target_domain="mathematical"
)
# Step 3: Verify conclusion
verification = await client.state_verification(
proposed_action="Accept that theorems need proofs",
trm_refined_state=premise_result
)
print(f"Chain result: {verification['verification_result']}")
asyncio.run(reasoning_chain())
```
### Web Application Integration
Integrate with web frameworks:
```python
# Flask example
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route('/validate-logic', methods=['POST'])
def validate_logic():
data = request.json
# Call TrmEngine API
response = requests.post("http://localhost:8000/logical-recursion", json=data)
result = response.json()
return jsonify(result)
if __name__ == '__main__':
app.run()
```
### Batch Processing
Process multiple arguments:
```python
async def batch_validation():
client = get_trm_client()
arguments = [
"All birds can fly. Penguins are birds. Therefore penguins can fly.",
"2 + 2 = 4",
"This statement is false."
]
for arg in arguments:
result = await client.logical_recursion(thought=arg)
quality = result['refined_state']['logical_quality']
print(f"'{arg[:30]}...': Quality {quality:.3f}")
asyncio.run(batch_validation())
```
### Error Handling
Handle validation failures gracefully:
```python
async def robust_validation():
client = get_trm_client()
try:
result = await client.logical_recursion(
thought="Complex logical argument here...",
context="advanced reasoning"
)
if result.get('error'):
print(f"Validation error: {result['error']}")
return None
status = result['refined_state']['status']
confidence = result['refined_state']['confidence']
if status == 'LOGIC_VERIFIED' and confidence > 0.8:
print("Strong logical argument")
elif status == 'LOGIC_WARNING':
print("Argument needs review")
else:
print("Weak logical argument")
except Exception as e:
print(f"Processing error: {e}")
asyncio.run(robust_validation())
```
## Model Training
TrmEngine includes a functional TRM implementation by default. For advanced use cases, you can train custom models using the Samsung TinyRecursiveModels framework.
### Using Pre-trained Models
1. **Download the framework:**
```bash
git clone https://github.com/SamsungSAILMontreal/TinyRecursiveModels.git
cd TinyRecursiveModels
pip install -r requirements.txt
```
2. **Train a model:**
```bash
# Example training command for ARC tasks
python pretrain.py \
--task arc1 \
--model_size small \
--max_epochs 100 \
--batch_size 32
```
3. **Export trained model to ONNX:**
```python
import torch
from models.trm import TinyRecursiveModel
# Load trained model
model = TinyRecursiveModel(embed_dim=512, hidden_dim=256)
model.load_state_dict(torch.load('path/to/trained_model.pth'))
model.eval()
# Create dummy inputs matching TrmEngine interface
dummy_input = {
'x': torch.randn(1, 512),
'y': torch.randn(1, 512),
'z': torch.randn(1, 512)
}
# Export to ONNX
torch.onnx.export(
model,
(dummy_input['x'], dummy_input['y'], dummy_input['z']),
'trm_v1.onnx',
input_names=['x', 'y', 'z'],
output_names=['z_new', 'y_new'],
dynamic_axes={
'x': {0: 'batch_size'},
'y': {0: 'batch_size'},
'z': {0: 'batch_size'},
'z_new': {0: 'batch_size'},
'y_new': {0: 'batch_size'}
},
opset_version=11
)
```
4. **Configure TrmEngine:**
```bash
export TRM_MODEL_PATH="/path/to/trm_v1.onnx"
```
### Model Requirements
For compatibility with TrmEngine, ONNX models must:
- Accept three inputs: `x`, `y`, `z` (each shape [batch_size, 512])
- Return two outputs: `z_new`, `y_new` (each shape [batch_size, 512])
- Use ONNX opset version 11 or compatible
### Built-in Implementation
By default, TrmEngine uses a functional implementation that provides:
- Recursive reasoning without external model dependencies
- Content-aware logical analysis
- Confidence scoring based on convergence analysis
- Support for domain-specific adaptations
The built-in implementation is suitable for most use cases and does not require model training.
## Performance
### System Requirements
- **Memory**: 100MB RAM minimum, 200MB recommended
- **Storage**: 50MB for installation
- **CPU**: Any modern processor (no GPU required)
- **Network**: None (runs locally)
### Performance Characteristics
| Operation | Typical Time | Memory Usage |
| -------------------------- | ------------ | ------------ |
| Text encoding | < 5ms | < 10MB |
| Single recursion step | ~10ms | < 50MB |
| Full validation (16 steps) | ~150ms | < 100MB |
| API request/response | < 200ms | < 50MB |
| MCP resource access | < 50ms | < 20MB |
| Health check (ping) | < 10ms | < 5MB |
### Configuration Impact
- **Recursion Depth**: Higher values improve accuracy but increase processing time
- **Embedding Dimension**: Larger dimensions provide better semantic understanding
- **Model Type**: ONNX models may be faster than built-in implementation
### Benchmark Results
Tested on Debian 13 with Intel i5 processor:
```
Logical validation (16 steps): 145ms average
State verification: 89ms average
Latent projection: 132ms average
Memory usage: 78MB peak
```
## Troubleshooting
### Installation Issues
#### Dependency Installation Fails
```bash
# Clear cache and reinstall
uv cache clean
uv sync --reinstall
```
#### Python Version Compatibility
Ensure Python 3.13+ is available:
```bash
python --version
uv python install 3.13
uv python pin 3.13
```
### Runtime Issues
#### Model Loading Problems
If you encounter model loading errors:
```bash
# Check if model file exists
ls -la $TRM_MODEL_PATH
# Verify ONNX model integrity
python -c "import onnxruntime as ort; ort.InferenceSession('$TRM_MODEL_PATH')"
```
#### API Server Won't Start
Check for port conflicts:
```bash
# Check if port 8000 is available
netstat -tlnp | grep :8000
# Use different port
PORT=8001 uv run python -m trmengine.api_server
```
#### Memory Issues
If you experience memory problems:
```bash
# Reduce embedding dimension
export EMBEDDING_DIM=256
# Reduce recursion depth
export RECURSION_LIMIT=8
```
### Integration Issues
#### MCP Configuration Problems
Validate MCP configuration:
```bash
# Check JSON syntax
python -m json.tool ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Verify paths exist
ls -la /path/to/TrmEngine
```
#### REST API Connection Issues
Test API connectivity:
```bash
# Check if server is running
curl http://localhost:8000/health
# Test with verbose output
curl -v http://localhost:8000/logical-recursion \
-H "Content-Type: application/json" \
-d '{"thought": "test"}'
```
### Validation Issues
#### Unexpected Validation Results
Debug validation process:
```python
# Enable detailed logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Test with simple input
from trmengine.standalone_client import get_trm_client
import asyncio
async def debug():
client = get_trm_client()
result = await client.logical_recursion("2 + 2 = 4")
print("Debug result:", result)
asyncio.run(debug())
```
#### Confidence Scores Not As Expected
Check input quality:
```python
# Test with different inputs
inputs = [
"Clear logical statement",
"Ambiguous statement",
"Contradictory statement"
]
for text in inputs:
result = await client.logical_recursion(text)
print(f"'{text}': {result['refined_state']['confidence']:.3f}")
```
### Development Issues
#### Testing Fails
Run tests individually:
```bash
# Run specific test
uv run python test_installation.py
# Run integration test
uv run python integration_demo.py
```
#### Import Errors During Development
Ensure proper Python path:
```bash
# Add project to path
export PYTHONPATH="/path/to/TrmEngine/src:$PYTHONPATH"
# Test import
python -c "import trmengine; print('OK')"
```
### Performance Optimization
#### Slow Response Times
Optimize configuration:
```bash
# Use smaller embedding dimension
export EMBEDDING_DIM=256
# Reduce recursion for faster responses
export RECURSION_LIMIT=8
# Use ONNX model if available (may be faster)
export TRM_MODEL_PATH="/path/to/model.onnx"
```
#### High Memory Usage
Monitor and optimize:
```bash
# Check memory usage
ps aux | grep trmengine
# Use lighter configuration
export EMBEDDING_DIM=256
export RECURSION_LIMIT=8
```
## Universal LLM Compatibility
**TrmEngine works with ANY LLM**, not just Claude! Here are the integration options:
### **For Grok, GPT, or Any LLM**
```bash
# Start TrmEngine API server
cd TrmEngine && uv run python -m trmengine.api_server
# Then any LLM can make HTTP requests:
curl -X POST http://localhost:8000/logical-recursion \
-H "Content-Type: application/json" \
-d '{"thought": "Your reasoning here", "context": "Optional context"}'
```
### **For Python Applications**
```python
from trmengine.standalone_client import get_trm_client
import asyncio
client = get_trm_client()
result = await client.logical_recursion("Your thought here")
```
### **For Claude Desktop (MCP)**
- Automatically configured in your `mcp.json`
- Native tool integration within Claude Desktop
### **For Web Applications**
- Deploy the REST API server
- Any frontend can call TrmEngine via HTTP
### **Integration Demo**
Run `uv run python integration_demo.py` to see all methods working!
---
## Research Foundation
This implementation is based on Samsung SAIL's research:
- **Paper**: ["Less is More: Recursive Reasoning with Tiny Networks"](https://arxiv.org/abs/2510.04871)
- **Code**: [SamsungSAILMontreal/TinyRecursiveModels](https://github.com/SamsungSAILMontreal/TinyRecursiveModels)
- **Video**: [Tiny AI Beats Giants! β Recursive Reasoning with Tiny Networks (TRM) Explained](https://www.youtube.com/watch?v=RujtTutVUaE)
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Summary
TrmEngine is a production-ready MCP server that provides advanced logical reasoning capabilities:
- **π§ Recursive Reasoning**: Based on Samsung's Tiny Recursive Model research
- **π§ 3 Specialized Tools**: Logical validation, action verification, constraint projection
- **π 5 Rich Resources**: Documentation, configuration, health monitoring, examples, model info
- **β‘ High Performance**: < 200ms response times, < 100MB memory usage
- **π Robust Validation**: Comprehensive input validation and error handling
- **π MCP Compliant**: Full JSON-RPC 2.0 implementation with proper protocol support
- **π₯οΈ Cursor Ready**: Seamless integration with Cursor and Claude Desktop
**Ready to enhance your AI reasoning workflows with structured logical validation!** π
## Acknowledgments
- **Samsung SAIL Montreal** for the Tiny Recursive Model research
- **Model Context Protocol** for the standardized tool integration framework
- **ONNX Runtime** for efficient model inference
---
**Raison d'Γͺtre**: A high-precision logic offloading server that replaces verbose Chain-of-Thought (CoT) with high-speed latent recursion.