Skip to content

Tutorial scaffolding 01 #1293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 12 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ This document contains critical information about working with this codebase. Fo

2. Code Quality
- Type hints required for all code
- Public APIs must have docstrings
- All public members MUST have Google Python Style Guide-compliant docstrings
- Functions must be focused and small
- Follow existing patterns exactly
- Line length: 120 chars maximum
Expand All @@ -24,6 +24,10 @@ This document contains critical information about working with this codebase. Fo
- Coverage: test edge cases and errors
- New features require tests
- Bug fixes require regression tests
- Documentation
- Test changes in docs/ and Python docstrings: `uv run mkdocs build`
- On macOS: `export DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib & uv run mkdocs build`
- Fix WARNING and ERROR issues and re-run build until clean

- For commits fixing bugs or adding features based on user reports add:

Expand Down Expand Up @@ -132,3 +136,46 @@ This document contains critical information about working with this codebase. Fo
- **Only catch `Exception` for**:
- Top-level handlers that must not crash
- Cleanup blocks (log at debug level)

## Docstring best practices for SDK documentation

The following guidance ensures docstrings are genuinely helpful for new SDK users by providing navigation, context, and accurate examples.

### Structure and formatting

- Follow Google Python Style Guide for docstrings
- Format docstrings in Markdown compatible with mkdocs-material and mkdocstrings
- Always surround lists with blank lines (before and after) - also applies to Markdown (.md) files
- Always surround headings with blank lines - also applies to Markdown (.md) files
- Always surround fenced code blocks with blank lines - also applies to Markdown (.md) files
- Use sentence case for all headings and heading-like text - also applies to Markdown (.md) files

### Content requirements

- Access patterns: Explicitly state how users typically access the method/class with phrases like "You typically access this
method through..." or "You typically call this method by..."
- Cross-references: Use extensive cross-references to related members to help SDK users navigate:
- Format: [`displayed_text`][module.path.to.Member]
- Include backticks around the displayed text
- Link to types, related methods, and alternative approaches
- Parameter descriptions:
- Document all valid values for enums/literals
- Explain what each parameter does and when to use it
- Cross-reference parameter types where helpful
- Real-world examples:
- Show actual usage patterns from the SDK, not theoretical code
- Include imports and proper module paths
- Verify examples against source code for accuracy
- Show multiple approaches (e.g., low-level SDK vs FastMCP)
- Add comments explaining what's happening
- Examples should be concise and only as complex as needed to clearly demonstrate real-world usage
- Context and purpose:
- Explain not just what the method does, but why and when to use it
- Include notes about important considerations (e.g., client filtering, performance)
- Mention alternative approaches where applicable

### Verification

- All code examples MUST be 100% accurate to the actual SDK implementation
- Verify imports, class names, method signatures against source code
- You MUST NOT rely on existing documentation as authoritative - you MUST check the source
71 changes: 49 additions & 22 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ Thank you for your interest in contributing to the MCP Python SDK! This document
4. Clone your fork: `git clone https://github.com/YOUR-USERNAME/python-sdk.git`
5. Install dependencies:

```bash
uv sync --frozen --all-extras --dev
```
```bash
uv sync --frozen --all-extras --dev
```

6. Set up pre-commit hooks:

```bash
uv tool install pre-commit --with pre-commit-uv --force-reinstall
```
```bash
uv tool install pre-commit --with pre-commit-uv --force-reinstall
```

## Development Workflow

Expand All @@ -33,37 +33,64 @@ uv tool install pre-commit --with pre-commit-uv --force-reinstall

4. Ensure tests pass:

```bash
uv run pytest
```
```bash
uv run pytest
```

5. Run type checking:

```bash
uv run pyright
```
```bash
uv run pyright
```

6. Run linting:

```bash
uv run ruff check .
uv run ruff format .
```
```bash
uv run ruff check .
uv run ruff format .
```

7. Update README snippets if you modified example code:

```bash
uv run scripts/update_readme_snippets.py
```
```bash
uv run scripts/update_readme_snippets.py
```

8. (Optional) Run pre-commit hooks on all files:

```bash
pre-commit run --all-files
```
```bash
pre-commit run --all-files
```

9. Submit a pull request to the same branch you branched from

## Building and viewing documentation

To build and view the documentation locally:

1. Install documentation dependencies (included with `--dev` flag above):

```bash
uv sync --frozen --group docs
```

2. Serve the documentation locally:

```bash
uv run mkdocs serve
```

