Skip to content

Commit 33f0e59

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 33f0e59

File tree

4 files changed

+161
-3
lines changed

4 files changed

+161
-3
lines changed

src/mcp/server/__init__.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,65 @@
1+
"""
2+
MCP Server Module
3+
4+
This module provides a framework for creating an MCP (Model Context 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(
19+
name: str, arguments: dict[str, str] | None
20+
) -> types.GetPromptResult:
21+
# Implementation
22+
23+
@server.list_tools()
24+
async def handle_list_tools() -> list[types.Tool]:
25+
# Implementation
26+
27+
@server.call_tool()
28+
async def handle_call_tool(
29+
name: str, arguments: dict | None
30+
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
31+
# Implementation
32+
33+
3. Define notification handlers if needed:
34+
@server.progress_notification()
35+
async def handle_progress(
36+
progress_token: str | int, progress: float, total: float | None
37+
) -> None:
38+
# Implementation
39+
40+
4. Run the server:
41+
async def main():
42+
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
43+
await server.run(
44+
read_stream,
45+
write_stream,
46+
InitializationOptions(
47+
server_name="your_server_name",
48+
server_version="your_version",
49+
capabilities=server.get_capabilities(
50+
notification_options=NotificationOptions(),
51+
experimental_capabilities={},
52+
),
53+
),
54+
)
55+
56+
asyncio.run(main())
57+
58+
The Server class provides methods to register handlers for various MCP requests and
59+
notifications. It automatically manages the request context and handles incoming
60+
messages from the client.
61+
"""
62+
163
import contextvars
264
import logging
365
import warnings

src/mcp/server/session.py

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,42 @@
1+
"""
2+
ServerSession Module
3+
4+
This module provides the ServerSession class, which manages communication between the
5+
server and client in the MCP (Model Context Protocol) framework. It is most commonly
6+
used in MCP servers to interact 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(
16+
types.ClientCapabilities(experimental={"advanced_tools": True})
17+
):
18+
# Perform advanced tool operations
19+
result = await perform_advanced_tool_operation(arguments)
20+
else:
21+
# Fall back to basic tool operations
22+
result = await perform_basic_tool_operation(arguments)
23+
24+
return result
25+
26+
@server.list_prompts()
27+
async def handle_list_prompts(ctx: RequestContext) -> list[types.Prompt]:
28+
# Access session for any necessary checks or operations
29+
if ctx.session.client_params:
30+
# Customize prompts based on client initialization parameters
31+
return generate_custom_prompts(ctx.session.client_params)
32+
else:
33+
return default_prompts
34+
```
35+
36+
The ServerSession class is typically used internally by the Server class and should not
37+
be instantiated directly by users of the MCP framework.
38+
"""
39+
140
from enum import Enum
241
from typing import Any
342

@@ -72,8 +111,10 @@ def check_client_capability(self, capability: types.ClientCapabilities) -> bool:
72111
return False
73112
# Check each experimental capability
74113
for exp_key, exp_value in capability.experimental.items():
75-
if (exp_key not in client_caps.experimental or
76-
client_caps.experimental[exp_key] != exp_value):
114+
if (
115+
exp_key not in client_caps.experimental
116+
or client_caps.experimental[exp_key] != exp_value
117+
):
77118
return False
78119

79120
return True
@@ -117,7 +158,6 @@ async def _received_notification(
117158
"Received notification before initialization was complete"
118159
)
119160

120-
121161
async def send_log_message(
122162
self, level: types.LoggingLevel, data: Any, logger: str | None = None
123163
) -> None:

src/mcp/server/sse.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,39 @@
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(
20+
request.scope, request.receive, request._send
21+
) as streams:
22+
await app.run(
23+
streams[0], streams[1], app.create_initialization_options()
24+
)
25+
26+
async def handle_messages(request):
27+
await sse.handle_post_message(request.scope, request.receive, request._send)
28+
29+
# Create and run Starlette app
30+
starlette_app = Starlette(routes=routes)
31+
uvicorn.run(starlette_app, host="0.0.0.0", port=port)
32+
```
33+
34+
See SseServerTransport class documentation for more details.
35+
"""
36+
137
import logging
238
from contextlib import asynccontextmanager
339
from typing import Any

src/mcp/server/stdio.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
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
6+
streams.
7+
8+
Example usage:
9+
```
10+
async def run_server():
11+
async with stdio_server() as (read_stream, write_stream):
12+
# read_stream contains incoming JSONRPCMessages from stdin
13+
# write_stream allows sending JSONRPCMessages to stdout
14+
server = await create_my_server()
15+
await server.run(read_stream, write_stream, init_options)
16+
17+
anyio.run(run_server)
18+
```
19+
"""
20+
121
import sys
222
from contextlib import asynccontextmanager
323

0 commit comments

Comments
 (0)