Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:EvolvingLMMs Lab Lmms eval Sample MCP Server: Difference between revisions

From Leeroopedia
Auto-imported from implementations/EvolvingLMMs_Lab_Lmms_eval_Sample_MCP_Server.md
 
Sync from local file
 
Line 1: Line 1:
{{PageInfo|type=Implementation|title=EvolvingLMMs_Lab_Lmms_eval_Sample_MCP_Server}}
{{PageInfo|type=Implementation|title=EvolvingLMMs_Lab_Lmms_eval_Sample_MCP_Server}}
**File**: `/tmp/kapso_repo_sslb_59s/examples/mcp_server/sample_mcp_server.py`
'''File''': <code>examples/mcp_server/sample_mcp_server.py</code>


**Principle**: [[MCP_Tool_Integration]]
'''Principle''': [[MCP_Tool_Integration]]


## Overview
== Overview ==
The Sample MCP Server demonstrates basic MCP tool implementations with three example tools: image zoom/crop, weather query, and blank image generation. It serves as a template for creating custom MCP tools and shows various return types and parameter patterns.
The Sample MCP Server demonstrates basic MCP tool implementations with three example tools: image zoom/crop, weather query, and blank image generation. It serves as a template for creating custom MCP tools and shows various return types and parameter patterns.


## Key Components
== Key Components ==


### 1. Server Initialization
=== 1. Server Initialization ===
```python
<syntaxhighlight lang="python">
app = FastMCP("demo")
app = FastMCP("demo")
```
</syntaxhighlight>
Creates a minimal FastMCP application named "demo" (version omitted, defaults to None).
Creates a minimal FastMCP application named "demo" (version omitted, defaults to None).


### 2. Tool Implementations
=== 2. Tool Implementations ===


#### image_zoom_in_tool
==== image_zoom_in_tool ====
```python
<syntaxhighlight lang="python">
@app.tool(name="image_zoom_in_tool", description="Zoom in on a specific region of an image by cropping it based on a bounding box (bbox) and an optional object label.")
@app.tool(name="image_zoom_in_tool", description="Zoom in on a specific region of an image by cropping it based on a bounding box (bbox) and an optional object label.")
def image_zoom_in_tool(image_path: str, bbox: List[float]):
def image_zoom_in_tool(image_path: str, bbox: List[float]):
```
</syntaxhighlight>


**Purpose**: Crops a region from an image based on bounding box coordinates
'''Purpose''': Crops a region from an image based on bounding box coordinates


**Parameters**:
'''Parameters''':
- `image_path` (str): Path to the input image file
- <code>image_path</code> (str): Path to the input image file
- `bbox` (List[float]): Bounding box coordinates [x_min, y_min, x_max, y_max]
- <code>bbox</code> (List[float]): Bounding box coordinates [x_min, y_min, x_max, y_max]


**Returns**: ImageContent with base64-encoded PNG
'''Returns''': ImageContent with base64-encoded PNG


**Implementation**:
'''Implementation''':
```python
<syntaxhighlight lang="python">
image = Image.open(image_path)
image = Image.open(image_path)
cropped_image = image.crop(bbox)
cropped_image = image.crop(bbox)
Line 42: Line 42:


return ImageContent(type="image", data=png, mimeType="image/png")
return ImageContent(type="image", data=png, mimeType="image/png")
```
</syntaxhighlight>


**Key Operations**:
'''Key Operations''':
1. Opens image using PIL
1. Opens image using PIL
2. Crops using bbox coordinates (left, upper, right, lower)
2. Crops using bbox coordinates (left, upper, right, lower)
Line 51: Line 51:
5. Wraps in ImageContent with proper MIME type
5. Wraps in ImageContent with proper MIME type


#### get_weather
==== get_weather ====
```python
<syntaxhighlight lang="python">
@app.tool(name="weather", description="query weather")
@app.tool(name="weather", description="query weather")
def get_weather(city: str):
def get_weather(city: str):
```
</syntaxhighlight>


**Purpose**: Demonstrates a simple text-based tool with predefined data
'''Purpose''': Demonstrates a simple text-based tool with predefined data


**Parameters**:
'''Parameters''':
- `city` (str): City name to query weather for
- <code>city</code> (str): City name to query weather for


**Returns**: Dict with weather information (temp, condition) or error message
'''Returns''': Dict with weather information (temp, condition) or error message


**Implementation**:
'''Implementation''':
```python
<syntaxhighlight lang="python">
weather_data = {"Beijing": {"temp": 25, "condition": "Rainy"}, "Shanghai": {"temp": 28, "condition": "Cloudy"}}
weather_data = {"Beijing": {"temp": 25, "condition": "Rainy"}, "Shanghai": {"temp": 28, "condition": "Cloudy"}}
result = weather_data.get(city, {"error": "未找到该城市"})
result = weather_data.get(city, {"error": "未找到该城市"})
return result
return result
```
</syntaxhighlight>


