Implementing OAuth 2.1 for MCP Servers with Scalekit
Securing applications with OAuth 2.1 can seem daunting, but using Scalekit simplifies the process significantly. In this guide, we’ll implement OAuth 2.1 for an MCP server that analyzes stock sentiment in the finance sector. By following these step-by-step instructions, you can set up a secure server that handles authenticated requests seamlessly.
Setting Up Dependencies
1. Alpha Vantage API
First, we’ll use the Alpha Vantage API to fetch stock news sentiment. Here’s how to get your API key:
- Visit the Alpha Vantage platform.
- Fill in your email and other requested details.
- Copy your API key, keeping it secure for later use.
2. Node.js Installation
Node.js is required to run the MCP Inspector for testing purposes. Follow these installation steps:
- Download the latest version from nodejs.org.
- Run the installer and accept default settings to complete installation.
3. Python Dependencies
Install the necessary Python packages using the command:
pip install fastapi fastmcp mcp scalekit-sdk-python
Using Scalekit
Account Setup
Create a Scalekit account by visiting scalekit.com. After signing up:
- Click on “Activate Full-Stack Auth”.
- Open the Authorization panel and add a new permission:
- Permission Name: news:read
- Description: Use Alpha Vantage to get Stock Sentiment
Adding Your MCP Server
In the MCP Servers section, click on “Add MCP Server” and fill in the following:
- Server Name: Your preferred name.
- Resource Identifier: A unique identifier, e.g.,
http://localhost:10000/mcp/
. - Scope: Set to
news:read
.
Obtaining API Credentials
Go to Settings and find your API Credentials:
- Copy the Client ID and the Environment URL.
- Generate a new Secret Key and store it securely.
Configuration File Creation
Create a config.py
file where all environment variables will be stored:
import os
from dotenv import load_dotenv
load_dotenv()
class Settings():
ALPHA_VANTAGE_API_KEY = os.environ.get('ALPHA_VANTAGE_API_KEY')
# Other variables ...
PORT = 10000
settings = Settings()
Stock Sentiment Logic
We need to fetch real-time news sentiment data using the Alpha Vantage API:
from mcp.server.fastmcp import FastMCP
import httpx
from config import settings
mcp = FastMCP("finance-news")
async def call_alpha_vantage(endpoint: str, params: dict) -> dict | None:
params["apikey"] = settings.ALPHA_VANTAGE_API_KEY
async with httpx.AsyncClient() as client:
response = await client.get(BASE_URL, params=params)
return response.json()
@mcp.tool()
async def get_news_sentiment(ticker: str) -> str:
data = await call_alpha_vantage("NEWS_SENTIMENT", {"tickers": ticker.upper()})
# Logic to return formatted article summaries...
Authorization Middleware
This middleware ensures only authenticated requests are processed. It validates access tokens and logs key events:
from fastapi import HTTPException, Request
from scalekit import ScalekitClient
class AuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Authorization logic...
Setting Up the MCP Server
The main server application uses FastAPI and integrates the custom middleware:
import uvicorn
from fastapi import FastAPI
from auth import AuthMiddleware
from finance import mcp as finance_news_server
app = FastAPI()
app.add_middleware(AuthMiddleware)
@app.get("/.well-known/oauth-protected-resource/mcp")
async def oauth_protected_resource_metadata():
return {"authorization_servers": [settings.SCALEKIT_AUTHORIZATION_SERVERS], ...}
Running the Server
To start your server, run:
python server.py
Then, use the MCP Inspector to connect and test the setup. Enter http://localhost:10000/mcp
as the server URL and provide the Bearer token to authenticate successfully.
Conclusion
Using OAuth 2.1 with Scalekit greatly simplifies securing your MCP server. By following these steps, you can easily implement secure token-based authentication and set up an efficient sentiment analysis service for stock news. With proper configuration and middleware in place, your server is ready to handle authenticated requests confidently.
Frequently Asked Questions
- What is OAuth 2.1? OAuth 2.1 is an industry-standard protocol for authorization that allows applications to securely access user data.
- How does Scalekit simplify OAuth implementation? Scalekit abstracts the complex flows of OAuth, allowing developers to focus on building features rather than managing token generation and validation.
- What is the Alpha Vantage API? It is a service that provides real-time and historical stock market data, including news sentiment.
- Do I need advanced coding skills to implement this? Basic knowledge of Python and API usage is required, but the guide provides step-by-step instructions.
- Can I use Scalekit for other types of applications? Yes, Scalekit is designed to work with various applications needing secure authentication, not just for finance-related ones.