GUIDE.mdโข8.73 kB
# MCP Wikipedia Server - Complete Guide
A Model Context Protocol (MCP) server that provides Wikipedia search and content retrieval tools using FastMCP and Python 3.11.
## ๐ Table of Contents
- [Overview](#overview)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Project Structure](#project-structure)
- [Available Tools](#available-tools)
- [Usage](#usage)
- [Development](#development)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
## ๐ฏ Overview
This project implements an MCP server that provides three powerful Wikipedia tools:
1. **Search Wikipedia** - Find articles and get summaries
2. **List Sections** - Get section titles from Wikipedia articles
3. **Get Section Content** - Retrieve specific section content
The server uses the Model Context Protocol (MCP) for structured communication with AI assistants and other clients.
## ๐ง Prerequisites
- **macOS** (tested on Apple Silicon)
- **Python 3.11+** (required for MCP compatibility)
- **Git** (for version control)
- **Terminal/Command Line** access
## ๐ฆ Installation
### Step 1: Clone or Navigate to Project
```bash
cd /Users/kaman/Desktop/MCPClientServer
```
### Step 2: Set Up Python 3.11 Environment
If you don't have Python 3.11, install it using pyenv:
```bash
# Install pyenv (if not already installed)
curl https://pyenv.run | bash
# Add to your shell profile (~/.zshrc or ~/.bash_profile)
export PYENV_ROOT="$HOME/.pyenv"
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
# Restart your shell or source the profile
source ~/.zshrc
# Install Python 3.11
pyenv install 3.11.10
pyenv local 3.11.10
```
### Step 3: Create Virtual Environment
```bash
# Create virtual environment with Python 3.11
python -m venv .venv311
# Activate the environment
source .venv311/bin/activate
# Verify Python version
python --version # Should show Python 3.11.10
```
### Step 4: Install Dependencies
```bash
# Upgrade pip
pip install --upgrade pip
# Install required packages
pip install wikipedia mcp fastmcp
```
## ๐ Project Structure
```
MCPClientServer/
โโโ .python-version # Pyenv Python version
โโโ .venv311/ # Python 3.11 virtual environment
โโโ src/
โ โโโ mcp_server/
โ โโโ mcp_server.py # Wikipedia MCP server
โ โโโ mcp_client.py # MCP client example
โโโ tests/
โ โโโ test_server.py # Test files
โโโ README.md # This guide
โโโ LICENSE # License file
โโโ pyproject.toml # Project configuration
```
## ๐ง Available Tools
### 1. `fetch_wikipedia_info`
**Purpose**: Search Wikipedia and get article summary
**Parameters**:
- `query` (string): Search term
**Example Response**:
```json
{
"title": "Python (programming language)",
"summary": "Python is a high-level, general-purpose programming language...",
"url": "https://en.wikipedia.org/wiki/Python_(programming_language)"
}
```
### 2. `list_wikipedia_sections`
**Purpose**: Get all section titles from a Wikipedia article
**Parameters**:
- `topic` (string): Wikipedia article title
**Example Response**:
```json
{
"sections": ["History", "Design philosophy", "Syntax and semantics", "Libraries"]
}
```
### 3. `get_section_content`
**Purpose**: Get content from a specific article section
**Parameters**:
- `topic` (string): Wikipedia article title
- `section_title` (string): Section name to retrieve
**Example Response**:
```json
{
"content": "Python was conceived in the late 1980s by Guido van Rossum..."
}
```
## ๐ Usage
### Starting the Server
```bash
# Activate virtual environment
source .venv311/bin/activate
# Navigate to server directory
cd src/mcp_server
# Start the Wikipedia MCP server
python mcp_server.py
```
You should see:
```
Starting MCP Wikipedia Server with multiple tools...
```
### Connecting via MCP Client
The server runs on stdio transport, meaning it communicates through standard input/output. Here's how to connect:
#### Python Client Example:
```python
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def use_wikipedia_server():
# Connect to the server
server_params = StdioServerParameters(
command="python",
args=["mcp_server.py"]
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the session
await session.initialize()
# List available tools
tools = await session.list_tools()
print(f"Available tools: {[tool.name for tool in tools.tools]}")
# Use the fetch_wikipedia_info tool
result = await session.call_tool("fetch_wikipedia_info", {"query": "Python programming"})
print(f"Result: {result.content}")
# Run the client
asyncio.run(use_wikipedia_server())
```
#### Claude Desktop Integration:
Add to your Claude Desktop config (`claude_desktop_config.json`):
```json
{
"mcpServers": {
"wikipedia": {
"command": "python",
"args": ["/Users/kaman/Desktop/MCPClientServer/src/mcp_server/mcp_server.py"],
"env": {
"PYTHONPATH": "/Users/kaman/Desktop/MCPClientServer/.venv311/lib/python3.11/site-packages"
}
}
}
}
```
## ๐ป Development
### Adding New Tools
To add a new Wikipedia-related tool:
1. **Define the tool function** in `mcp_server.py`:
```python
@mcp.tool()
def your_new_tool(parameter: str) -> dict:
"""
Description of what your tool does.
"""
try:
# Your logic here
result = some_wikipedia_operation(parameter)
return {"result": result}
except Exception as e:
return {"error": str(e)}
```
2. **Test the tool**:
```bash
# Start server and test with your MCP client
python mcp_server.py
```
### Code Style
- Follow PEP 8 Python style guidelines
- Use type hints for all function parameters and returns
- Include docstrings for all tools
- Handle exceptions gracefully and return error messages
### Testing
Run tests to ensure everything works:
```bash
# Activate environment
source .venv311/bin/activate
# Run tests (if available)
python -m pytest tests/ -v
```
## ๐ Troubleshooting
### Common Issues
#### 1. ModuleNotFoundError: No module named 'wikipedia'
**Solution**:
```bash
source .venv311/bin/activate
pip install wikipedia
```
#### 2. MCP package requires Python 3.10+
**Solution**: Ensure you're using Python 3.11:
```bash
python --version # Should show 3.11.x
pyenv local 3.11.10 # Set local Python version
```
#### 3. Server not starting
**Check**:
- Virtual environment is activated
- All dependencies are installed
- Python version is 3.11+
- No port conflicts
#### 4. Wikipedia API errors
**Common causes**:
- Network connectivity issues
- Wikipedia service temporarily unavailable
- Invalid article titles or search terms
**Solutions**:
- Check internet connection
- Try different search terms
- Add retry logic for network requests
### Debug Mode
For detailed logging, modify the server to include debug output:
```python
import logging
logging.basicConfig(level=logging.DEBUG)
```
## ๐ Environment Variables
You can customize the server behavior with environment variables:
```bash
# Set Wikipedia language (default: en)
export WIKIPEDIA_LANGUAGE=en
# Set request timeout (default: 30 seconds)
export WIKIPEDIA_TIMEOUT=30
```
## ๐ค Contributing
1. **Fork the repository**
2. **Create a feature branch**: `git checkout -b feature/new-tool`
3. **Make changes** and add tests
4. **Commit changes**: `git commit -m "Add new Wikipedia tool"`
5. **Push to branch**: `git push origin feature/new-tool`
6. **Create Pull Request**
### Development Setup
```bash
# Clone your fork
git clone your-fork-url
cd MCPClientServer
# Set up development environment
source .venv311/bin/activate
pip install -e . # Install in development mode
```
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ References
- [Model Context Protocol Documentation](https://modelcontextprotocol.io/)
- [FastMCP Framework](https://github.com/jlowin/fastmcp)
- [Wikipedia API Documentation](https://wikipedia.readthedocs.io/)
- [Python Wikipedia Package](https://pypi.org/project/wikipedia/)
## ๐ Support
If you encounter issues:
1. Check this guide's troubleshooting section
2. Review the error messages carefully
3. Ensure all prerequisites are met
4. Check that your virtual environment is properly activated
---
**Happy coding with MCP and Wikipedia! ๐**