**Key Operations**:
'''Key Operations''':
1. Hardcoded weather data for two cities
1. Hardcoded weather data for two cities
2. Lookup by city name
2. Lookup by city name
3. Returns error dict if city not found (Chinese message: "City not found")
3. Returns error dict if city not found (Chinese message: "City not found")


#### get_blank_image
==== get_blank_image ====
```python
<syntaxhighlight lang="python">
@app.tool(name="get_blank_image", description="get blank image")
@app.tool(name="get_blank_image", description="get blank image")
def get_blank_image(width: int = 512, height: int = 512):
def get_blank_image(width: int = 512, height: int = 512):
```
</syntaxhighlight>


**Purpose**: Generates a blank white image of specified dimensions
'''Purpose''': Generates a blank white image of specified dimensions


**Parameters**:
'''Parameters''':
- `width` (int): Image width in pixels (default: 512)
- <code>width</code> (int): Image width in pixels (default: 512)
- `height` (int): Image height in pixels (default: 512)
- <code>height</code> (int): Image height in pixels (default: 512)


**Returns**: ImageContent with base64-encoded PNG
'''Returns''': ImageContent with base64-encoded PNG


**Implementation**:
'''Implementation''':
```python
<syntaxhighlight lang="python">
image = Image.new("RGB", (width, height), color=(255, 255, 255))
image = Image.new("RGB", (width, height), color=(255, 255, 255))
image_bytes = io.BytesIO()
image_bytes = io.BytesIO()
Line 98: Line 98:
png = base64.b64encode(image_bytes.getvalue()).decode("utf-8")
png = base64.b64encode(image_bytes.getvalue()).decode("utf-8")
return ImageContent(type="image", data=png, mimeType="image/png")
return ImageContent(type="image", data=png, mimeType="image/png")
```
</syntaxhighlight>


**Key Operations**:
'''Key Operations''':
1. Creates new RGB image with white background
1. Creates new RGB image with white background
2. Saves to in-memory buffer as PNG
2. Saves to in-memory buffer as PNG
Line 106: Line 106:
4. Wraps in ImageContent for MCP protocol
4. Wraps in ImageContent for MCP protocol


### 3. Server Entry Point
=== 3. Server Entry Point ===
```python
<syntaxhighlight lang="python">
if __name__ == "__main__":
if __name__ == "__main__":
     app.run()
     app.run()
```
</syntaxhighlight>
Launches the MCP server when script is executed.
Launches the MCP server when script is executed.


## Dependencies
== Dependencies ==
- `base64`: For encoding images to base64
- <code>base64</code>: For encoding images to base64
- `io`: For in-memory byte buffers (BytesIO)
- <code>io</code>: For in-memory byte buffers (BytesIO)
- `typing`: For type annotations (List)
- <code>typing</code>: For type annotations (List)
- `mcp.server.fastmcp`: FastMCP framework
- <code>mcp.server.fastmcp</code>: FastMCP framework
- `mcp.types`: MCP content types (ImageContent)
- <code>mcp.types</code>: MCP content types (ImageContent)
- `PIL.Image`: For image creation and manipulation
- <code>PIL.Image</code>: For image creation and manipulation


## Tool Patterns
== Tool Patterns ==


### Image Processing Tools
=== Image Processing Tools ===
Both `image_zoom_in_tool` and `get_blank_image` demonstrate the pattern for image-returning tools:
Both <code>image_zoom_in_tool</code> and <code>get_blank_image</code> demonstrate the pattern for image-returning tools:
1. Generate or process image using PIL
1. Generate or process image using PIL
2. Save to BytesIO buffer as PNG
2. Save to BytesIO buffer as PNG
Line 130: Line 130:
4. Wrap in ImageContent with MIME type
4. Wrap in ImageContent with MIME type


### Data Lookup Tools
=== Data Lookup Tools ===
The `get_weather` tool shows a simple lookup pattern:
The <code>get_weather</code> tool shows a simple lookup pattern:
1. Maintain static data structure
1. Maintain static data structure
2. Lookup by key
2. Lookup by key
Line 137: Line 137:
4. Can be extended with API calls or database queries
4. Can be extended with API calls or database queries


## Usage Examples
== Usage Examples ==


### Starting the Server
=== Starting the Server ===
```bash
<syntaxhighlight lang="bash">
python examples/mcp_server/sample_mcp_server.py
python examples/mcp_server/sample_mcp_server.py
```
</syntaxhighlight>


