# /// script # requires-python = ">=3.10" # dependencies = ["mcp>=1.0", "openai>=1.0", "requests>=2.31"] # /// import os import base64 import tempfile import requests from urllib.parse import urlparse from mcp.server.fastmcp import FastMCP from openai import OpenAI mcp = FastMCP("Robust-Vision-Server") def is_valid_url(url: str) -> bool: """Return True iff the input is a syntactically valid http/https URL.""" try: result = urlparse(url) return all([result.scheme in ['http', 'https'], result.netloc]) except ValueError: return False def get_base64_from_local_file(file_path: str) -> str: """Read a local image file and encode it as a base64 data URI.""" if not os.path.exists(file_path): raise FileNotFoundError(f"local file not found: {file_path}") with open(file_path, "rb") as f: encoded = base64.b64encode(f.read()).decode('utf-8') # OpenRouter accepts a generic image/jpeg URI; the API infers the real format. return f"data:image/jpeg;base64,{encoded}" @mcp.tool() def analyze_image_with_openrouter( image_source: str, prompt: str = "Describe the image in detail and extract any salient text or information.", model_name: str = "bytedance-seed/seed-2.0-lite", ) -> str: """ Analyze an image with an OpenRouter vision model. Accepts both local file paths and remote http/https URLs. Remote images are downloaded to a temporary directory before being sent to the API. Args: image_source: absolute local path or http/https URL. prompt: instruction passed to the vision model. model_name: OpenRouter model id. """ api_key = os.getenv("OPENROUTER_API_KEY") if not api_key: return "Error: OPENROUTER_API_KEY is not set." client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key) # Branch A: remote URL — download to a temp dir, then call the API. if is_valid_url(image_source): with tempfile.TemporaryDirectory() as temp_dir: temp_file_path = os.path.join(temp_dir, "downloaded_image.tmp") try: headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "image/webp,image/apng,image/*,*/*;q=0.8", } response = requests.get(image_source, headers=headers, stream=True, timeout=15) response.raise_for_status() content_type = response.headers.get('Content-Type', '') if not content_type.startswith('image/'): return f"Download failed: target URL did not return an image (Content-Type: {content_type})." with open(temp_file_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) image_data_uri = get_base64_from_local_file(temp_file_path) except requests.exceptions.Timeout: return "Download failed: request timed out (>15s)." except requests.exceptions.HTTPError as err: return f"Download failed: HTTP error {err.response.status_code}." except requests.exceptions.RequestException as err: return f"Download failed: network error: {err}" except Exception as err: return f"Temp-file processing failed: {err}" # Call inside the `with` block so the temp file outlives the request. return _call_openrouter_api(client, model_name, prompt, image_data_uri) # Branch B: local file path. try: image_data_uri = get_base64_from_local_file(image_source) return _call_openrouter_api(client, model_name, prompt, image_data_uri) except Exception as err: return f"Local file processing failed: {err}" def _call_openrouter_api(client: OpenAI, model: str, prompt: str, image_data_uri: str) -> str: try: response = client.chat.completions.create( model=model, messages=[ { "role": "user", "content": [ {"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": image_data_uri}}, ], } ], ) return response.choices[0].message.content except Exception as err: return f"OpenRouter API call failed: {err}" if __name__ == "__main__": mcp.run()