logic-lm-mcp-server


Namelogic-lm-mcp-server JSON
Version 1.0.1 PyPI version JSON
download
home_pageNone
SummaryA Model Context Protocol server that provides symbolic reasoning capabilities using Logic-LM framework and Answer Set Programming
upload_time2025-08-28 21:36:54
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT License Copyright (c) 2024 Steven Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords answer-set-programming asp clingo logic mcp reasoning symbolic-solver
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Logic-LM MCP Server

A Model Context Protocol (MCP) server that provides symbolic reasoning capabilities using Logic-LM framework and Answer Set Programming (ASP).

## Attribution

This implementation is inspired by and builds upon the Logic-LLM framework:

**Original Research:**
- **Paper:** [Logic-LLM: Empowering Large Language Models with Symbolic Solvers for Faithful Logical Reasoning](https://arxiv.org/abs/2305.12295)
- **Repository:** [teacherpeterpan/Logic-LLM](https://github.com/teacherpeterpan/Logic-LLM)
- **Authors:** Liangming Pan, Alon Albalak, Xinyi Wang, William Yang Wang

This MCP server adapts the Logic-LLM approach for integration with Claude Code and other MCP clients, providing LLM-collaborative symbolic reasoning through Answer Set Programming.

## 🚀 Quick Start

### Prerequisites
- Python 3.8 or higher

### Installation

Choose your preferred installation method:

#### Option 1: Install from PyPI (Recommended) ✅ **LIVE ON PYPI**
```bash
# Install with pip
pip install logic-lm-mcp-server

# Or install with uv (10-100x faster)
uv pip install logic-lm-mcp-server
```

📦 **Package URL:** https://pypi.org/project/logic-lm-mcp-server/

#### Option 2: Install with Clingo solver (for full functionality)
```bash
# Install with optional solver
pip install logic-lm-mcp-server[solver]

# Or with uv
uv pip install logic-lm-mcp-server[solver]
```

#### Option 3: Development Installation
```bash
git clone https://github.com/stevenwangbe/logic-lm-mcp-server.git
cd logic-lm-mcp-server
pip install -e .
```

### Test Installation
```bash
logic-lm-mcp --help
```

### Integration with Claude Code

After installing the package, add it to your Claude Code configuration:

**Method 1: Using the console command (after PyPI installation)**
```bash
claude mcp add logic-lm-mcp logic-lm-mcp
```

**Method 2: Manual configuration**

Edit `~/.config/claude/claude_desktop_config.json` (create if it doesn't exist):

```json
{
  "mcpServers": {
    "logic-lm": {
      "command": "logic-lm-mcp"
    }
  }
}
```

**Restart Claude Code** to load the new MCP server.

3. **Test the integration:**

Try these commands in Claude Code:
```
Check Logic-LM server health
Translate this logic problem to ASP: "All birds can fly. Penguins are birds. Can penguins fly?"
```

### Alternative Integration (Other MCP Clients)

For other MCP-compatible tools, start the server manually:
```bash
python start_server.py
```

The server will run on stdio and provide these tools:
- `get_asp_guidelines` - Get ASP translation guidelines
- `translate_to_asp_instructions` - Get problem-specific ASP guidance
- `verify_asp_program` - Execute ASP programs with Clingo
- `check_solver_health` - Verify system health

## Overview

Logic-LM MCP Server converts natural language logical problems into Answer Set Programming (ASP) format, solves them using the Clingo solver, and returns human-readable results. It provides a three-stage reasoning pipeline: Problem Formulation → Symbolic Reasoning → Result Interpretation.

## Features

- **Natural Language Input**: Convert English logical problems to formal representations
- **ASP-Based Reasoning**: Uses Answer Set Programming for robust logical inference
- **Clingo Integration**: Leverages the Clingo ASP solver for symbolic reasoning
- **Self-Refinement**: Iterative improvement of solutions through multiple reasoning passes
- **Template Library**: Reusable ASP patterns for common logical structures
- **Fallback Handling**: Graceful degradation when solver components unavailable
- **FastMCP Integration**: Modern MCP server implementation with type safety

## Tools Provided

### 1. `get_asp_guidelines`
Get comprehensive ASP translation guidelines (cached for efficiency).

**Parameters:** None

**Returns:** Complete ASP Logic Translation Guidelines document with comprehensive instructions for translating natural language into Answer Set Programming format.

### 2. `translate_to_asp_instructions`  
Get lightweight instructions for translating a specific natural language problem to ASP.

**Parameters:**
- `problem` (string, required): Natural language logical problem to translate

**Example:**
```json
{
  "problem": "All cats are mammals. Fluffy is a cat. Is Fluffy a mammal?"
}
```

**Response:**
```json
{
  "success": true,
  "solution": "TRANSLATE TO ASP: All cats are mammals...\n\nINSTRUCTIONS:\n1. Call get_asp_guidelines() for complete patterns\n2. Analyze logical structure...",
  "confidence": 1.0,
  "method": "lightweight_translation_instructions",
  "metadata": {
    "problem_length": 58,
    "guidelines_cached": false,
    "next_steps": ["Call get_asp_guidelines() if needed", "Generate ASP code", "Call verify_asp_program()"]
  }
}
```

### 3. `verify_asp_program`
Directly verify and solve an ASP program using the Clingo solver.

**Parameters:**
- `program` (string, required): ASP program code to verify and solve
- `max_models` (integer, 1-100, default: 10): Maximum number of models to find

**Example:**
```json
{
  "program": "% Facts\ncat(fluffy).\n\n% Rule: All cats are mammals\nmammal(X) :- cat(X).\n\n% Query\n#show mammal/1.",
  "max_models": 10
}
```

### 4. `check_solver_health`
Check Logic-LM server and Clingo solver health status.

**Returns:**
- Server status and component initialization status
- Clingo availability and version information
- System capabilities and configuration details
- Basic functionality test results

## Architecture

### Core Components

1. **LogicFramework**: Main reasoning orchestrator
2. **ClingoSolver**: ASP solver interface and management  
3. **ASPTemplateLibrary**: Reusable logical pattern templates
4. **FastMCP Integration**: Modern MCP server implementation

### Processing Pipeline

```
Natural Language Input
         ↓
LLM Translation Instructions (Problem-specific guidance)
         ↓  
ASP Program Generation (LLM-driven with guidelines)
         ↓
Clingo Solver Execution
         ↓
Model Interpretation (Symbolic results)
         ↓
Human-Readable Output
```

## Dependencies

- **Python 3.8+**: Core runtime environment
- **FastMCP 2.0+**: Modern MCP server framework
- **Pydantic 2.0+**: Input validation and type safety
- **Clingo 5.8.0+**: ASP solver (automatically detects if missing)

## Installation

### Option 1: Using pip
```bash
pip install -r requirements.txt
```

### Option 2: Manual installation
```bash
pip install fastmcp>=2.0.0 pydantic>=2.0.0 clingo>=5.8.0
```

### Option 3: Development setup
```bash
git clone <repository-url>
cd logic-lm-mcp-server
pip install -e .
```

## Configuration

The server automatically handles:
- Clingo solver installation detection
- Template library loading
- Environment-specific optimizations
- Error recovery and fallback modes

### Environment Variables
- No environment variables required
- Server runs with sensible defaults

## Usage Examples

### Basic Logical Reasoning
```
Input: "If it's raining, then the ground is wet. It's raining. Is the ground wet?"
Output: "Yes, the ground is wet. This conclusion follows from modus ponens..."
```

### Syllogistic Reasoning  
```
Input: "All birds can fly. Penguins are birds. Can penguins fly?"
Output: "Based on the given premises, yes. However, this conflicts with real-world knowledge..."
```

### Set-Based Logic
```
Input: "All members of set A are in set B. X is in set A. Is X in set B?"
Output: "Yes, X is in set B. This follows from set inclusion transitivity..."
```

## Testing

### Basic Functionality Test
```bash
logic-lm-mcp --help
```

### Test MCP Integration
```bash
# Test with Claude Code
claude mcp get logic-lm
```

## Error Handling

- **Clingo Unavailable**: Provides informative error messages with installation guidance
- **Invalid ASP Programs**: Syntax checking with detailed error messages  
- **Solver Timeouts**: Graceful handling of complex problems
- **Resource Constraints**: Memory and time limit management

## Performance

- **Simple Problems**: 50-200ms response time
- **Complex Reasoning**: 200-1000ms with self-refinement
- **Memory Usage**: ~25MB base + ~1MB per concurrent request
- **Concurrent Support**: Multiple simultaneous reasoning requests

## Troubleshooting

### Common Issues

1. **"No module named 'pydantic'" or similar**
   - Install dependencies: `pip install -r requirements.txt`

2. **"Clingo not available"**
   - Install Clingo: `pip install clingo`
   - Server will run with limited functionality if Clingo is missing

3. **Server fails to start**
   - Check Python version: `python --version` (requires 3.8+)
   - Test installation: `logic-lm-mcp --help`

4. **MCP connection issues**
   - Verify MCP server configuration: `claude mcp get logic-lm`
   - Check installation: `logic-lm-mcp --help`

### Getting Help

1. Test installation: `logic-lm-mcp --help`
2. Check the health endpoint: use `check_solver_health` tool
3. Enable debug traces: set `include_trace=true` in requests

## FAQ - Common Setup Errors

### "Missing required dependencies" on startup

**Error:**
```
❌ Missing required dependencies:
  - fastmcp>=2.0.0
  - pydantic>=2.0.0
```

**Cause:** Dependencies not properly installed or virtual environment not activated.

**Solution:**
```bash
# Option 1: Use virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

# Option 2: Install globally
pip install -r requirements.txt

# Option 3: Use venv python directly
venv/bin/python start_server.py
```

### "ModuleNotFoundError: No module named 'fastmcp'"

**Error:**
```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'fastmcp'
```

**Cause:** Virtual environment not properly activated or dependencies not installed.

**Solution:**
```bash
# Clean installation
rm -rf venv/
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

### "ModuleNotFoundError: No module named 'pydantic'"

**Error:**
```
ModuleNotFoundError: No module named 'pydantic'
```

**Cause:** Missing core dependency, often from incomplete installation.

**Solution:**
```bash
pip install pydantic>=2.0.0
# Or reinstall all dependencies
pip install -r requirements.txt
```

### Virtual environment using system Python instead of venv Python

**Error:** Virtual environment is using the system Python instead of the isolated venv Python.

**Symptoms:**
- Packages installed globally instead of in venv
- Permission errors during package installation
- `which python` shows system path after activation
- Inconsistent behavior between development and production

**Causes:**
- Incorrect virtual environment activation
- Shell aliases overriding PATH (alias python, alias python3)
- Corrupted virtual environment
- PATH configuration issues

**Solutions:**

**Option 1: Verify and fix activation**
```bash
# Check if activation worked properly
source venv/bin/activate
which python  # Should show venv/bin/python, not /usr/bin/python

# If still showing system python, check for aliases
alias python
alias python3

# Remove problematic aliases
unalias python
unalias python3
```

**Option 2: Use explicit venv path (most reliable)**
```bash
# Instead of relying on activation, use direct paths
venv/bin/python -c "import sys; print(sys.executable)"
venv/bin/pip install package-name

# For our package specifically
venv/bin/python -c "from logic_lm_mcp import LogicFramework; print('✅ Works!')"
```

**Option 3: Recreate virtual environment**
```bash
# Clean recreation if venv is corrupted
rm -rf venv/
python3 -m venv venv
source venv/bin/activate
which python  # Verify it shows venv/bin/python
pip install logic-lm-mcp-server
```

**Option 4: Use absolute paths in shell**
```bash
# For Linux/Mac
/full/path/to/venv/bin/python script.py

# For Windows  
C:\full\path\to\venv\Scripts\python.exe script.py
```

### "Clingo not available" but everything else works

**Error:**
```
"clingo_available": false
```

**Cause:** Clingo ASP solver not installed.

**Solution:**
```bash
# Option 1: Via pip
pip install clingo>=5.8.0

# Option 2: Via conda
conda install -c conda-forge clingo

# Option 3: Check installation
python -c "import clingo; print('Clingo available')"
```

### Server starts but MCP tools not available

**Error:** MCP connection fails or tools not found.

**Cause:** Server not properly configured in Claude Code.

**Solution:**
1. Verify server is running: `python start_server.py`
2. Check Claude Code MCP configuration
3. Restart Claude Code if needed
4. Use absolute paths in configuration

### Python version compatibility issues

**Error:**
```
SyntaxError: invalid syntax
```

**Cause:** Python version < 3.8.

**Solution:**
```bash
# Check Python version
python --version  # Must be 3.8+

# Use specific Python version
python3.8 -m venv venv
# or
python3.9 -m venv venv
```

### Background process conflicts

**Error:** Server won't start, port already in use.

**Cause:** Previous server instance still running.

**Solution:**
```bash
# Kill existing processes
pkill -f start_server.py
pkill -f logic-lm

# Or find and kill specific process
ps aux | grep start_server
kill <process_id>
```

### File permission errors

**Error:**
```
PermissionError: [Errno 13] Permission denied
```

**Cause:** Insufficient file permissions.

**Solution:**
```bash
# Fix permissions
chmod +x start_server.py
chmod -R 755 src/

# Or run with appropriate permissions
sudo python start_server.py  # Not recommended
```

### Import path issues

**Error:**
```
ModuleNotFoundError: No module named 'src'
```

**Cause:** Python can't find local modules.

**Solution:**
```bash
# Run from project root directory
cd /path/to/logic-lm-mcp-server
python start_server.py

# Or use absolute imports
export PYTHONPATH="${PYTHONPATH}:$(pwd)"
```

### Cache or old dependency conflicts

**Error:** Server uses old logic after code changes.

**Cause:** Python bytecode cache or old dependencies.

**Solution:**
```bash
# Clear Python cache
find . -type d -name "__pycache__" -exec rm -rf {} +
find . -name "*.pyc" -delete

# Reinstall dependencies cleanly
rm -rf venv/
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# Restart Claude Code
```

### Memory or resource issues

**Error:** Server crashes or becomes unresponsive.

**Cause:** Insufficient system resources.

**Solution:**
- Close other applications to free memory
- Use smaller `max_models` parameter in requests
- Check system requirements (25MB base memory)
- Monitor server logs for resource warnings

## Development

### Project Structure
```
logic-lm-mcp-server/
├── src/
│   ├── __init__.py           # Package initialization
│   ├── logic_lm_mcp/
│   │   ├── __init__.py       # Package initialization
│   │   ├── main.py           # FastMCP server implementation
│   │   ├── logic_framework.py # Core Logic-LM framework
│   │   └── asp_templates.py   # ASP template library
├── pyproject.toml            # Modern Python packaging
├── requirements.txt          # Python dependencies
├── start_server.py          # Development server startup
└── README.md               # This documentation
```

### Adding New Templates

1. Edit `src/logic_lm_mcp/asp_templates.py`
2. Add new template to `_initialize_templates()` method
3. Test with `logic-lm-mcp --help` and MCP tools

### Extending Logic Framework

1. Edit `src/logic_lm_mcp/logic_framework.py`
2. Add new reasoning methods to `LogicFramework` class
3. Update FastMCP tools in `src/logic_lm_mcp/main.py`

## Resources

### ASP Templates
The server provides access to ASP templates via MCP resources:
- `asp-templates://list` - List all available templates
- `asp-templates://info/{template_name}` - Get template information
- `asp-templates://template/{template_name}` - Get template code

### Available Templates
- **universal**: Universal quantification (All X are Y)
- **conditional**: Conditional rules (If X then Y)
- **syllogism**: Basic syllogistic reasoning
- **existential**: Existential quantification (Some X are Y)
- **negation**: Negation patterns (No X are Y)
- **set_membership**: Set membership and relationships
- **transitive**: Transitive relationships

## License

MIT License - See LICENSE file for details.

## Support

For issues, feature requests, or questions about Logic-LM reasoning capabilities, please:

1. Test installation: `logic-lm-mcp --help`
2. Check the troubleshooting section above
3. Open an issue in the repository with:
   - Python version
   - Operating system
   - Error messages
   - Installation method used (pip/uv)
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "logic-lm-mcp-server",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "answer-set-programming, asp, clingo, logic, mcp, reasoning, symbolic-solver",
    "author": null,
    "author_email": "Steven Wang <stevenwangbe@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/d8/9d/268028301080759414de6c3f5b41931536d6a506569dc4e91a0e952f4d82/logic_lm_mcp_server-1.0.1.tar.gz",
    "platform": null,
    "description": "# Logic-LM MCP Server\n\nA Model Context Protocol (MCP) server that provides symbolic reasoning capabilities using Logic-LM framework and Answer Set Programming (ASP).\n\n## Attribution\n\nThis implementation is inspired by and builds upon the Logic-LLM framework:\n\n**Original Research:**\n- **Paper:** [Logic-LLM: Empowering Large Language Models with Symbolic Solvers for Faithful Logical Reasoning](https://arxiv.org/abs/2305.12295)\n- **Repository:** [teacherpeterpan/Logic-LLM](https://github.com/teacherpeterpan/Logic-LLM)\n- **Authors:** Liangming Pan, Alon Albalak, Xinyi Wang, William Yang Wang\n\nThis MCP server adapts the Logic-LLM approach for integration with Claude Code and other MCP clients, providing LLM-collaborative symbolic reasoning through Answer Set Programming.\n\n## \ud83d\ude80 Quick Start\n\n### Prerequisites\n- Python 3.8 or higher\n\n### Installation\n\nChoose your preferred installation method:\n\n#### Option 1: Install from PyPI (Recommended) \u2705 **LIVE ON PYPI**\n```bash\n# Install with pip\npip install logic-lm-mcp-server\n\n# Or install with uv (10-100x faster)\nuv pip install logic-lm-mcp-server\n```\n\n\ud83d\udce6 **Package URL:** https://pypi.org/project/logic-lm-mcp-server/\n\n#### Option 2: Install with Clingo solver (for full functionality)\n```bash\n# Install with optional solver\npip install logic-lm-mcp-server[solver]\n\n# Or with uv\nuv pip install logic-lm-mcp-server[solver]\n```\n\n#### Option 3: Development Installation\n```bash\ngit clone https://github.com/stevenwangbe/logic-lm-mcp-server.git\ncd logic-lm-mcp-server\npip install -e .\n```\n\n### Test Installation\n```bash\nlogic-lm-mcp --help\n```\n\n### Integration with Claude Code\n\nAfter installing the package, add it to your Claude Code configuration:\n\n**Method 1: Using the console command (after PyPI installation)**\n```bash\nclaude mcp add logic-lm-mcp logic-lm-mcp\n```\n\n**Method 2: Manual configuration**\n\nEdit `~/.config/claude/claude_desktop_config.json` (create if it doesn't exist):\n\n```json\n{\n  \"mcpServers\": {\n    \"logic-lm\": {\n      \"command\": \"logic-lm-mcp\"\n    }\n  }\n}\n```\n\n**Restart Claude Code** to load the new MCP server.\n\n3. **Test the integration:**\n\nTry these commands in Claude Code:\n```\nCheck Logic-LM server health\nTranslate this logic problem to ASP: \"All birds can fly. Penguins are birds. Can penguins fly?\"\n```\n\n### Alternative Integration (Other MCP Clients)\n\nFor other MCP-compatible tools, start the server manually:\n```bash\npython start_server.py\n```\n\nThe server will run on stdio and provide these tools:\n- `get_asp_guidelines` - Get ASP translation guidelines\n- `translate_to_asp_instructions` - Get problem-specific ASP guidance\n- `verify_asp_program` - Execute ASP programs with Clingo\n- `check_solver_health` - Verify system health\n\n## Overview\n\nLogic-LM MCP Server converts natural language logical problems into Answer Set Programming (ASP) format, solves them using the Clingo solver, and returns human-readable results. It provides a three-stage reasoning pipeline: Problem Formulation \u2192 Symbolic Reasoning \u2192 Result Interpretation.\n\n## Features\n\n- **Natural Language Input**: Convert English logical problems to formal representations\n- **ASP-Based Reasoning**: Uses Answer Set Programming for robust logical inference\n- **Clingo Integration**: Leverages the Clingo ASP solver for symbolic reasoning\n- **Self-Refinement**: Iterative improvement of solutions through multiple reasoning passes\n- **Template Library**: Reusable ASP patterns for common logical structures\n- **Fallback Handling**: Graceful degradation when solver components unavailable\n- **FastMCP Integration**: Modern MCP server implementation with type safety\n\n## Tools Provided\n\n### 1. `get_asp_guidelines`\nGet comprehensive ASP translation guidelines (cached for efficiency).\n\n**Parameters:** None\n\n**Returns:** Complete ASP Logic Translation Guidelines document with comprehensive instructions for translating natural language into Answer Set Programming format.\n\n### 2. `translate_to_asp_instructions`  \nGet lightweight instructions for translating a specific natural language problem to ASP.\n\n**Parameters:**\n- `problem` (string, required): Natural language logical problem to translate\n\n**Example:**\n```json\n{\n  \"problem\": \"All cats are mammals. Fluffy is a cat. Is Fluffy a mammal?\"\n}\n```\n\n**Response:**\n```json\n{\n  \"success\": true,\n  \"solution\": \"TRANSLATE TO ASP: All cats are mammals...\\n\\nINSTRUCTIONS:\\n1. Call get_asp_guidelines() for complete patterns\\n2. Analyze logical structure...\",\n  \"confidence\": 1.0,\n  \"method\": \"lightweight_translation_instructions\",\n  \"metadata\": {\n    \"problem_length\": 58,\n    \"guidelines_cached\": false,\n    \"next_steps\": [\"Call get_asp_guidelines() if needed\", \"Generate ASP code\", \"Call verify_asp_program()\"]\n  }\n}\n```\n\n### 3. `verify_asp_program`\nDirectly verify and solve an ASP program using the Clingo solver.\n\n**Parameters:**\n- `program` (string, required): ASP program code to verify and solve\n- `max_models` (integer, 1-100, default: 10): Maximum number of models to find\n\n**Example:**\n```json\n{\n  \"program\": \"% Facts\\ncat(fluffy).\\n\\n% Rule: All cats are mammals\\nmammal(X) :- cat(X).\\n\\n% Query\\n#show mammal/1.\",\n  \"max_models\": 10\n}\n```\n\n### 4. `check_solver_health`\nCheck Logic-LM server and Clingo solver health status.\n\n**Returns:**\n- Server status and component initialization status\n- Clingo availability and version information\n- System capabilities and configuration details\n- Basic functionality test results\n\n## Architecture\n\n### Core Components\n\n1. **LogicFramework**: Main reasoning orchestrator\n2. **ClingoSolver**: ASP solver interface and management  \n3. **ASPTemplateLibrary**: Reusable logical pattern templates\n4. **FastMCP Integration**: Modern MCP server implementation\n\n### Processing Pipeline\n\n```\nNatural Language Input\n         \u2193\nLLM Translation Instructions (Problem-specific guidance)\n         \u2193  \nASP Program Generation (LLM-driven with guidelines)\n         \u2193\nClingo Solver Execution\n         \u2193\nModel Interpretation (Symbolic results)\n         \u2193\nHuman-Readable Output\n```\n\n## Dependencies\n\n- **Python 3.8+**: Core runtime environment\n- **FastMCP 2.0+**: Modern MCP server framework\n- **Pydantic 2.0+**: Input validation and type safety\n- **Clingo 5.8.0+**: ASP solver (automatically detects if missing)\n\n## Installation\n\n### Option 1: Using pip\n```bash\npip install -r requirements.txt\n```\n\n### Option 2: Manual installation\n```bash\npip install fastmcp>=2.0.0 pydantic>=2.0.0 clingo>=5.8.0\n```\n\n### Option 3: Development setup\n```bash\ngit clone <repository-url>\ncd logic-lm-mcp-server\npip install -e .\n```\n\n## Configuration\n\nThe server automatically handles:\n- Clingo solver installation detection\n- Template library loading\n- Environment-specific optimizations\n- Error recovery and fallback modes\n\n### Environment Variables\n- No environment variables required\n- Server runs with sensible defaults\n\n## Usage Examples\n\n### Basic Logical Reasoning\n```\nInput: \"If it's raining, then the ground is wet. It's raining. Is the ground wet?\"\nOutput: \"Yes, the ground is wet. This conclusion follows from modus ponens...\"\n```\n\n### Syllogistic Reasoning  \n```\nInput: \"All birds can fly. Penguins are birds. Can penguins fly?\"\nOutput: \"Based on the given premises, yes. However, this conflicts with real-world knowledge...\"\n```\n\n### Set-Based Logic\n```\nInput: \"All members of set A are in set B. X is in set A. Is X in set B?\"\nOutput: \"Yes, X is in set B. This follows from set inclusion transitivity...\"\n```\n\n## Testing\n\n### Basic Functionality Test\n```bash\nlogic-lm-mcp --help\n```\n\n### Test MCP Integration\n```bash\n# Test with Claude Code\nclaude mcp get logic-lm\n```\n\n## Error Handling\n\n- **Clingo Unavailable**: Provides informative error messages with installation guidance\n- **Invalid ASP Programs**: Syntax checking with detailed error messages  \n- **Solver Timeouts**: Graceful handling of complex problems\n- **Resource Constraints**: Memory and time limit management\n\n## Performance\n\n- **Simple Problems**: 50-200ms response time\n- **Complex Reasoning**: 200-1000ms with self-refinement\n- **Memory Usage**: ~25MB base + ~1MB per concurrent request\n- **Concurrent Support**: Multiple simultaneous reasoning requests\n\n## Troubleshooting\n\n### Common Issues\n\n1. **\"No module named 'pydantic'\" or similar**\n   - Install dependencies: `pip install -r requirements.txt`\n\n2. **\"Clingo not available\"**\n   - Install Clingo: `pip install clingo`\n   - Server will run with limited functionality if Clingo is missing\n\n3. **Server fails to start**\n   - Check Python version: `python --version` (requires 3.8+)\n   - Test installation: `logic-lm-mcp --help`\n\n4. **MCP connection issues**\n   - Verify MCP server configuration: `claude mcp get logic-lm`\n   - Check installation: `logic-lm-mcp --help`\n\n### Getting Help\n\n1. Test installation: `logic-lm-mcp --help`\n2. Check the health endpoint: use `check_solver_health` tool\n3. Enable debug traces: set `include_trace=true` in requests\n\n## FAQ - Common Setup Errors\n\n### \"Missing required dependencies\" on startup\n\n**Error:**\n```\n\u274c Missing required dependencies:\n  - fastmcp>=2.0.0\n  - pydantic>=2.0.0\n```\n\n**Cause:** Dependencies not properly installed or virtual environment not activated.\n\n**Solution:**\n```bash\n# Option 1: Use virtual environment\npython3 -m venv venv\nsource venv/bin/activate  # On Windows: venv\\Scripts\\activate\npip install -r requirements.txt\n\n# Option 2: Install globally\npip install -r requirements.txt\n\n# Option 3: Use venv python directly\nvenv/bin/python start_server.py\n```\n\n### \"ModuleNotFoundError: No module named 'fastmcp'\"\n\n**Error:**\n```\nTraceback (most recent call last):\n  File \"<string>\", line 1, in <module>\nModuleNotFoundError: No module named 'fastmcp'\n```\n\n**Cause:** Virtual environment not properly activated or dependencies not installed.\n\n**Solution:**\n```bash\n# Clean installation\nrm -rf venv/\npython3 -m venv venv\nsource venv/bin/activate\npip install -r requirements.txt\n```\n\n### \"ModuleNotFoundError: No module named 'pydantic'\"\n\n**Error:**\n```\nModuleNotFoundError: No module named 'pydantic'\n```\n\n**Cause:** Missing core dependency, often from incomplete installation.\n\n**Solution:**\n```bash\npip install pydantic>=2.0.0\n# Or reinstall all dependencies\npip install -r requirements.txt\n```\n\n### Virtual environment using system Python instead of venv Python\n\n**Error:** Virtual environment is using the system Python instead of the isolated venv Python.\n\n**Symptoms:**\n- Packages installed globally instead of in venv\n- Permission errors during package installation\n- `which python` shows system path after activation\n- Inconsistent behavior between development and production\n\n**Causes:**\n- Incorrect virtual environment activation\n- Shell aliases overriding PATH (alias python, alias python3)\n- Corrupted virtual environment\n- PATH configuration issues\n\n**Solutions:**\n\n**Option 1: Verify and fix activation**\n```bash\n# Check if activation worked properly\nsource venv/bin/activate\nwhich python  # Should show venv/bin/python, not /usr/bin/python\n\n# If still showing system python, check for aliases\nalias python\nalias python3\n\n# Remove problematic aliases\nunalias python\nunalias python3\n```\n\n**Option 2: Use explicit venv path (most reliable)**\n```bash\n# Instead of relying on activation, use direct paths\nvenv/bin/python -c \"import sys; print(sys.executable)\"\nvenv/bin/pip install package-name\n\n# For our package specifically\nvenv/bin/python -c \"from logic_lm_mcp import LogicFramework; print('\u2705 Works!')\"\n```\n\n**Option 3: Recreate virtual environment**\n```bash\n# Clean recreation if venv is corrupted\nrm -rf venv/\npython3 -m venv venv\nsource venv/bin/activate\nwhich python  # Verify it shows venv/bin/python\npip install logic-lm-mcp-server\n```\n\n**Option 4: Use absolute paths in shell**\n```bash\n# For Linux/Mac\n/full/path/to/venv/bin/python script.py\n\n# For Windows  \nC:\\full\\path\\to\\venv\\Scripts\\python.exe script.py\n```\n\n### \"Clingo not available\" but everything else works\n\n**Error:**\n```\n\"clingo_available\": false\n```\n\n**Cause:** Clingo ASP solver not installed.\n\n**Solution:**\n```bash\n# Option 1: Via pip\npip install clingo>=5.8.0\n\n# Option 2: Via conda\nconda install -c conda-forge clingo\n\n# Option 3: Check installation\npython -c \"import clingo; print('Clingo available')\"\n```\n\n### Server starts but MCP tools not available\n\n**Error:** MCP connection fails or tools not found.\n\n**Cause:** Server not properly configured in Claude Code.\n\n**Solution:**\n1. Verify server is running: `python start_server.py`\n2. Check Claude Code MCP configuration\n3. Restart Claude Code if needed\n4. Use absolute paths in configuration\n\n### Python version compatibility issues\n\n**Error:**\n```\nSyntaxError: invalid syntax\n```\n\n**Cause:** Python version < 3.8.\n\n**Solution:**\n```bash\n# Check Python version\npython --version  # Must be 3.8+\n\n# Use specific Python version\npython3.8 -m venv venv\n# or\npython3.9 -m venv venv\n```\n\n### Background process conflicts\n\n**Error:** Server won't start, port already in use.\n\n**Cause:** Previous server instance still running.\n\n**Solution:**\n```bash\n# Kill existing processes\npkill -f start_server.py\npkill -f logic-lm\n\n# Or find and kill specific process\nps aux | grep start_server\nkill <process_id>\n```\n\n### File permission errors\n\n**Error:**\n```\nPermissionError: [Errno 13] Permission denied\n```\n\n**Cause:** Insufficient file permissions.\n\n**Solution:**\n```bash\n# Fix permissions\nchmod +x start_server.py\nchmod -R 755 src/\n\n# Or run with appropriate permissions\nsudo python start_server.py  # Not recommended\n```\n\n### Import path issues\n\n**Error:**\n```\nModuleNotFoundError: No module named 'src'\n```\n\n**Cause:** Python can't find local modules.\n\n**Solution:**\n```bash\n# Run from project root directory\ncd /path/to/logic-lm-mcp-server\npython start_server.py\n\n# Or use absolute imports\nexport PYTHONPATH=\"${PYTHONPATH}:$(pwd)\"\n```\n\n### Cache or old dependency conflicts\n\n**Error:** Server uses old logic after code changes.\n\n**Cause:** Python bytecode cache or old dependencies.\n\n**Solution:**\n```bash\n# Clear Python cache\nfind . -type d -name \"__pycache__\" -exec rm -rf {} +\nfind . -name \"*.pyc\" -delete\n\n# Reinstall dependencies cleanly\nrm -rf venv/\npython3 -m venv venv\nsource venv/bin/activate\npip install -r requirements.txt\n\n# Restart Claude Code\n```\n\n### Memory or resource issues\n\n**Error:** Server crashes or becomes unresponsive.\n\n**Cause:** Insufficient system resources.\n\n**Solution:**\n- Close other applications to free memory\n- Use smaller `max_models` parameter in requests\n- Check system requirements (25MB base memory)\n- Monitor server logs for resource warnings\n\n## Development\n\n### Project Structure\n```\nlogic-lm-mcp-server/\n\u251c\u2500\u2500 src/\n\u2502   \u251c\u2500\u2500 __init__.py           # Package initialization\n\u2502   \u251c\u2500\u2500 logic_lm_mcp/\n\u2502   \u2502   \u251c\u2500\u2500 __init__.py       # Package initialization\n\u2502   \u2502   \u251c\u2500\u2500 main.py           # FastMCP server implementation\n\u2502   \u2502   \u251c\u2500\u2500 logic_framework.py # Core Logic-LM framework\n\u2502   \u2502   \u2514\u2500\u2500 asp_templates.py   # ASP template library\n\u251c\u2500\u2500 pyproject.toml            # Modern Python packaging\n\u251c\u2500\u2500 requirements.txt          # Python dependencies\n\u251c\u2500\u2500 start_server.py          # Development server startup\n\u2514\u2500\u2500 README.md               # This documentation\n```\n\n### Adding New Templates\n\n1. Edit `src/logic_lm_mcp/asp_templates.py`\n2. Add new template to `_initialize_templates()` method\n3. Test with `logic-lm-mcp --help` and MCP tools\n\n### Extending Logic Framework\n\n1. Edit `src/logic_lm_mcp/logic_framework.py`\n2. Add new reasoning methods to `LogicFramework` class\n3. Update FastMCP tools in `src/logic_lm_mcp/main.py`\n\n## Resources\n\n### ASP Templates\nThe server provides access to ASP templates via MCP resources:\n- `asp-templates://list` - List all available templates\n- `asp-templates://info/{template_name}` - Get template information\n- `asp-templates://template/{template_name}` - Get template code\n\n### Available Templates\n- **universal**: Universal quantification (All X are Y)\n- **conditional**: Conditional rules (If X then Y)\n- **syllogism**: Basic syllogistic reasoning\n- **existential**: Existential quantification (Some X are Y)\n- **negation**: Negation patterns (No X are Y)\n- **set_membership**: Set membership and relationships\n- **transitive**: Transitive relationships\n\n## License\n\nMIT License - See LICENSE file for details.\n\n## Support\n\nFor issues, feature requests, or questions about Logic-LM reasoning capabilities, please:\n\n1. Test installation: `logic-lm-mcp --help`\n2. Check the troubleshooting section above\n3. Open an issue in the repository with:\n   - Python version\n   - Operating system\n   - Error messages\n   - Installation method used (pip/uv)",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2024 Steven Wang\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "A Model Context Protocol server that provides symbolic reasoning capabilities using Logic-LM framework and Answer Set Programming",
    "version": "1.0.1",
    "project_urls": {
        "Documentation": "https://github.com/stevenwangbe/logic-lm-mcp-server/blob/main/README.md",
        "Homepage": "https://github.com/stevenwangbe/logic-lm-mcp-server",
        "Issues": "https://github.com/stevenwangbe/logic-lm-mcp-server/issues",
        "Repository": "https://github.com/stevenwangbe/logic-lm-mcp-server"
    },
    "split_keywords": [
        "answer-set-programming",
        " asp",
        " clingo",
        " logic",
        " mcp",
        " reasoning",
        " symbolic-solver"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6f58672c4bb33f44edaf40704585589101e24f52b716e65a4fa31d5d000b56a0",
                "md5": "e0f203314fc4b140d4338ed9bce83e68",
                "sha256": "dc1ef6b138ac1111c37d3990dcb45881f82ba5397abc960723ce9434f40d8132"
            },
            "downloads": -1,
            "filename": "logic_lm_mcp_server-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e0f203314fc4b140d4338ed9bce83e68",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 20336,
            "upload_time": "2025-08-28T21:36:52",
            "upload_time_iso_8601": "2025-08-28T21:36:52.602446Z",
            "url": "https://files.pythonhosted.org/packages/6f/58/672c4bb33f44edaf40704585589101e24f52b716e65a4fa31d5d000b56a0/logic_lm_mcp_server-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "d89d268028301080759414de6c3f5b41931536d6a506569dc4e91a0e952f4d82",
                "md5": "27a12ad6c99b692f9c9124cce46a4724",
                "sha256": "d46a3739a328dc1e057647e0a6ea0592ecc66ee7c96fc5759f4bcc2316e10edb"
            },
            "downloads": -1,
            "filename": "logic_lm_mcp_server-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "27a12ad6c99b692f9c9124cce46a4724",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 20512,
            "upload_time": "2025-08-28T21:36:54",
            "upload_time_iso_8601": "2025-08-28T21:36:54.138782Z",
            "url": "https://files.pythonhosted.org/packages/d8/9d/268028301080759414de6c3f5b41931536d6a506569dc4e91a0e952f4d82/logic_lm_mcp_server-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-28 21:36:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "stevenwangbe",
    "github_project": "logic-lm-mcp-server",
    "github_not_found": true,
    "lcname": "logic-lm-mcp-server"
}
        
Elapsed time: 0.98569s