**Note for macOS users**: If you encounter a [Cairo library error](https://squidfunk.github.io/mkdocs-material/plugins/requirements/image-processing/#cairo-library-was-not-found), set the library path before running mkdocs:

```bash
export DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib
uv run mkdocs serve
```

3. Open your browser to `http://127.0.0.1:8000/python-sdk/` to view the documentation

The documentation will auto-reload when you make changes to files in `docs/`, `mkdocs.yml`, or `src/mcp/`.

## Code Style

- We use `ruff` for linting and formatting
Expand Down
1 change: 0 additions & 1 deletion docs/api.md

This file was deleted.

144 changes: 144 additions & 0 deletions docs/examples-authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Authentication examples

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

## Security considerations

When implementing authentication:

- **Use HTTPS**: All OAuth flows must use HTTPS in production
- **Token validation**: Always validate tokens on the resource server side
- **Scope checking**: Verify that tokens have required scopes
- **Introspection**: Use token introspection for distributed validation
- **RFC compliance**: Follow RFC 9728 for proper authoriazation server (AS) discovery

## OAuth architecture

The MCP OAuth implementation follows the OAuth 2.1 authorization code flow with token introspection:

```mermaid
sequenceDiagram
participant C as Client
participant AS as Authorization Server
participant RS as Resource Server<br/>(MCP Server)
participant U as User

Note over C,RS: 1. Discovery Phase (RFC 9728)
C->>RS: GET /.well-known/oauth-protected-resource
RS->>C: Protected Resource Metadata<br/>(issuer, scopes, etc.)

Note over C,AS: 2. Authorization Phase
C->>AS: GET /authorize?response_type=code&client_id=...
AS->>U: Redirect to login/consent
U->>AS: User authenticates and consents
AS->>C: Authorization code (via redirect)

Note over C,AS: 3. Token Exchange
C->>AS: POST /token<br/>(authorization_code grant)
AS->>C: Access token + refresh token

Note over C,RS: 4. Resource Access
C->>RS: MCP request + Authorization: Bearer <token>
RS->>AS: POST /introspect<br/>(validate token)
AS->>RS: Token info (active, scopes, user)
RS->>C: MCP response (if authorized)

Note over C,AS: 5. Token Refresh (when needed)
C->>AS: POST /token<br/>(refresh_token grant)
AS->>C: New access token
```

**Components:**

- **Authorization Server (AS)**: Handles OAuth flows, issues and validates tokens
- **Resource Server (RS)**: Your MCP server that validates tokens and serves protected resources
- **Client**: Discovers AS through RFC 9728, obtains tokens, and uses them with MCP server
- **User**: Resource owner who authorizes access

## OAuth server implementation

FastMCP server with OAuth token verification:

```python
--8<-- "examples/snippets/servers/oauth_server.py"
```

This example shows:

- Implementing the `TokenVerifier` protocol for token validation
- Using `AuthSettings` for RFC 9728 Protected Resource Metadata
- Resource server configuration with authorization server discovery
- Protected tools that require authentication

## Complete authentication server

Full Authorization Server implementation with token introspection:

```python
--8<-- "examples/servers/simple-auth/mcp_simple_auth/auth_server.py"
```

This comprehensive example includes:

- OAuth 2.1 authorization flows (authorization code, refresh token)
- Token introspection endpoint for resource servers
- Client registration and metadata management
- RFC 9728 protected resource metadata endpoint

## Resource server with introspection

MCP Resource Server that validates tokens via Authorization Server introspection:

```python
--8<-- "examples/servers/simple-auth/mcp_simple_auth/server.py"
```

This demonstrates:

- Token introspection for validation instead of local token verification
- Separation of Authorization Server (AS) and Resource Server (RS)
- Protected MCP tools and resources
- Production-ready server patterns

## Token verification implementation

Custom token verification logic:

```python
--8<-- "examples/servers/simple-auth/mcp_simple_auth/token_verifier.py"
```

This component handles:

- HTTP token introspection requests
- Token validation with scope checking
- RFC 8707 resource parameter validation
- Error handling and logging

## Simple authentication provider

Authentication provider for development and testing:

```python
--8<-- "examples/servers/simple-auth/mcp_simple_auth/simple_auth_provider.py"
```

This utility provides:

- Simplified token generation for testing
- Development authentication flows
- Testing utilities for protected resources

## Legacy Authorization Server

Backward compatibility with older OAuth implementations:

```python
--8<-- "examples/servers/simple-auth/mcp_simple_auth/legacy_as_server.py"
```

This example shows:

- Support for non-RFC 9728 compliant clients
- Legacy endpoint compatibility
- Migration patterns for existing systems
Loading
Loading