|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +MCP Everything Server - Conformance Test Server |
| 4 | +
|
| 5 | +Server implementing all MCP features for conformance testing based on Conformance Server Specification. |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import logging |
| 10 | + |
| 11 | +import click |
| 12 | +from mcp.server.fastmcp import Context, FastMCP |
| 13 | +from mcp.server.fastmcp.prompts.base import UserMessage |
| 14 | +from mcp.server.session import ServerSession |
| 15 | +from mcp.types import ( |
| 16 | + AudioContent, |
| 17 | + Completion, |
| 18 | + CompletionArgument, |
| 19 | + CompletionContext, |
| 20 | + EmbeddedResource, |
| 21 | + ImageContent, |
| 22 | + PromptReference, |
| 23 | + ResourceTemplateReference, |
| 24 | + SamplingMessage, |
| 25 | + TextContent, |
| 26 | + TextResourceContents, |
| 27 | +) |
| 28 | +from pydantic import AnyUrl, BaseModel, Field |
| 29 | + |
| 30 | +logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | +# Test data |
| 33 | +TEST_IMAGE_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==" |
| 34 | +TEST_AUDIO_BASE64 = "UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQIAAAA=" |
| 35 | + |
| 36 | +# Server state |
| 37 | +resource_subscriptions: set[str] = set() |
| 38 | +watched_resource_content = "Watched resource content" |
| 39 | + |
| 40 | +mcp = FastMCP( |
| 41 | + name="mcp-conformance-test-server", |
| 42 | +) |
| 43 | + |
| 44 | + |
| 45 | +# Tools |
| 46 | +@mcp.tool() |
| 47 | +def test_simple_text() -> str: |
| 48 | + """Tests simple text content response""" |
| 49 | + return "This is a simple text response for testing." |
| 50 | + |
| 51 | + |
| 52 | +@mcp.tool() |
| 53 | +def test_image_content() -> list[ImageContent]: |
| 54 | + """Tests image content response""" |
| 55 | + return [ImageContent(type="image", data=TEST_IMAGE_BASE64, mimeType="image/png")] |
| 56 | + |
| 57 | + |
| 58 | +@mcp.tool() |
| 59 | +def test_audio_content() -> list[AudioContent]: |
| 60 | + """Tests audio content response""" |
| 61 | + return [AudioContent(type="audio", data=TEST_AUDIO_BASE64, mimeType="audio/wav")] |
| 62 | + |
| 63 | + |
| 64 | +@mcp.tool() |
| 65 | +def test_embedded_resource() -> list[EmbeddedResource]: |
| 66 | + """Tests embedded resource content response""" |
| 67 | + return [ |
| 68 | + EmbeddedResource( |
| 69 | + type="resource", |
| 70 | + resource=TextResourceContents( |
| 71 | + uri=AnyUrl("test://embedded-resource"), |
| 72 | + mimeType="text/plain", |
| 73 | + text="This is an embedded resource content.", |
| 74 | + ), |
| 75 | + ) |
| 76 | + ] |
| 77 | + |
| 78 | + |
| 79 | +@mcp.tool() |
| 80 | +def test_multiple_content_types() -> list[TextContent | ImageContent | EmbeddedResource]: |
| 81 | + """Tests response with multiple content types (text, image, resource)""" |
| 82 | + return [ |
| 83 | + TextContent(type="text", text="Multiple content types test:"), |
| 84 | + ImageContent(type="image", data=TEST_IMAGE_BASE64, mimeType="image/png"), |
| 85 | + EmbeddedResource( |
| 86 | + type="resource", |
| 87 | + resource=TextResourceContents( |
| 88 | + uri=AnyUrl("test://mixed-content-resource"), |
| 89 | + mimeType="application/json", |
| 90 | + text='{"test": "data", "value": 123}', |
| 91 | + ), |
| 92 | + ), |
| 93 | + ] |
| 94 | + |
| 95 | + |
| 96 | +@mcp.tool() |
| 97 | +async def test_tool_with_logging(ctx: Context[ServerSession, None]) -> str: |
| 98 | + """Tests tool that emits log messages during execution""" |
| 99 | + await ctx.info("Tool execution started") |
| 100 | + await asyncio.sleep(0.05) |
| 101 | + |
| 102 | + await ctx.info("Tool processing data") |
| 103 | + await asyncio.sleep(0.05) |
| 104 | + |
| 105 | + await ctx.info("Tool execution completed") |
| 106 | + return "Tool with logging executed successfully" |
| 107 | + |
| 108 | + |
| 109 | +@mcp.tool() |
| 110 | +async def test_tool_with_progress(ctx: Context[ServerSession, None]) -> str: |
| 111 | + """Tests tool that reports progress notifications""" |
| 112 | + await ctx.report_progress(progress=0, total=100, message="Completed step 0 of 100") |
| 113 | + await asyncio.sleep(0.05) |
| 114 | + |
| 115 | + await ctx.report_progress(progress=50, total=100, message="Completed step 50 of 100") |
| 116 | + await asyncio.sleep(0.05) |
| 117 | + |
| 118 | + await ctx.report_progress(progress=100, total=100, message="Completed step 100 of 100") |
| 119 | + |
| 120 | + # Return progress token as string |
| 121 | + progress_token = ctx.request_context.meta.progressToken if ctx.request_context and ctx.request_context.meta else 0 |
| 122 | + return str(progress_token) |
| 123 | + |
| 124 | + |
| 125 | +class SamplingInput(BaseModel): |
| 126 | + prompt: str = Field(description="The prompt to send to the LLM") |
| 127 | + |
| 128 | + |
| 129 | +@mcp.tool() |
| 130 | +async def test_sampling(prompt: str, ctx: Context[ServerSession, None]) -> str: |
| 131 | + """Tests server-initiated sampling (LLM completion request)""" |
| 132 | + try: |
| 133 | + # Request sampling from client |
| 134 | + result = await ctx.session.create_message( |
| 135 | + messages=[SamplingMessage(role="user", content=TextContent(type="text", text=prompt))], |
| 136 | + max_tokens=100, |
| 137 | + ) |
| 138 | + |
| 139 | + if result.content.type == "text": |
| 140 | + model_response = result.content.text |
| 141 | + else: |
| 142 | + model_response = "No response" |
| 143 | + |
| 144 | + return f"LLM response: {model_response}" |
| 145 | + except Exception as e: |
| 146 | + return f"Sampling not supported or error: {str(e)}" |
| 147 | + |
| 148 | + |
| 149 | +class ElicitationInput(BaseModel): |
| 150 | + message: str = Field(description="The message to show the user") |
| 151 | + |
| 152 | + |
| 153 | +class UserResponse(BaseModel): |
| 154 | + response: str = Field(description="User's response") |
| 155 | + |
| 156 | + |
| 157 | +@mcp.tool() |
| 158 | +async def test_elicitation(message: str, ctx: Context[ServerSession, None]) -> str: |
| 159 | + """Tests server-initiated elicitation (user input request)""" |
| 160 | + try: |
| 161 | + # Request user input from client |
| 162 | + result = await ctx.elicit(message=message, schema=UserResponse) |
| 163 | + |
| 164 | + # Type-safe discriminated union narrowing using action field |
| 165 | + if result.action == "accept": |
| 166 | + content = result.data.model_dump_json() |
| 167 | + else: # decline or cancel |
| 168 | + content = "{}" |
| 169 | + |
| 170 | + return f"User response: action={result.action}, content={content}" |
| 171 | + except Exception as e: |
| 172 | + return f"Elicitation not supported or error: {str(e)}" |
| 173 | + |
| 174 | + |
| 175 | +@mcp.tool() |
| 176 | +def test_error_handling() -> str: |
| 177 | + """Tests error response handling""" |
| 178 | + raise RuntimeError("This tool intentionally returns an error for testing") |
| 179 | + |
| 180 | + |
| 181 | +# Resources |
| 182 | +@mcp.resource("test://static-text") |
| 183 | +def static_text_resource() -> str: |
| 184 | + """A static text resource for testing""" |
| 185 | + return "This is the content of the static text resource." |
| 186 | + |
| 187 | + |
| 188 | +@mcp.resource("test://static-binary") |
| 189 | +def static_binary_resource() -> bytes: |
| 190 | + """A static binary resource (image) for testing""" |
| 191 | + import base64 |
| 192 | + |
| 193 | + return base64.b64decode(TEST_IMAGE_BASE64) |
| 194 | + |
| 195 | + |
| 196 | +@mcp.resource("test://template/{id}/data") |
| 197 | +def template_resource(id: str) -> str: |
| 198 | + """A resource template with parameter substitution""" |
| 199 | + import json |
| 200 | + |
| 201 | + return json.dumps({"id": id, "templateTest": True, "data": f"Data for ID: {id}"}) |
| 202 | + |
| 203 | + |
| 204 | +@mcp.resource("test://watched-resource") |
| 205 | +def watched_resource() -> str: |
| 206 | + """A resource that can be subscribed to for updates""" |
| 207 | + return watched_resource_content |
| 208 | + |
| 209 | + |
| 210 | +# Prompts |
| 211 | +@mcp.prompt() |
| 212 | +def test_simple_prompt() -> list[UserMessage]: |
| 213 | + """A simple prompt without arguments""" |
| 214 | + return [UserMessage(role="user", content=TextContent(type="text", text="This is a simple prompt for testing."))] |
| 215 | + |
| 216 | + |
| 217 | +@mcp.prompt() |
| 218 | +def test_prompt_with_arguments(arg1: str, arg2: str) -> list[UserMessage]: |
| 219 | + """A prompt with required arguments""" |
| 220 | + return [ |
| 221 | + UserMessage( |
| 222 | + role="user", content=TextContent(type="text", text=f"Prompt with arguments: arg1='{arg1}', arg2='{arg2}'") |
| 223 | + ) |
| 224 | + ] |
| 225 | + |
| 226 | + |
| 227 | +@mcp.prompt() |
| 228 | +def test_prompt_with_embedded_resource(resourceUri: str) -> list[UserMessage]: |
| 229 | + """A prompt that includes an embedded resource""" |
| 230 | + return [ |
| 231 | + UserMessage( |
| 232 | + role="user", |
| 233 | + content=EmbeddedResource( |
| 234 | + type="resource", |
| 235 | + resource=TextResourceContents( |
| 236 | + uri=AnyUrl(resourceUri), |
| 237 | + mimeType="text/plain", |
| 238 | + text="Embedded resource content for testing.", |
| 239 | + ), |
| 240 | + ), |
| 241 | + ), |
| 242 | + UserMessage(role="user", content=TextContent(type="text", text="Please process the embedded resource above.")), |
| 243 | + ] |
| 244 | + |
| 245 | + |
| 246 | +@mcp.prompt() |
| 247 | +def test_prompt_with_image() -> list[UserMessage]: |
| 248 | + """A prompt that includes image content""" |
| 249 | + return [ |
| 250 | + UserMessage(role="user", content=ImageContent(type="image", data=TEST_IMAGE_BASE64, mimeType="image/png")), |
| 251 | + UserMessage(role="user", content=TextContent(type="text", text="Please analyze the image above.")), |
| 252 | + ] |
| 253 | + |
| 254 | + |
| 255 | +# Custom request handlers |
| 256 | +# TODO(felix): Add public APIs to FastMCP for subscribe_resource, unsubscribe_resource, |
| 257 | +# and set_logging_level to avoid accessing protected _mcp_server attribute. |
| 258 | +@mcp._mcp_server.set_logging_level() # pyright: ignore[reportPrivateUsage] |
| 259 | +async def handle_set_logging_level(level: str) -> None: |
| 260 | + """Handle logging level changes""" |
| 261 | + logger.info(f"Log level set to: {level}") |
| 262 | + # In a real implementation, you would adjust the logging level here |
| 263 | + # For conformance testing, we just acknowledge the request |
| 264 | + |
| 265 | + |
| 266 | +async def handle_subscribe(uri: AnyUrl) -> None: |
| 267 | + """Handle resource subscription""" |
| 268 | + resource_subscriptions.add(str(uri)) |
| 269 | + logger.info(f"Subscribed to resource: {uri}") |
| 270 | + |
| 271 | + |
| 272 | +async def handle_unsubscribe(uri: AnyUrl) -> None: |
| 273 | + """Handle resource unsubscription""" |
| 274 | + resource_subscriptions.discard(str(uri)) |
| 275 | + logger.info(f"Unsubscribed from resource: {uri}") |
| 276 | + |
| 277 | + |
| 278 | +mcp._mcp_server.subscribe_resource()(handle_subscribe) # pyright: ignore[reportPrivateUsage] |
| 279 | +mcp._mcp_server.unsubscribe_resource()(handle_unsubscribe) # pyright: ignore[reportPrivateUsage] |
| 280 | + |
| 281 | + |
| 282 | +@mcp.completion() |
| 283 | +async def _handle_completion( |
| 284 | + ref: PromptReference | ResourceTemplateReference, |
| 285 | + argument: CompletionArgument, |
| 286 | + context: CompletionContext | None, |
| 287 | +) -> Completion: |
| 288 | + """Handle completion requests""" |
| 289 | + # Basic completion support - returns empty array for conformance |
| 290 | + # Real implementations would provide contextual suggestions |
| 291 | + return Completion(values=[], total=0, hasMore=False) |
| 292 | + |
| 293 | + |
| 294 | +# CLI |
| 295 | +@click.command() |
| 296 | +@click.option("--port", default=3001, help="Port to listen on for HTTP") |
| 297 | +@click.option( |
| 298 | + "--log-level", |
| 299 | + default="INFO", |
| 300 | + help="Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)", |
| 301 | +) |
| 302 | +def main(port: int, log_level: str) -> int: |
| 303 | + """Run the MCP Everything Server.""" |
| 304 | + logging.basicConfig( |
| 305 | + level=getattr(logging, log_level.upper()), |
| 306 | + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 307 | + ) |
| 308 | + |
| 309 | + logger.info(f"Starting MCP Everything Server on port {port}") |
| 310 | + logger.info(f"Endpoint will be: http://localhost:{port}/mcp") |
| 311 | + |
| 312 | + mcp.settings.port = port |
| 313 | + mcp.run(transport="streamable-http") |
| 314 | + |
| 315 | + return 0 |
| 316 | + |
| 317 | + |
| 318 | +if __name__ == "__main__": |
| 319 | + main() |
0 commit comments