import argparse
from fastmcp import FastMCP
from pathlib import Path
# define mcp server name
mcp = FastMCP(name="Resource Server")
# basic resource
@mcp.resource("resource://greeting")
def greet() -> str:
"""Simple greet"""
return "Hey This Is Harsh👋"
# Image resource with URL - protocol://host//path
@mcp.resource("images://img.jpg", mime_type="image/jpeg") # defined uri -> returns in json output for resource calls
def fetch_image_bytes() -> bytes:
"""Returns Harsh's profile photo"""
file_path = Path("img.jpg").resolve() # file must be present at script route
if not file_path.exists():
raise FileNotFoundError(f"Image file not found: {file_path}")
return file_path.read_bytes()
async def run_tests():
print("Running tests for mcp_resources.py...")
from fastmcp import Client
async with Client(mcp) as client:
print("Pinging server...")
await client.ping()
print("Server is responsive.")
# Test resource://greeting using read_resource
try:
greeting_content = await client.read_resource("resource://greeting")
greeting = greeting_content[0].text
assert greeting == "Hey This Is Harsh👋", f"Greeting test failed: Expected 'Hey This Is Harsh👋', got '{greeting}'"
print(f"Greeting test passed. Output: {greeting}")
except Exception as e:
print(f"Greeting test failed with exception: {e}")
# Test images://img.jpg using read_resource
try:
image_content = await client.read_resource("images://img.jpg")
image_bytes = image_content[0].blob
print(f"Image resource test passed. Returned {len(image_bytes)} bytes.")
except FileNotFoundError:
print("Image resource test skipped: img.jpg not found. Please create img.jpg for a full test.")
except Exception as e:
print(f"Image resource test failed with exception: {e}")
print("Tests finished.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="MCP Resource Server")
parser.add_argument("--test", action="store_true", help="Run tests for the resources.")
args = parser.parse_args()
if args.test:
import asyncio
asyncio.run(run_tests())
else:
mcp.run(transport="stdio")