Skip to main content
Glama
AI-Chinmay

Utility MCP Server

by AI-Chinmay
README.md
# MCPs 
Think of MCP like the ๐”๐’๐-๐‚ ๐ฉ๐จ๐ซ๐ญ ๐จ๐ง ๐š ๐ฅ๐š๐ฉ๐ญ๐จ๐ฉ. Any device that wants to connect, whether itโ€™s an external hard drive, monitor, or power supply, must follow the USB-C standard.
Similarly, MCP is a standardized protocol developed by Anthropic that defines how ๐‹๐‹๐Œ๐ฌ ๐œ๐จ๐ง๐ง๐ž๐œ๐ญ ๐ญ๐จ ๐œ๐จ๐ง๐ญ๐ž๐ฑ๐ญ๐ฌ ๐š๐ง๐ ๐๐š๐ญ๐š ๐ฌ๐จ๐ฎ๐ซ๐œ๐ž๐ฌ.

The laptop = MCP host
The USB-C port = MCP itself
The monitor, hard drive, power supply = MCP servers

For more understanding of MCPs, visit https://medium.com/@BH_Chinmay/basics-of-mcps-why-and-what-9579c21caac4

# Utility MCP Server

A Model Context Protocol (MCP) server that provides AI-powered document processing and search capabilities.

## Overview

This project implements an MCP server with tools for:
- **PDF Document Processing**: Extract text, metadata, and statistics from PDF files
- **Document Summarization**: Use Azure OpenAI to generate intelligent summaries of documents and pages
- **Web Search**: Perform Google searches and retrieve top results

## Architecture

```
MCPs/
โ”œโ”€โ”€ mcp-servers/              # MCP server entrypoint and tools
โ”‚   โ”œโ”€โ”€ server.py             # Server initialization and tool registration
โ”‚   โ”œโ”€โ”€ mcp_instance.py       # FastMCP instance with logging configuration
โ”‚   โ””โ”€โ”€ tools/                # Tool implementations
โ”‚       โ”œโ”€โ”€ document_summerizer.py  # PDF summarization tools
โ”‚       โ”œโ”€โ”€ google_search.py        # Web search tool
โ”‚       โ””โ”€โ”€ pdf_reader.py           # Basic PDF reading tool
โ”œโ”€โ”€ utils/                    # Shared utility modules
โ”‚   โ”œโ”€โ”€ llm_utils.py          # Azure OpenAI integration
โ”‚   โ””โ”€โ”€ pdf_utils.py          # PDF processing utilities
โ”œโ”€โ”€ requirements.txt          # Python dependencies
โ”œโ”€โ”€ .env                      # Environment variables (secrets)
โ””โ”€โ”€ README.md                 # This file
```

## Tools

### Document Summarization Tools (`tools/document_summerizer.py`)

#### `summarize_document(pdf_path)`
Analyzes a complete PDF document and generates an intelligent summary.
- Extracts all text from the PDF
- Splits content into manageable chunks
- Summarizes each chunk using Azure OpenAI
- Generates a final summary from partial summaries
- **Returns**: File path, page count, chunk count, and final summary

#### `summarize_page(pdf_path, page_number)`
Generates a summary for a specific page in a PDF.
- Extracts text from the specified page
- Processes through Azure OpenAI
- **Returns**: Page number and page summary

#### `extract_document_text(pdf_path)`
Extracts all text content from a PDF without summarization.
- **Returns**: Full text content

#### `document_statistics(pdf_path)`
Calculates text statistics for a document.
- **Returns**: Character count, word count, and line count

#### `document_metadata(pdf_path)`
Retrieves metadata from a PDF document.
- **Returns**: Page count, title, author, creator, and producer

### Google Search Tool (`tools/google_search.py`)

#### `google_search(query, num_results)`
Performs a Google search and returns top results.
- Uses Google Custom Search API
- **Parameters**: 
  - `query`: Search query string
  - `num_results`: Number of results to return (default: 5)
- **Returns**: List of results with title, link, and snippet

### PDF Reader Tool (`tools/pdf_reader.py`)

#### `read_pdf(pdf_path)`
Basic PDF text extraction tool.
- Reads and returns all text from a PDF
- **Returns**: Extracted text content

## Utilities

### LLM Utilities (`utils/llm_utils.py`)
Handles Azure OpenAI integration:
- `_get_client()`: Initializes Azure OpenAI client with environment configuration
- `llm_summary(text)`: Sends text to Azure OpenAI for summarization

