MCP Protocol Sampling
Understanding Model Context Protocol (MCP) sampling through hands-on examples and debugging real library issues.
Overview
This project helps you understand MCP sampling by:
- Identifying and documenting bugs in the mcp-go library
- Providing working reference implementations
- Offering debugging tools and techniques
- Creating educational resources for the community
Prerequisites
Required: Understanding of Server-Sent Events (SSE) and bidirectional communication patterns.
If you’re new to SSE, start with: Learn SSE Bidirectional
Quick Start
# Clone the repository
git clone https://github.com/hardwaylabs/learn-mcp-sampling
cd learn-mcp-sampling
# Set up environment
export ANTHROPIC_API_KEY="your-api-key-here" # For real LLM integration
export MCP_DEBUG=1 # Enable verbose logging
# Test working examples
go run mcp-implementations/cmd/enhanced-server/main.go # Terminal 1
go run mcp-implementations/cmd/enhanced-client/main.go # Terminal 2
go run debugging-tools/cmd/test-workflow/main.go # Terminal 3
What You’ll Learn
1. MCP Protocol
How sampling should work in theory:
- Protocol specifications
- Message flow patterns
- Session management
- Error handling
2. Library Analysis
What’s broken in mcp-go implementation:
- SSE connection issues
- Missing transport options
- Session management bugs
- Event parsing problems
3. Reference Implementation
Working examples for comparison:
- Clean SSE connections
- Proper bidirectional communication
- Real Anthropic API integration
- Multi-modal content support
4. Debugging Techniques
Tools and methods for protocol analysis:
- Connection testing utilities
- Event stream monitoring
- Request/response correlation
- Session lifecycle tracking
Project Structure
learn-mcp-sampling/
├── working-examples/ # SSE reference implementations
│ ├── basic-sse-server/ # How SSE should work
│ └── basic-sse-client/ # Clean connection example
├── mcp-implementations/ # MCP protocol examples
│ ├── enhanced-server/ # Real file analysis server
│ ├── enhanced-client/ # Anthropic API integration
│ └── simulate-sampling/ # Working simulation
├── debugging-tools/ # Analysis and testing
│ ├── test-workflow/ # End-to-end testing
│ ├── check-sampling-clients/# Connection diagnostics
│ └── analysis/ # Bug documentation
└── files/ # Sample files for testing
How MCP Sampling Works
Intended Flow
- MCP Client declares sampling capability
- Tool needs LLM analysis
- MCP Server sends sampling request via SSE
- MCP Client processes with LLM API
- MCP Client returns results via HTTP POST
- MCP Server provides results to tool
Current Issues
The mcp-go library has fundamental SSE implementation issues:
- Connection timeouts: “context deadline exceeded” errors
- Missing features: Need for
WithContinuousListening()
- Session bugs: Improper header handling
- Parsing errors: SSE stream processing failures
Our Solution
Enhanced implementations that work correctly:
- ✅ Instant SSE message delivery
- ✅ Proper bidirectional communication
- ✅ Real Anthropic API integration
- ✅ Multi-modal content support
Real-World Implementation
File Analysis System
The enhanced implementation demonstrates:
Server capabilities:
- Serves local files for analysis
- Supports text, images, and PDFs
- Handles security (path traversal protection)
- Provides detailed logging
Client features:
- Uses Claude 3.5 Sonnet for analysis
- Supports summarization and code analysis
- Handles visual content understanding
- Monitors token usage and costs
Example Usage
// Server: Analyze a file
func (s *Server) AnalyzeFile(path string) (*Analysis, error) {
// Send sampling request via SSE
request := &SamplingRequest{
ID: generateID(),
Method: "analyze_file",
Params: map[string]interface{}{"path": path},
}
// Wait for LLM response
response := <-s.responseChannel
return parseAnalysis(response), nil
}
// Client: Process with LLM
func (c *Client) HandleSamplingRequest(req *Request) {
// Call Anthropic API
response, _ := c.anthropic.Messages.Create(&anthropic.MessageRequest{
Model: anthropic.Claude35Sonnet,
Messages: []anthropic.Message{{Content: req.Prompt}},
})
// Return via HTTP POST
c.SendResponse(req.ID, response.Content)
}
Debugging Workflow
1. Test Basic Connectivity
# Check if servers can connect
go run debugging-tools/cmd/check-sampling-clients/main.go
2. Monitor SSE Streams
# Debug SSE message delivery
go run debugging-tools/cmd/debug-server/main.go
3. Run Full Workflow
# Test complete sampling cycle
go run debugging-tools/cmd/test-workflow/main.go
4. Analyze Results
Check for:
- Connection establishment patterns
- Event delivery timing
- Response correlation
- Error conditions
Known Issues & Solutions
Issue: “context deadline exceeded”
Problem: mcp-go StreamableHTTP times out
Solution: Use our enhanced implementation or WithContinuousListening()
Issue: No sampling requests received
Problem: Server not registering tools properly Solution: Verify tool registration and capability declaration
Issue: Authentication errors
Problem: Missing or invalid API key
Solution: Set ANTHROPIC_API_KEY
environment variable
Issue: Connection drops
Problem: Network or proxy interference Solution: Check firewall rules, use HTTPS in production
Contributing to mcp-go
This project helps fix the mcp-go library by providing:
Evidence
- Clear reproduction of bugs
- Detailed error documentation
- Performance comparisons
Solutions
- Working reference implementations
- Proposed fixes with tests
- Migration guides
How to Help
- Use our tools to identify issues
- Reference our implementations for correct behavior
- Submit PRs to mcp-go with evidence
- Test fixes using our validation suite
Advanced Features
Multi-Modal Analysis
- Text files (code, docs, configs)
- Images (screenshots, diagrams)
- PDFs (reports, documentation)
- Custom prompts for specific analysis
Production Patterns
- Rate limiting for API calls
- Token usage monitoring
- Error recovery strategies
- Horizontal scaling support
Learning Path
Phase 1: Understand the Problem
- Read the analysis documentation
- Run working SSE examples
- Try broken MCP implementations
- Compare behaviors
Phase 2: Study Solutions
- Enhanced server with file analysis
- Client with Anthropic integration
- Simulation of intended behavior
Phase 3: Debug and Fix
- Use debugging tools
- Analyze library code
- Propose and test fixes
Resources
Common Use Cases
LLM Integration
Servers request LLM analysis for complex tasks, clients handle API calls.
Remote Code Execution
IDE integration with cloud development environments.
Interactive Workflows
Multi-step processes requiring human or AI input.
Support
- Open issues on GitHub
- Check analysis documents for known problems
- Join discussions about mcp-go improvements