Implementation:EvolvingLMMs Lab Lmms eval Sample MCP Server: Difference between revisions
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''': <code>examples/mcp_server/sample_mcp_server.py</code> | |||
'''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. | 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 === | |||
<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 === | |||
==== image_zoom_in_tool ==== | |||
<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 | |||
'''Parameters''': | |||
- | - <code>image_path</code> (str): Path to the input image file | ||
- | - <code>bbox</code> (List[float]): Bounding box coordinates [x_min, y_min, x_max, y_max] | ||
'''Returns''': ImageContent with base64-encoded PNG | |||
'''Implementation''': | |||
<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''': | |||
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 ==== | |||
<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 | |||
'''Parameters''': | |||
- | - <code>city</code> (str): City name to query weather for | ||
'''Returns''': Dict with weather information (temp, condition) or error message | |||
'''Implementation''': | |||
<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''': | |||
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 ==== | |||
<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 | |||
'''Parameters''': | |||
- | - <code>width</code> (int): Image width in pixels (default: 512) | ||
- | - <code>height</code> (int): Image height in pixels (default: 512) | ||
'''Returns''': ImageContent with base64-encoded PNG | |||
'''Implementation''': | |||
<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''': | |||
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 === | |||
<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 == | |||
- | - <code>base64</code>: For encoding images to base64 | ||
- | - <code>io</code>: For in-memory byte buffers (BytesIO) | ||
- | - <code>typing</code>: For type annotations (List) | ||
- | - <code>mcp.server.fastmcp</code>: FastMCP framework | ||
- | - <code>mcp.types</code>: MCP content types (ImageContent) | ||
- | - <code>PIL.Image</code>: For image creation and manipulation | ||
== Tool Patterns == | |||
=== Image Processing Tools === | |||
Both | 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 === | |||
The | 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 == | |||
=== Starting the Server === | |||
<syntaxhighlight lang="bash"> | |||
python examples/mcp_server/sample_mcp_server.py | python examples/mcp_server/sample_mcp_server.py | ||
</syntaxhighlight> | |||
=== Invoking Tools === | |||
<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 == | |||
1. | 1. '''Minimal Server Setup''': No version or complex config to keep example simple | ||
2. | 2. '''Diverse Tool Types''': Shows both image and text return types | ||
3. | 3. '''Default Parameters''': <code>get_blank_image</code> demonstrates optional params with defaults | ||
4. | 4. '''Static Data''': Weather tool uses hardcoded data for simplicity | ||
5. | 5. '''Standard Image Format''': PNG chosen for lossless quality and broad support | ||
== Extension Points == | |||
This server can be extended by: | This server can be extended by: | ||
1. Adding database or API calls to | 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 == | |||
| 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 == | |||
- [[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 == | |||
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 == | |||
1. | 1. '''Prototyping''': Quick testing of MCP tool concepts | ||
2. | 2. '''Learning''': Understanding MCP tool structure | ||
3. | 3. '''Template''': Starting point for custom tools | ||
4. | 4. '''Testing''': Validating MCP client implementations | ||
5. | 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