This example demonstrates how to use the authentication framework with the Model Context Protocol (MCP) Go SDK.
The MCP SDK provides a pluggable authentication system that supports multiple authentication methods:
- Bearer Token Authentication: For session-based authentication with refresh tokens
- API Key Authentication: For long-lived service-to-service authentication
- Custom Authentication: Implement your own authentication provider
- Creating and validating bearer tokens
- Token expiration and refresh
- Session-based authentication flow
- Generating secure API keys
- API key validation
- Rate limiting support (configurable)
- Protecting MCP server endpoints
- Role-based access control (RBAC)
- Permission-based tool filtering
go run main.goAuthentication providers implement the AuthProvider interface:
type AuthProvider interface {
Authenticate(ctx context.Context, req *AuthRequest) (*AuthResult, error)
Validate(ctx context.Context, token string) (*UserInfo, error)
Refresh(ctx context.Context, refreshToken string) (*AuthResult, error)
Revoke(ctx context.Context, token string) error
Type() string
}Enable authentication in your transport configuration:
config := transport.DefaultTransportConfig(transport.TransportTypeStreamableHTTP)
config.Features.EnableAuthentication = true
config.Security.Authentication = &transport.AuthenticationConfig{
Type: "bearer",
Required: true,
TokenExpiry: 10 * time.Minute,
EnableCache: true,
CacheTTL: 5 * time.Minute,
}Pass authentication tokens via context:
ctx := auth.ContextWithToken(context.Background(), token)
result, err := client.SendRequest(ctx, "method", params)The authentication system supports RBAC with configurable permissions:
config.Security.Authentication.RBAC = &auth.RBACConfig{
Enabled: true,
DefaultRole: "user",
ResourcePermissions: map[string][]string{
"admin_tool": {"admin"},
"write_data": {"write"},
"read_data": {"read"},
},
}- Always use HTTPS in production for HTTP transports
- Implement token expiration and refresh mechanisms
- Use secure random generation for tokens and API keys
- Enable token caching to improve performance
- Implement rate limiting for API endpoints
- Log authentication events for security auditing
In production, replace the in-memory token storage with:
- Redis for distributed systems
- Database for persistent storage
- Secure key management service
Consider using established authentication services:
- OAuth2/OIDC providers (Auth0, Okta, etc.)
- JWT token validation
- LDAP/Active Directory integration
For HTTP transports, configure security headers:
- CORS policies
- Rate limiting
- Request size limits
- TLS configuration
Implement custom authentication by creating your own AuthProvider:
type CustomAuthProvider struct {
// Your implementation
}
func (p *CustomAuthProvider) Authenticate(ctx context.Context, req *AuthRequest) (*AuthResult, error) {
// Custom authentication logic
}The authentication middleware includes built-in token caching:
- Reduces validation overhead
- Configurable TTL and size limits
- Automatic cleanup of expired entries
Authentication integrates seamlessly with other middleware:
- Reliability (retries, circuit breakers)
- Observability (metrics, logging)
- Rate limiting
- Import cycle errors: Make sure to import the auth package to register the middleware factory
- Token validation failures: Check token expiration and format
- Permission denied: Verify user roles and permissions configuration
Enable debug logging to troubleshoot authentication issues:
config.Observability.EnableLogging = true
config.Observability.LogLevel = "debug"