|
| 1 | +""" |
| 2 | +MCP Server Module |
| 3 | +
|
| 4 | +This module provides a framework for creating an MCP (Machine Comprehension Protocol) server. |
| 5 | +It allows you to easily define and handle various types of requests and notifications |
| 6 | +in an asynchronous manner. |
| 7 | +
|
| 8 | +Usage: |
| 9 | +1. Create a Server instance: |
| 10 | + server = Server("your_server_name") |
| 11 | +
|
| 12 | +2. Define request handlers using decorators: |
| 13 | + @server.list_prompts() |
| 14 | + async def handle_list_prompts() -> list[types.Prompt]: |
| 15 | + # Implementation |
| 16 | +
|
| 17 | + @server.get_prompt() |
| 18 | + async def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> types.GetPromptResult: |
| 19 | + # Implementation |
| 20 | +
|
| 21 | + @server.list_tools() |
| 22 | + async def handle_list_tools() -> list[types.Tool]: |
| 23 | + # Implementation |
| 24 | +
|
| 25 | + @server.call_tool() |
| 26 | + async def handle_call_tool(name: str, arguments: dict | None) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: |
| 27 | + # Implementation |
| 28 | +
|
| 29 | +3. Define notification handlers if needed: |
| 30 | + @server.progress_notification() |
| 31 | + async def handle_progress(progress_token: str | int, progress: float, total: float | None) -> None: |
| 32 | + # Implementation |
| 33 | +
|
| 34 | +4. Run the server: |
| 35 | + async def main(): |
| 36 | + async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): |
| 37 | + await server.run( |
| 38 | + read_stream, |
| 39 | + write_stream, |
| 40 | + InitializationOptions( |
| 41 | + server_name="your_server_name", |
| 42 | + server_version="your_version", |
| 43 | + capabilities=server.get_capabilities( |
| 44 | + notification_options=NotificationOptions(), |
| 45 | + experimental_capabilities={}, |
| 46 | + ), |
| 47 | + ), |
| 48 | + ) |
| 49 | +
|
| 50 | + asyncio.run(main()) |
| 51 | +
|
| 52 | +The Server class provides methods to register handlers for various MCP requests and notifications. |
| 53 | +It automatically manages the request context and handles incoming messages from the client. |
| 54 | +
|
| 55 | +For more advanced usage, you can customize the server's capabilities, handle resource requests, |
| 56 | +implement logging, and add completion support for prompts and resources. |
| 57 | +
|
| 58 | +Refer to the method docstrings and type hints for detailed information on each handler and its expected inputs and outputs. |
| 59 | +""" |
1 | 60 | import contextvars |
2 | 61 | import logging |
3 | 62 | import warnings |
|
0 commit comments