demo-mcp-server

masaic-ai-platform/demo-mcp-server

3.2

If you are the rightful owner of demo-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

A demonstration of a Model Context Protocol (MCP) server using JSON-RPC 2.0 over HTTP for image processing.

Tools
  1. image_to_base64

    Downloads an image from a URL and converts it to a base64 encoded string saved in a file.

  2. img_scene_generator

    Uses OpenAI's API to generate new images based on a text prompt and an input image.

Demo MCP Server

A simple demonstration of a Model Context Protocol (MCP) server implementation using JSON-RPC 2.0 over HTTP. This demo server shows how to implement the MCP specification with two example tools for image processing.

Features

  • JSON-RPC 2.0 implementation
  • MCP protocol support with standard methods
  • Two example tools: image encoding and scene generation
  • Mock mode for testing without API dependencies
  • Basic file management and serving
  • Logging for debugging

Available MCP Tools

1. image_to_base64

Downloads an image from a URL and converts it to a base64 encoded string saved in a file.

Input Parameters:

  • url (string, required): The URL of the image to download and encode

Returns:

  • encodedFilePath: Path to the file containing the base64 encoded image

Use Case: Prepare images for AI processing or storage

2. img_scene_generator

Uses OpenAI's API to generate new images based on a text prompt and an input image.

Input Parameters:

  • prompt (string, required): Text description for scene generation
  • encodedFilePath (string, required): Path to file with base64 encoded image

Returns:

  • situationDescription: AI-generated description of the scene
  • image_url: URL to access the generated image

Use Case: Create AI-generated variations or scenes based on existing images

Quick Start

Prerequisites

  • Python 3.8+
  • Virtual environment (recommended)
  • OpenAI API key (for img_scene_generator tool)

1. Installation

# Clone or download the project
cd demo-mcp-server

# Create and activate virtual environment
python -m venv myenv
source myenv/bin/activate  # On Windows: myenv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

2. Configuration

Set up your OpenAI API key (required for img_scene_generator tool):

export OPENAI_API_KEY="your-actual-openai-api-key-here"

Or create a .env file:

echo "OPENAI_API_KEY=your-actual-openai-api-key-here" > .env

3. Run the Server

Real Mode (with OpenAI API):

python mcp_server.py

Mock Mode (for testing without API calls):

python mcp_server.py dataConfig=mock

The server will start on http://localhost:8086

Check Container Status

# Check if container is running
docker ps

# View container logs
docker logs mcp-server

# Check health status
docker inspect --format='{{.State.Health.Status}}' mcp-server

Server Endpoints

EndpointMethodDescription
/mcpPOSTMain MCP endpoint (JSON-RPC 2.0)
/GETServer information
/healthGETHealth check
/imagesGETList all generated images with metadata
/{filename}GETServe generated images (e.g., generated_image_123.png)

Using the MCP Protocol

Step 1: Initialize Connection

POST /mcp
{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {
            "name": "your-client",
            "version": "1.0.0"
        }
    }
}

Step 2: Send Initialized Notification

POST /mcp
{
    "jsonrpc": "2.0",
    "method": "initialized",
    "params": {}
}

Step 3: List Available Tools

POST /mcp
{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list",
    "params": {}
}

Step 4: Use the Tools

Example: Convert image to base64

POST /mcp
{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
        "name": "image_to_base64",
        "arguments": {
            "url": "https://example.com/image.jpg"
        }
    }
}

Example: Generate scene with AI

POST /mcp
{
    "jsonrpc": "2.0",
    "id": 4,
    "method": "tools/call",
    "params": {
        "name": "img_scene_generator",
        "arguments": {
            "prompt": "Transform this into a futuristic cyberpunk scene",
            "encodedFilePath": "/path/to/encoded/image/file.txt"
        }
    }
}

Configuration

Environment Variables

  • OPENAI_API_KEY: Required for img_scene_generator tool
  • ENCODED_IMG_DIR: Directory for storing encoded images (optional)
  • GENERATED_IMG_DIR: Directory for storing generated images (optional)

Default directories (when environment variables are not set):

  • Encoded images: /Users/jasbirsingh/Downloads/img_server/encoded_img
  • Generated images: /Users/jasbirsingh/Downloads/img_server/generated_img

Command Line Options

  • dataConfig=mock: Run in mock mode (no real API calls)
  • dataConfig=real: Run in real mode (default)

Development & Testing

Testing the Server

  1. Health Check:

    curl http://localhost:8086/health
    
  2. List Tools:

    curl -X POST http://localhost:8086/mcp \
      -H "Content-Type: application/json" \
      -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
    
  3. Mock Mode Testing: Run with dataConfig=mock to test without OpenAI API calls

File Structure

demo-mcp-server/
ā”œā”€ā”€ mcp_server.py          # Main server implementation
ā”œā”€ā”€ requirements.txt       # Python dependencies
ā”œā”€ā”€ Dockerfile            # Docker container configuration
ā”œā”€ā”€ README.md             # This file
ā”œā”€ā”€ myenv/                # Virtual environment (local development)
└── data/                 # Generated files (when using Docker volumes)
    ā”œā”€ā”€ encoded_img/      # Base64 encoded image files
    └── generated_img/    # AI generated image files

Generated Files

  • Encoded Images: encode-img-{timestamp}.txt
  • Generated Images: generated_image_{timestamp}.png

Troubleshooting

Common Issues

  1. ModuleNotFoundError: No module named 'aiohttp'

    pip install aiohttp
    
  2. OpenAI API Error

    • Verify your API key is set correctly
    • Check your OpenAI account has sufficient credits
    • Use mock mode for testing: python mcp_server.py dataConfig=mock
  3. Directory Permission Errors

    • Ensure the application has write permissions to the configured directories
    • The server will auto-create directories if they don't exist

Logs

The server provides detailed logging. Check the console output for:

  • Request processing status
  • Tool execution progress
  • Error details and stack traces

Requirements

See requirements.txt for the complete list of dependencies:

  • fastapi - Web framework
  • uvicorn[standard] - ASGI server
  • openai - OpenAI API client
  • aiohttp - Async HTTP client
  • requests - HTTP library
  • pydantic - Data validation
  • python-dotenv - Environment variable management

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

License

This project follows the MIT License terms.


Need Help? Check the server logs for detailed error messages and debugging information.