### PDF Utilities (`utils/pdf_utils.py`)
Core PDF processing functions:
- `extract_text(pdf_path)`: Extracts all text from a PDF
- `chunk_text(text, chunk_size)`: Splits text into chunks
- `get_metadata(pdf_path)`: Extracts PDF metadata
- `get_page_text(pdf_path, page_number)`: Extracts text from a specific page

## Configuration

### Environment Variables (`.env`)

The application requires the following environment variables:

**Google Search Configuration:**
```
GOOGLE_API_KEY=<your-google-api-key>
GOOGLE_SEARCH_ENGINE_ID=<your-search-engine-id>
```

**Azure OpenAI Configuration:**
```
AZURE_OPENAI_ENDPOINT=<your-azure-endpoint>
AZURE_OPENAI_API_KEY=<your-azure-api-key>
AZURE_OPENAI_API_VERSION=<api-version>
AZURE_OPENAI_DEPLOYMENT=<deployment-name>
```

**Important**: Never commit `.env` with actual credentials to version control.

## Setup and Installation

### Prerequisites
- Python 3.10+
- Virtual environment (recommended)

### Installation

1. Create a virtual environment:
```bash
python -m venv .venv
```

2. Activate the virtual environment:
```bash
# Windows
.venv\Scripts\activate

# macOS/Linux
source .venv/bin/activate
```

3. Install dependencies:
```bash
pip install -r requirements.txt
```

4. Create and configure `.env`:
```bash
cp .env.example .env
# Edit .env and add your API credentials
```

## Running the Server

### Development Mode
```bash
cd mcp-servers
mcp dev server.py
```

### Production Mode
```bash
cd mcp-servers
python server.py
```

## Logging

The application uses Python's built-in logging module with the following configuration:
- **Level**: INFO (use DEBUG for detailed output)
- **Format**: `YYYY-MM-DD HH:MM:SS - logger_name - LEVEL - message`
- **Security**: All credentials and API keys are masked in logs

### Log Levels
- **DEBUG**: Detailed operation information (page extraction, chunk processing)
- **INFO**: Normal operation events (tool invocations, completion status)
- **WARNING**: Warning messages (invalid page numbers, missing configuration)
- **ERROR**: Error events with full exception tracebacks

### Enabling Debug Logging
To see more detailed logs during development:
```python
import logging
logging.getLogger().setLevel(logging.DEBUG)
```

## Dependencies

- **mcp** (1.28.1+): Model Context Protocol framework
- **openai** (1.0.0+): Azure OpenAI client
- **python-dotenv**: Environment variable management
- **httpx** (0.27.0+): Async HTTP client for Google Search API
- **PyMuPDF** (1.24.0+): PDF text extraction

See `requirements.txt` for complete list.

## Error Handling

All tools include comprehensive error handling:
- File existence validation before processing
- Exception logging with full tracebacks
- User-friendly error messages in responses
- No sensitive data logged in error messages

## Security Considerations

1. **Credentials**: Store all API keys and endpoints in `.env` file
2. **Logging**: Credentials are never logged or printed
3. **Environment**: Use separate `.env` files for different environments (dev, staging, production)
4. **Access**: Restrict access to `.env` file permissions (never commit to version control)

## Development Notes

### Adding New Tools
1. Create a new file in `tools/` directory
2. Import and register with `@mcp.tool()` decorator
3. Add comprehensive logging with `logger.info()` and `logger.error()`
4. Document the tool in this README

### Code Style
- Use descriptive variable names
- Include docstrings for all functions
- Log important operations and errors
- Never log sensitive information (API keys, authentication tokens)

## Troubleshooting

### Import Errors
If you encounter `ModuleNotFoundError`:
1. Ensure virtual environment is activated
2. Run `pip install -r requirements.txt`
3. Check that Python path includes both `mcp-servers/` and project root directories

### Missing Environment Variables
If you see "Missing Azure OpenAI environment variables":
1. Verify `.env` file exists in the project root
2. Check that all required variables are set (not empty)
3. Restart the server after updating `.env`

### PDF Processing Issues
- Ensure PDF file exists and is readable
- Check that PyMuPDF (fitz) is properly installed
- Verify sufficient disk space for large PDF files


## Support

For issues or questions, please refer to the logging output for detailed error information.