Skip to content

Commit 74040f1

Browse files
mmacyclaude
andauthored
Enhance SDK docstrings and documentation (#9)
* misc doc work * Enhance SDK docstrings for better new user experience Add comprehensive documentation for key MCP SDK methods and request context: - send_log_message: Access patterns, logging levels, examples - check_client_capability: Capability checking with real examples - elicit methods: Interactive data collection documentation - Request context ecosystem: RequestContext, Context, access patterns - Cross-references and practical examples throughout All changes follow Google Python Style Guide and include verified code examples. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3add4e6 commit 74040f1

16 files changed

+1140
-293
lines changed

CLAUDE.md

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,45 @@ This document contains critical information about working with this codebase. Fo
133133
- Top-level handlers that must not crash
134134
- Cleanup blocks (log at debug level)
135135

136-
- Always use sentence case for all headings and heading-like text in any Markdown-formatted content, including docstrings.
137-
- Example snippets in docsstrings MUST only appear within the Examples section of the docstring. You MAY include multiple examples in the Examples section.
138-
- Surround all lists, both ordered and unordered, with blank lines. Applies to Markdown in Markdown files as well as docstrings in Python files.
136+
## Docstring best practices for SDK documentation
137+
138+
The following guidance ensures docstrings are genuinely helpful for new SDK users by providing navigation, context, and accurate examples.
139+
140+
### Structure and formatting
141+
142+
- Follow Google Python Style Guide for docstrings
143+
- Format docstrings in Markdown compatible with mkdocs-material and mkdocstrings
144+
- Always surround lists with blank lines (before and after) - also applies to Markdown (.md) files
145+
- Always surround headings with blank lines - also applies to Markdown (.md) files
146+
- Always surround fenced code blocks with blank lines - also applies to Markdown (.md) files
147+
- Use sentence case for all headings and heading-like text - also applies to Markdown (.md) files
148+
149+
### Content requirements
150+
151+
- Access patterns: Explicitly state how users typically access the method/class with phrases like "You typically access this
152+
method through..." or "You typically call this method by..."
153+
- Cross-references: Use extensive cross-references to related members to help SDK users navigate:
154+
- Format: [`displayed_text`][module.path.to.Member]
155+
- Include backticks around the displayed text
156+
- Link to types, related methods, and alternative approaches
157+
- Parameter descriptions:
158+
- Document all valid values for enums/literals
159+
- Explain what each parameter does and when to use it
160+
- Cross-reference parameter types where helpful
161+
- Real-world examples:
162+
- Show actual usage patterns from the SDK, not theoretical code
163+
- Include imports and proper module paths
164+
- Verify examples against source code for accuracy
165+
- Show multiple approaches (e.g., low-level SDK vs FastMCP)
166+
- Add comments explaining what's happening
167+
- Examples should be concise and only as complex as needed to clearly demonstrate real-world usage
168+
- Context and purpose:
169+
- Explain not just what the method does, but why and when to use it
170+
- Include notes about important considerations (e.g., client filtering, performance)
171+
- Mention alternative approaches where applicable
172+
173+
### Verification
174+
175+
- All code examples MUST be 100% accurate to the actual SDK implementation
176+
- Verify imports, class names, method signatures against source code
177+
- You MUST NOT rely on existing documentation as authoritative - you MUST check the source

docs/examples-authentication.md

Lines changed: 53 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,59 @@
22

33
MCP supports OAuth 2.1 authentication for protecting server resources. This section demonstrates both server-side token verification and client-side authentication flows.
44

5+
## Security considerations
6+
7+
When implementing authentication:
8+
9+
- **Use HTTPS**: All OAuth flows must use HTTPS in production
10+
- **Token validation**: Always validate tokens on the resource server side
11+
- **Scope checking**: Verify that tokens have required scopes
12+
- **Introspection**: Use token introspection for distributed validation
13+
- **RFC compliance**: Follow RFC 9728 for proper authoriazation server (AS) discovery
14+
15+
## OAuth architecture
16+
17+
The MCP OAuth implementation follows the OAuth 2.1 authorization code flow with token introspection:
18+
19+
```mermaid
20+
sequenceDiagram
21+
participant C as Client
22+
participant AS as Authorization Server
23+
participant RS as Resource Server<br/>(MCP Server)
24+
participant U as User
25+
26+
Note over C,RS: 1. Discovery Phase (RFC 9728)
27+
C->>RS: GET /.well-known/oauth-protected-resource
28+
RS->>C: Protected Resource Metadata<br/>(issuer, scopes, etc.)
29+
30+
Note over C,AS: 2. Authorization Phase
31+
C->>AS: GET /authorize?response_type=code&client_id=...
32+
AS->>U: Redirect to login/consent
33+
U->>AS: User authenticates and consents
34+
AS->>C: Authorization code (via redirect)
35+
36+
Note over C,AS: 3. Token Exchange
37+
C->>AS: POST /token<br/>(authorization_code grant)
38+
AS->>C: Access token + refresh token
39+
40+
Note over C,RS: 4. Resource Access
41+
C->>RS: MCP request + Authorization: Bearer <token>
42+
RS->>AS: POST /introspect<br/>(validate token)
43+
AS->>RS: Token info (active, scopes, user)
44+
RS->>C: MCP response (if authorized)
45+
46+
Note over C,AS: 5. Token Refresh (when needed)
47+
C->>AS: POST /token<br/>(refresh_token grant)
48+
AS->>C: New access token
49+
```
50+
51+
**Components:**
52+
53+
- **Authorization Server (AS)**: Handles OAuth flows, issues and validates tokens
54+
- **Resource Server (RS)**: Your MCP server that validates tokens and serves protected resources
55+
- **Client**: Discovers AS through RFC 9728, obtains tokens, and uses them with MCP server
56+
- **User**: Resource owner who authorizes access
57+
558
## OAuth server implementation
659

760
FastMCP server with OAuth token verification:
@@ -89,58 +142,3 @@ This example shows:
89142
- Support for non-RFC 9728 compliant clients
90143
- Legacy endpoint compatibility
91144
- Migration patterns for existing systems
92-
93-
## OAuth architecture
94-
95-
The MCP OAuth implementation follows the OAuth 2.1 authorization code flow with token introspection:
96-
97-
```mermaid
98-
sequenceDiagram
99-
participant C as Client
100-
participant AS as Authorization Server
101-
participant RS as Resource Server<br/>(MCP Server)
102-
participant U as User
103-
104-
Note over C,RS: 1. Discovery Phase (RFC 9728)
105-
C->>RS: GET /.well-known/oauth-protected-resource
106-
RS->>C: Protected Resource Metadata<br/>(issuer, scopes, etc.)
107-
108-
Note over C,AS: 2. Authorization Phase
109-
C->>AS: GET /authorize?response_type=code&client_id=...
110-
AS->>U: Redirect to login/consent
111-
U->>AS: User authenticates and consents
112-
AS->>C: Authorization code (via redirect)
113-
114-
Note over C,AS: 3. Token Exchange
115-
C->>AS: POST /token<br/>(authorization_code grant)
116-
AS->>C: Access token + refresh token
117-
118-
Note over C,RS: 4. Resource Access
119-
C->>RS: MCP request + Authorization: Bearer <token>
120-
RS->>AS: POST /introspect<br/>(validate token)
121-
AS->>RS: Token info (active, scopes, user)
122-
RS->>C: MCP response (if authorized)
123-
124-
Note over C,AS: 5. Token Refresh (when needed)
125-
C->>AS: POST /token<br/>(refresh_token grant)
126-
AS->>C: New access token
127-
```
128-
129-
**Components:**
130-
131-
- **Authorization Server (AS)**: Handles OAuth flows, issues and validates tokens
132-
- **Resource Server (RS)**: Your MCP server that validates tokens and serves protected resources
133-
- **Client**: Discovers AS through RFC 9728, obtains tokens, and uses them with MCP server
134-
- **User**: Resource owner who authorizes access
135-
136-
## Security considerations
137-
138-
When implementing authentication:
139-
140-
1. **Use HTTPS**: All OAuth flows must use HTTPS in production
141-
2. **Token validation**: Always validate tokens on the resource server side
142-
3. **Scope checking**: Verify that tokens have required scopes
143-
4. **Introspection**: Use token introspection for distributed validation
144-
5. **RFC compliance**: Follow RFC 9728 for proper AS discovery
145-
146-
These examples provide a complete OAuth 2.1 implementation suitable for production use with proper security practices.

docs/examples-clients.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
MCP clients connect to servers to access tools, resources, and prompts. This section demonstrates various client patterns and connection types.
44

5+
These examples provide comprehensive patterns for building MCP clients that can handle various server types, authentication methods, and interaction patterns.
6+
57
## Basic stdio client
68

79
Connecting to MCP servers over stdio transport:
@@ -123,5 +125,3 @@ This example demonstrates:
123125
- Token management and refresh
124126
- Protected resource access
125127
- Integration with authenticated MCP servers
126-
127-
These examples provide comprehensive patterns for building MCP clients that can handle various server types, authentication methods, and interaction patterns.

docs/examples-echo-servers.md

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
# Echo server examples
22

3-
Echo servers are simple examples that demonstrate basic MCP functionality by echoing input back to clients. These are useful for testing and understanding MCP fundamentals.
3+
Echo servers provide a foundation for understanding MCP patterns before building more complex functionality.
4+
5+
Echo servers are useful for:
6+
7+
- **Testing client connections**: Verify that your client can connect and call tools
8+
- **Understanding MCP basics**: Learn the fundamental request/response patterns
9+
- **Development and debugging**: Simple, predictable behavior for testing
10+
- **Protocol verification**: Ensure transport layers work correctly
11+
12+
The following servers are minimal examples that demonstrate basic MCP functionality by echoing input back to clients.
413

514
## Simple echo server
615

@@ -30,14 +39,7 @@ This enhanced version demonstrates:
3039
- Different parameter types and patterns
3140
- Tool naming and description best practices
3241

33-
Echo servers are useful for:
34-
35-
- **Testing client connections**: Verify that your client can connect and call tools
36-
- **Understanding MCP basics**: Learn the fundamental request/response patterns
37-
- **Development and debugging**: Simple, predictable behavior for testing
38-
- **Protocol verification**: Ensure transport layers work correctly
39-
40-
## Usage patterns
42+
## Usage
4143

4244
These echo servers can be used to test different aspects of MCP:
4345

@@ -66,10 +68,9 @@ Example tool calls you can make to echo servers:
6668
```
6769

6870
Expected response:
71+
6972
```json
7073
{
7174
"result": "Echo: Hello, MCP!"
7275
}
7376
```
74-
75-
Echo servers provide a foundation for understanding MCP patterns before building more complex functionality.

docs/examples-lowlevel-servers.md

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,30 @@
11
# Low-level server examples
22

3-
The low-level server API provides maximum control over MCP protocol implementation. Use these patterns when you need fine-grained control or when FastMCP doesn't meet your requirements.
3+
The [low-level server API](/python-sdk/reference/mcp/server/lowlevel/server/) provides maximum control over MCP protocol implementation. Use these patterns when you need fine-grained control or when [`FastMCP`][mcp.server.fastmcp.FastMCP] doesn't meet your requirements.
4+
5+
The low-level API provides the foundation that FastMCP is built upon, giving you access to all MCP protocol features with complete control over implementation details.
6+
7+
## When to use low-level API
8+
9+
Choose the low-level API when you need:
10+
11+
- Custom protocol message handling
12+
- Complex initialization sequences
13+
- Fine-grained control over capabilities
14+
- Integration with existing server infrastructure
15+
- Performance optimization at the protocol level
16+
- Custom authentication or authorization logic
17+
18+
Key differences between the low-level server API and FastMCP are:
19+
20+
| | Low-level API | FastMCP |
21+
| --------------- | ------------------------ | ----------------------------- |
22+
| **Control** | Maximum control | Convention over configuration |
23+
| **Boilerplate** | More verbose | Minimal setup |
24+
| **Decorators** | Server method decorators | Simple function decorators |
25+
| **Schema** | Manual definition | Automatic from type hints |
26+
| **Lifecycle** | Manual management | Automatic handling |
27+
| **Best for** | Complex custom logic | Rapid development |
428

529
## Basic low-level server
630

@@ -12,7 +36,7 @@ Fundamental low-level server patterns:
1236

1337
This example demonstrates:
1438

15-
- Creating a `Server` instance directly
39+
- Creating a [`Server`][mcp.server.lowlevel.Server] instance directly
1640
- Manual handler registration with decorators
1741
- Prompt management with `@server.list_prompts()` and `@server.get_prompt()`
1842
- Manual capability declaration
@@ -69,27 +93,3 @@ This production-ready example includes:
6993
- Input validation and error handling
7094
- Proper MCP protocol compliance
7195
- Tool execution with structured responses
72-
73-
## Key differences from FastMCP
74-
75-
| Aspect | Low-level API | FastMCP |
76-
|--------|---------------|---------|
77-
| **Control** | Maximum control | Convention over configuration |
78-
| **Boilerplate** | More verbose | Minimal setup |
79-
| **Decorators** | Server method decorators | Simple function decorators |
80-
| **Schema** | Manual definition | Automatic from type hints |
81-
| **Lifecycle** | Manual management | Automatic handling |
82-
| **Best for** | Complex custom logic | Rapid development |
83-
84-
## When to use low-level API
85-
86-
Choose the low-level API when you need:
87-
88-
- Custom protocol message handling
89-
- Complex initialization sequences
90-
- Fine-grained control over capabilities
91-
- Integration with existing server infrastructure
92-
- Performance optimization at the protocol level
93-
- Custom authentication or authorization logic
94-
95-
The low-level API provides the foundation that FastMCP is built upon, giving you access to all MCP protocol features with complete control over implementation details.

docs/examples-quickstart.md

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,21 @@
22

33
This section provides quick and simple examples to get you started with the MCP Python SDK.
44

5+
These examples can be run directly with:
6+
7+
```bash
8+
python server.py
9+
```
10+
11+
Or test with the MCP Inspector:
12+
13+
```bash
14+
uv run mcp dev server.py
15+
```
16+
517
## FastMCP quickstart
618

7-
The simplest way to create an MCP server is with FastMCP. This example demonstrates the core concepts: tools, resources, and prompts.
19+
The easiest way to create an MCP server is with [`FastMCP`][mcp.server.fastmcp.FastMCP]. This example demonstrates the core concepts: tools, resources, and prompts.
820

921
```python
1022
--8<-- "examples/snippets/servers/fastmcp_quickstart.py"
@@ -38,15 +50,3 @@ This example demonstrates:
3850
- Minimal server setup with just a greeting tool
3951
- Direct execution without additional configuration
4052
- Entry point setup for standalone running
41-
42-
All these examples can be run directly with:
43-
44-
```bash
45-
python server.py
46-
```
47-
48-
Or tested with the MCP Inspector:
49-
50-
```bash
51-
uv run mcp dev server.py
52-
```

0 commit comments

Comments
 (0)