claude-ia-mcp-tools-auth
Herramientas MCP con autenticación OAuth
Un ejemplo en Python que demuestra cómo construir un servidor MCP (Model Context Protocol) con autenticación OAuth, combinando un cliente de API, una capa de lógica de negocio y herramientas MCP protegidas.
Características
Flujo de autenticación OAuth: autenticación con un clic en el navegador para tokens de sesión
Arquitectura en capas: Cliente de API → Lógica de negocio → Herramientas MCP
Acceso seguro a las herramientas: Requiere un token de autenticación válido para llamar a las herramientas protegidas
Servidor HTTP simple: servidor de autenticación basado en que se opone** "Serventa en
localhost:5000Gestión de se token tokens: tokens de sesión de 24 horas con persistencia
Related MCP server: OAuth MCP Server
Arquitectura
src/example/
├── api/
│ ├── api_client.py # HTTP API client (JSONPlaceholder)
│ └── http_server.py # Local HTTP server
├── auth/
│ └── manager.py # OAuth token & state management
├── business/
│ └── service.py # Business logic layer
├── http/
│ └── auth_server.py # Flask OAuth auth server
├── mcp/
│ └── server.py # MCP server with auth
└── main.pyInstalación
python -m venv .venv
# Windows:
.venv\Scripts\activate
# Linux/macOS:
source .venv/bin/activate
pip install -r requirements.txtInicio rápido
1. Inicia el servidor de autenticación
python -m src.example.http.auth_serverEsto inicia un servidor Flask en http://localhost:5000 con un flujo de autenticación OAuth:
Visita la página de inicio
Hace cl ic en "Click to Authenticate"
Obén tu token de sesión en la página de llamca
Copia y guarda tu token
2. Inicia el servidor MCP
En otro terminal:
python -m src.example.mcp.server3. Usa las herramientos MCP
El servidor MCP ahora requieren la autenticación. Peña, obén la URL de autenticación:
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | python -m src.example.mcp.serverLuego autentícate y usa las herramientos con tu token:
echo '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"get_user","arguments":{"user_id":1},"auth_token":"YOUR_SESSION_TOKEN"},"id":1}' | python -m src.example.mcp.serverFlujo de autenticación
Obén la URL de autenticación: Llaa a la herramiento
get_auth_url(no es necesaria la autenticación){"jsonrpc":"2.0","method":"tools/call","params":{"name":"get_auth_url","arguments":{}},"id":1}Clic en el navegador: El usuario hce cl ic en la URL de autenticación devuelta
E se el
http://localhost:5000/auth/callback?state=...
El navegador mustra una página de éxito con el token de sesión
El token es válido durante 24 horas
Usa the token: Include
auth_tokenen todas las llamadas a la herramientas{"params":{"name":"get_user","arguments":{"user_id":1},"auth_token":"YOUR_TOKEN"}}
Herramientas as disponibles
Públicas (sin autenticación)
get_auth_url- Obén la URL de autenticator OAuth
Protegidas (autenticator requerida)
get_user- Obén un usuario por IDlist_users- Listar todos los usuarioscreate_user- Crear un nuevo usuarioupdate_user- Actualizar el nombre/correo electrónico del de usuariodelete_user- Elimina a un usuario
Configuración
Establee las variables de entorno:
export PORT=5000 # Auth server port
export FLASK_SECRET_KEY=your-secret-key # Flask secret (change in production!)Pruebas
Ejecuta las pruebas con pytest:
pytest -v
pytest --cov=src # With coverage
pytest tests/test_auth.py # Auth tests onlyEjecuta el script de shell
sh test-auth-flow.sh
========================================
MCP Auth Server - Complete Flow Test
========================================
Base URL: https://claude-ia-mcp-tools-auth-staging.up.railway.app
Step 1: Start Auth Flow
GET /auth/start
Status: 401
Auth URL: https://claude-ia-mcp-tools-auth-staging.up.railway.app/auth/callback?state=Xukdt6MwHba0n0UfkOX3lAAanm7MJhSyzomyCJCxj1M
State Token: Xukdt6MwHba0n0UfkOX3lAAanm7MJhSyzomyCJCx...
Step 2: Complete Auth Callback
GET /auth/callback?state=Xukdt6MwHba0n0UfkOX3lAAanm7MJhSyzomyCJCxj1M
Status: 200
Session Token: 7Y6SaanfrLmiOXoE2kUvTbdEfawIMSJyGDaNFPf1...
Step 3: Verify Token with Auth Status
GET /auth/status -H 'Authorization: Bearer 7Y6SaanfrLmiOXoE2kUvTbdEfawIMSJyGDaNFPf1-Bg'
Response:
{"authenticated":true,"user_id":"user_1b25e4982c9904b8"}
========================================
TEST RESULTS
========================================
State Token: Xukdt6MwHba0n0UfkOX3lAAanm7MJhSyzomyCJCxj1M
Session Token: 7Y6SaanfrLmiOXoE2kUvTbdEfawIMSJyGDaNFPf1-Bg
Authenticated: true
User ID: user_1b25e4982c9904b8
========================================
Step 4: Test Invalid Token
GET /auth/status -H 'Authorization: Bearer invalid_token_123'
Response: {"authenticated":false,"user_id":null}
SUCCESS: Complete auth flow working correctly!
You can now use this token for MCP:
Authorization: Bearer 7Y6SaanfrLmiOXoE2kUvTbdEfawIMSJyGDaNFPf1-Bg
Despliegue
Para producción, actualiza:
FLASK_SECRET_KEY - Usa una clave aleatoria fuerte
Proveedor de OAuth - Reemplaza por un proveedor de code** OAuth real (Google, GitHub, etc.)
Almacenamiento de tokens - Usa una base de datos en lugar de
.auth_tokens.jsonHTTPS - Habilita SSL/TLS para los endpoints de autenticación
Notas de arquitectura
Este ejemplo demuestra:
Separación de responsabilidades: El cliente de API, la lógica de negocio y la capa MCP son independientes
Diseño en capas: Fácil de probar y reemplazar componentes
Integración de autenticación: Los tokens de autenticación se pasan a través de los parámetros, no de los encabezados
Manejo de errores: Respuestas de error apropiadas para fallos de autenticación
El cliente de lahttps://jsonplaceholder.typicode.com como API de demostración.
Replaza por tu propia implementación de API sin cambiar las interfaces MCP/negocio.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA complete OAuth 2.1 server implementation for FastMCP with PKCE support, enabling secure authentication and authorization flows. Provides authorization code exchange, token management, and refresh capabilities for building authenticated MCP applications.
- FlicenseNot gradedqualityDmaintenanceAn MCP server for OAuth 2.0 authentication supporting Device Code and Client Credentials flows, enabling secure token management for MCP applications.
- FlicenseNot gradedqualityDmaintenanceA simple MCP server with OAuth 2.0 authentication for testing OAuth support in mcp-cli.
- FlicenseNot gradedqualityCmaintenanceThis MCP server requires user authentication via Auth0 and then enables calling protected APIs (e.g., a Todos API) on behalf of the user.
Related MCP Connectors
Self-hosted federated MCP gateway: one OAuth 2.1 MCP server in front of N apps, user-level scopes.
MCP server for Argo RPG Platform — connects AI assistants to campaign data via OAuth2
Streamable HTTP MCP server for Google Calendar and Sheets with OAuth login.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/vicboma1/claude-ia-mcp-tools-auth'
If you have feedback or need assistance with the MCP directory API, please join our Discord server