Universal OAuth middleware library for MCP (Model Context Protocol) servers with support for any OAuth provider.
Overview
This library provides OAuth authentication for MCP servers using a flexible connector pattern. It handles the complete OAuth flow for any OAuth provider and provides an authenticated endpoint where you create your own MCP server with tools. Built using the official .
Universal OAuth middleware library for MCP (Model Context Protocol) servers with support for any OAuth provider.
import express from "express"
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"
import { McpOAuth } from "mcp-s-oauth"
import type { McpOAuthConfig } from "mcp-s-oauth"
const app = express()
// Choose your OAuth provider connector
import { githubConnector } from "mcp-s-oauth"
// or import { googleConnector } from "mcp-s-oauth"
// or create your own custom connector
// Configure OAuth with any provider
const config: McpOAuthConfig = {
baseUrl: "http://localhost:3000",
clientId: "your-oauth-client-id",
clientSecret: "your-oauth-client-secret",
connector: githubConnector // or any other connector
}
// Create your MCP handler - this is where YOU create the MCP server
const mcpHandler = async (req: express.Request, res: express.Response, { authInfo }) => {
// Access the OAuth token from any provider
const oauthToken = authInfo.token
// Create transport and your MCP server
const transport = new StreamableHTTPServerTransport(/* options */)
const mcpServer = new Server({ name: "my-server", version: "1.0.0" })
// Register your tools (customize based on your OAuth provider)
mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{
name: "get_profile",
description: "Get authenticated user profile",
inputSchema: { type: "object" }
}]
}))
mcpServer.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "get_profile") {
// Call your OAuth provider's API using the token
// Example for GitHub: https://api.github.com/user
// Example for Google: https://www.googleapis.com/oauth2/v2/userinfo
const apiUrl = "https://api.github.com/user" // adjust for your provider
const response = await fetch(apiUrl, {
headers: { "Authorization": `Bearer ${authInfo.token}` }
})
const userData = await response.json()
return {
content: [{ type: "text", text: `Profile: ${JSON.stringify(userData, null, 2)}` }]
}
}
})
// Handle the MCP request
await mcpServer.connect(transport)
await transport.handleRequest(req, res, req.body)
}
// Use the library
const mcpOAuth = McpOAuth(config, mcpHandler)
app.use("/", mcpOAuth.router)
app.listen(3000)
Form vs JSON: Check provider docs for token endpoint format
Field Names: Response might use different field names
Scopes: Ensure scopes are valid for your provider
Callback URL: Must match OAuth app configuration
Example Tools Implementation
The tools you create depend on your OAuth provider and their APIs. The library provides the OAuth token - you implement the tools. Here's a complete GitHub example:
For other OAuth providers, follow the same pattern using their respective APIs:
Slack: Use https://slack.com/api/ endpoints
Google Services: Use Google API endpoints (Gmail, Drive, Sheets, etc.)
Notion: Use https://api.notion.com/v1/ endpoints
Jira: Use Atlassian REST API endpoints
And more... - Each connector works with the provider's standard OAuth API
MCP Client Usage
Using with MCP Clients
Your OAuth-authenticated MCP server implements the MCP (Model Context Protocol) and can be used with any MCP-compatible client:
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
const client = new Client({
name: "oauth-mcp-client",
version: "1.0.0"
})
const transport = new StreamableHTTPClientTransport(
new URL("http://localhost:3000/mcp")
)
await client.connect(transport)
// List available tools (depends on your implementation)
const tools = await client.listTools()
console.log("Available tools:", tools)
// Call any tool you've implemented
const result = await client.callTool({
name: "get_profile", // or any tool name you've implemented
arguments: {}
})
console.log("Result:", result)
Authentication Flow
Start OAuth Flow: Make a request to /auth/authorize to initiate OAuth with your provider
User Authorization: User is redirected to OAuth provider to authorize your application
Token Exchange: Provider redirects back with an authorization code
MCP Access: Use the obtained token to make authenticated MCP requests to /mcp
API Reference
Server Information
GET / - Server information, available tools, and authentication endpoints
GET /health - Health check endpoint
Authentication Endpoints
POST /auth/authorize - Start OAuth flow with configured provider
POST /auth/token - Exchange authorization code for access token
GET /oauth/callback - OAuth callback handler (used by the provider)
MCP Protocol
ALL /mcp - Main MCP endpoint supporting all MCP protocol methods
Requires Bearer token authentication
Supports session management with mcp-session-id header
Handles tools/list and tools/call requests
Returns tools you've implemented in your mcpHandler
Testing the Server
Test the MCP server using the official SDK client:
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
// Connect to the server
const client = new Client({ name: "test-client", version: "1.0.0" })
const transport = new StreamableHTTPClientTransport(
new URL("http://localhost:3000/mcp"),
{
requestInit: {
headers: {
'Authorization': 'Bearer your-oauth-token-here'
}
}
}
)
await client.connect(transport)
// Test listing tools
const tools = await client.listTools()
console.log("Available tools:", tools.tools)
// Test calling any tool you've implemented
const result = await client.callTool({
name: "get_profile", // or any tool name you've implemented
arguments: {}
})
console.log("Result:", result.content)
# Install dependencies
npm install
# Development mode with auto-reload
npm run dev
# Build for production
npm run build
# Run production build
npm start
# Run tests
npm test
# Lint code
npm run lint
# Format code
npm run format
Adding New Tools
To add new MCP tools to your server:
Update the tools list in ListToolsRequestSchema handler
Add tool implementation in CallToolRequestSchema handler
Use the OAuth token to call your provider's APIs
Example (provider-agnostic):
// In ListToolsRequestSchema handler
{
name: "get_user_data",
description: "Get user data from OAuth provider",
inputSchema: {
type: "object",
properties: {
fields: {
type: "array",
items: { type: "string" },
description: "Fields to retrieve"
}
}
}
}
// In CallToolRequestSchema handler
if (name === "get_user_data") {
const { fields = [] } = request.params.arguments || {}
// Use the OAuth token to call your provider's API
const apiUrl = "https://api.your-provider.com/user" // adjust for your provider
const response = await fetch(apiUrl, {
headers: {
"Authorization": `Bearer ${authInfo.token}`,
"Accept": "application/json"
}
})
const userData = await response.json()
return {
content: [{
type: "text",
text: JSON.stringify(userData, null, 2)
}]
}
}
Security Considerations
OAuth Secrets: Never commit OAuth client secrets to version control
HTTPS: Use HTTPS in production for secure OAuth flows
Environment Variables: Store all sensitive configuration in environment variables
Token Storage: Tokens are managed by the MCP SDK OAuth provider
OAuth App Configuration: Configure your OAuth app with correct callback URLs
Scope Limitation: Request only the OAuth scopes your application needs
Token Validation: The library handles token validation automatically
Troubleshooting
Common Issues
"Missing required environment variables"
Ensure your OAuth provider's CLIENT_ID and CLIENT_SECRET are set
Check environment variable names match your configuration
OAuth callback errors
Verify your BASE_URL matches your OAuth app configuration
Check that Authorization callback URL is set to ${baseUrl}/oauth/callback
Ensure your OAuth provider app is configured correctly
Token exchange errors
Check isForm setting in your connector - most providers use form encoding
Verify tokenUrl is correct for your provider
Check if provider requires special headers or parameters
API rate limits
Authenticated requests usually have higher rate limits
Consider implementing caching for frequently accessed data
Check your provider's rate limiting documentation
MCP client connection issues
Ensure you're using the correct MCP endpoint URL: /mcp
Verify Bearer token authentication is properly configured
Check that your tools are properly registered in the mcpHandler
Connector issues
Verify OAuth URLs are correct for your provider
Check scopes are valid for your provider
Test OAuth flow manually in browser first
Debug Mode
Enable detailed logging by setting environment variables:
DEBUG=mcp:*
NODE_ENV=development
Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
Visit webrix.ai for our fully managed hosting solution with advanced features:
Zero Configuration: Get started in seconds without any setup
Enterprise-grade Security: Advanced SSO authentication for all MCP interactions
20+ Pre-built Connectors: Fast plug-and-play integration with hundreds of tools
Roles & Permissions: Granular access control with custom role definitions
Monitoring & Analytics: Real-time insights into your MCP usage
High Availability: 99.9% uptime SLA with global CDN
Premium Support: Direct access to our engineering team
Custom Integrations: Build and deploy custom MCP connectors
M
MCP S Oauth
webrix-ai·4 estrelas·
Universal OAuth middleware library for MCP (Model Context Protocol) servers with support for any OAuth provider.
Ainda não há lista de ferramentas. Servidores remotos recebem uma após a primeira verificação de saúde.
Perguntas frequentes
Perguntas
Como instalo MCP S Oauth?
Copie nesta página a configuração stdio para Cursor, Claude Desktop, Claude Code ou VS Code. Ela usa a instalação do publicador, não um proxy do PlugMCP.
MCP S Oauth precisa de uma chave de API?
Este registro não lista nenhuma variável de ambiente obrigatória.
Qual transporte MCP S Oauth usa?
MCP S Oauth roda localmente via stdio.
Quando MCP S Oauth foi verificado pela última vez?
Última verificação: 2026-10-27. Universal OAuth middleware library for MCP (Model Context Protocol) servers with support for any OAuth provider.