Skip to content

Commit dbd4a43

Browse files
committed
Add a simple module documentation to help LLMs with the pattern
LLMs have issue infering the actual usage pattern from the code itself. We add a simple module documentation to help with that.
1 parent 54952ca commit dbd4a43

File tree

4 files changed

+146
-0
lines changed

4 files changed

+146
-0
lines changed

src/mcp/server/__init__.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,62 @@
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+
"""
160
import contextvars
261
import logging
362
import warnings

src/mcp/server/session.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,39 @@
1+
"""
2+
ServerSession Module
3+
4+
This module provides the ServerSession class, which manages communication between the server and client
5+
in the MCP (Model Context Protocol) framework. It is most commonly used in MCP servers to interact
6+
with the client.
7+
8+
Common usage pattern:
9+
```
10+
server = Server(name)
11+
12+
@server.call_tool()
13+
async def handle_tool_call(ctx: RequestContext, arguments: dict[str, Any]) -> Any:
14+
# Check client capabilities before proceeding
15+
if ctx.session.check_client_capability(types.ClientCapabilities(experimental={"advanced_tools": True})):
16+
# Perform advanced tool operations
17+
result = await perform_advanced_tool_operation(arguments)
18+
else:
19+
# Fall back to basic tool operations
20+
result = await perform_basic_tool_operation(arguments)
21+
22+
return result
23+
24+
@server.list_prompts()
25+
async def handle_list_prompts(ctx: RequestContext) -> list[types.Prompt]:
26+
# Access session for any necessary checks or operations
27+
if ctx.session.client_params:
28+
# Customize prompts based on client initialization parameters
29+
return generate_custom_prompts(ctx.session.client_params)
30+
else:
31+
return default_prompts
32+
```
33+
34+
The ServerSession class is typically used internally by the Server class and should not be
35+
instantiated directly by users of the MCP framework.
36+
"""
137
from enum import Enum
238
from typing import Any
339

src/mcp/server/sse.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,35 @@
1+
"""
2+
SSE Server Transport Module
3+
4+
This module implements a Server-Sent Events (SSE) transport layer for MCP servers.
5+
6+
Example usage:
7+
```
8+
# Create an SSE transport at an endpoint
9+
sse = SseServerTransport("/messages")
10+
11+
# Create Starlette routes for SSE and message handling
12+
routes = [
13+
Route("/sse", endpoint=handle_sse),
14+
Route("/messages", endpoint=handle_messages, methods=["POST"])
15+
]
16+
17+
# Define handler functions
18+
async def handle_sse(request):
19+
async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
20+
await app.run(streams[0], streams[1], app.create_initialization_options())
21+
22+
async def handle_messages(request):
23+
await sse.handle_post_message(request.scope, request.receive, request._send)
24+
25+
# Create and run Starlette app
26+
starlette_app = Starlette(routes=routes)
27+
uvicorn.run(starlette_app, host="0.0.0.0", port=port)
28+
```
29+
30+
See SseServerTransport class documentation for more details.
31+
"""
32+
133
import logging
234
from contextlib import asynccontextmanager
335
from typing import Any

src/mcp/server/stdio.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,22 @@
1+
"""
2+
Stdio Server Transport Module
3+
4+
This module provides functionality for creating an stdio-based transport layer
5+
that can be used to communicate with an MCP client through standard input/output streams.
6+
7+
Example usage:
8+
```
9+
async def run_server():
10+
async with stdio_server() as (read_stream, write_stream):
11+
# read_stream contains incoming JSONRPCMessages from stdin
12+
# write_stream allows sending JSONRPCMessages to stdout
13+
server = await create_my_server()
14+
await server.run(read_stream, write_stream, init_options)
15+
16+
anyio.run(run_server)
17+
```
18+
"""
19+
120
import sys
221
from contextlib import asynccontextmanager
322

0 commit comments

Comments
 (0)