### Invoking Tools
=== Invoking Tools ===
```python
<syntaxhighlight lang="python">
from lmms_eval.mcp.client import MCPClient
from lmms_eval.mcp.client import MCPClient


Line 169: Line 169:
     "height": 768
     "height": 768
})
})
```
</syntaxhighlight>


## Design Decisions
== Design Decisions ==


1. **Minimal Server Setup**: No version or complex config to keep example simple
1. '''Minimal Server Setup''': No version or complex config to keep example simple
2. **Diverse Tool Types**: Shows both image and text return types
2. '''Diverse Tool Types''': Shows both image and text return types
3. **Default Parameters**: `get_blank_image` demonstrates optional params with defaults
3. '''Default Parameters''': <code>get_blank_image</code> demonstrates optional params with defaults
4. **Static Data**: Weather tool uses hardcoded data for simplicity
4. '''Static Data''': Weather tool uses hardcoded data for simplicity
5. **Standard Image Format**: PNG chosen for lossless quality and broad support
5. '''Standard Image Format''': PNG chosen for lossless quality and broad support


## Extension Points
== Extension Points ==


This server can be extended by:
This server can be extended by:
1. Adding database or API calls to `get_weather`
1. Adding database or API calls to <code>get_weather</code>
2. Implementing more image transformations (rotate, filter, etc.)
2. Implementing more image transformations (rotate, filter, etc.)
3. Adding error handling for invalid image paths
3. Adding error handling for invalid image paths
Line 189: Line 189:
6. Adding authentication/authorization
6. Adding authentication/authorization


## Comparison with crop_video_mcp_server
== Comparison with crop_video_mcp_server ==


| Aspect | sample_mcp_server | crop_video_mcp_server |
| Aspect | sample_mcp_server | crop_video_mcp_server |
Line 200: Line 200:
| Use Case | Learning/template | Actual video processing |
| Use Case | Learning/template | Actual video processing |


## Related Components
== Related Components ==
- [[Crop_Video_MCP_Server]]: More complex MCP server example
- [[Crop_Video_MCP_Server]]: More complex MCP server example
- [[MCP_Client]]: Client for invoking these tools
- [[MCP_Client]]: Client for invoking these tools
- [[Media_Handling]]: Framework's built-in media processing
- [[Media_Handling]]: Framework's built-in media processing


## Best Practices Demonstrated
== Best Practices Demonstrated ==
1. Clear tool names and descriptions for LLM consumption
1. Clear tool names and descriptions for LLM consumption
2. Type annotations for all parameters
2. Type annotations for all parameters
Line 213: Line 213:
6. Standard image encoding approach
6. Standard image encoding approach


## Common Use Cases
== Common Use Cases ==
1. **Prototyping**: Quick testing of MCP tool concepts
1. '''Prototyping''': Quick testing of MCP tool concepts
2. **Learning**: Understanding MCP tool structure
2. '''Learning''': Understanding MCP tool structure
3. **Template**: Starting point for custom tools
3. '''Template''': Starting point for custom tools
4. **Testing**: Validating MCP client implementations
4. '''Testing''': Validating MCP client implementations
5. **Demonstration**: Showing different tool return types
5. '''Demonstration''': Showing different tool return types


[[Category:Implementations]]
[[Category:Implementations]]

Latest revision as of 10:38, 27 September 2026

File: examples/mcp_server/sample_mcp_server.py

Principle: MCP_Tool_Integration

Overview

The Sample MCP Server demonstrates basic MCP tool implementations with three example tools: image zoom/crop, weather query, and blank image generation. It serves as a template for creating custom MCP tools and shows various return types and parameter patterns.

Key Components

1. Server Initialization

app = FastMCP("demo")

Creates a minimal FastMCP application named "demo" (version omitted, defaults to None).

2. Tool Implementations

image_zoom_in_tool

@app.tool(name="image_zoom_in_tool", description="Zoom in on a specific region of an image by cropping it based on a bounding box (bbox) and an optional object label.")
def image_zoom_in_tool(image_path: str, bbox: List[float]):

Purpose: Crops a region from an image based on bounding box coordinates

Parameters: - image_path (str): Path to the input image file - bbox (List[float]): Bounding box coordinates [x_min, y_min, x_max, y_max]

Returns: ImageContent with base64-encoded PNG

Implementation:

image = Image.open(image_path)
cropped_image = image.crop(bbox)

image_bytes = io.BytesIO()
cropped_image.save(image_bytes, format="PNG")
image_bytes.seek(0)
png = base64.b64encode(image_bytes.getvalue()).decode("utf-8")

return ImageContent(type="image", data=png, mimeType="image/png")

Key Operations: 1. Opens image using PIL 2. Crops using bbox coordinates (left, upper, right, lower) 3. Encodes cropped image to PNG in memory 4. Base64 encodes for transmission 5. Wraps in ImageContent with proper MIME type

get_weather

@app.tool(name="weather", description="query weather")
def get_weather(city: str):

Purpose: Demonstrates a simple text-based tool with predefined data

Parameters: - city (str): City name to query weather for

Returns: Dict with weather information (temp, condition) or error message

Implementation:

weather_data = {"Beijing": {"temp": 25, "condition": "Rainy"}, "Shanghai": {"temp": 28, "condition": "Cloudy"}}
result = weather_data.get(city, {"error": "未找到该城市"})
return result

Key Operations: 1. Hardcoded weather data for two cities 2. Lookup by city name 3. Returns error dict if city not found (Chinese message: "City not found")

get_blank_image

@app.tool(name="get_blank_image", description="get blank image")
def get_blank_image(width: int = 512, height: int = 512):

Purpose: Generates a blank white image of specified dimensions

Parameters: - width (int): Image width in pixels (default: 512) - height (int): Image height in pixels (default: 512)

Returns: ImageContent with base64-encoded PNG

Implementation:

image = Image.new("RGB", (width, height), color=(255, 255, 255))
image_bytes = io.BytesIO()
image.save(image_bytes, format="PNG")
image_bytes.seek(0)
png = base64.b64encode(image_bytes.getvalue()).decode("utf-8")
return ImageContent(type="image", data=png, mimeType="image/png")

Key Operations: 1. Creates new RGB image with white background 2. Saves to in-memory buffer as PNG 3. Base64 encodes image data 4. Wraps in ImageContent for MCP protocol

3. Server Entry Point

if __name__ == "__main__":
    app.run()

Launches the MCP server when script is executed.

Dependencies

- base64: For encoding images to base64 - io: For in-memory byte buffers (BytesIO) - typing: For type annotations (List) - mcp.server.fastmcp: FastMCP framework - mcp.types: MCP content types (ImageContent) - PIL.Image: For image creation and manipulation

Tool Patterns

Image Processing Tools

Both image_zoom_in_tool and get_blank_image demonstrate the pattern for image-returning tools: 1. Generate or process image using PIL 2. Save to BytesIO buffer as PNG 3. Base64 encode the bytes 4. Wrap in ImageContent with MIME type

Data Lookup Tools

The get_weather tool shows a simple lookup pattern: 1. Maintain static data structure 2. Lookup by key 3. Return dict with result or error 4. Can be extended with API calls or database queries

Usage Examples

Starting the Server

python examples/mcp_server/sample_mcp_server.py

Invoking Tools

from lmms_eval.mcp.client import MCPClient

client = MCPClient("examples/mcp_server/sample_mcp_server.py")

# Get available tools
functions = client.get_function_list_sync()

# Crop image region
result1 = client.run_tool_sync("image_zoom_in_tool", {
    "image_path": "/path/to/image.jpg",
    "bbox": [100, 100, 300, 300]
})

# Query weather
result2 = client.run_tool_sync("weather", {
    "city": "Beijing"
})

# Generate blank canvas
result3 = client.run_tool_sync("get_blank_image", {
    "width": 1024,
    "height": 768
})

Design Decisions

1. Minimal Server Setup: No version or complex config to keep example simple 2. Diverse Tool Types: Shows both image and text return types 3. Default Parameters: get_blank_image demonstrates optional params with defaults 4. Static Data: Weather tool uses hardcoded data for simplicity 5. Standard Image Format: PNG chosen for lossless quality and broad support

Extension Points

This server can be extended by: 1. Adding database or API calls to get_weather 2. Implementing more image transformations (rotate, filter, etc.) 3. Adding error handling for invalid image paths 4. Validating bbox coordinates 5. Supporting additional image formats 6. Adding authentication/authorization

Comparison with crop_video_mcp_server

| Aspect | sample_mcp_server | crop_video_mcp_server | |--------|-------------------|----------------------| | Complexity | Simple examples | Production-ready tool | | Validation | Minimal | Comprehensive | | Logging | None | Extensive | | Error Handling | Basic | Detailed with context | | Documentation | Sparse | Complete docstrings | | Use Case | Learning/template | Actual video processing |

Related Components

- Crop_Video_MCP_Server: More complex MCP server example - MCP_Client: Client for invoking these tools - Media_Handling: Framework's built-in media processing

Best Practices Demonstrated

1. Clear tool names and descriptions for LLM consumption 2. Type annotations for all parameters 3. Consistent return type patterns (ImageContent for images) 4. Default parameter values where appropriate 5. Simple, focused tool implementations 6. Standard image encoding approach

Common Use Cases

1. Prototyping: Quick testing of MCP tool concepts 2. Learning: Understanding MCP tool structure 3. Template: Starting point for custom tools 4. Testing: Validating MCP client implementations 5. Demonstration: Showing different tool return types