Close Menu
  • AI
  • Content Creation
  • Tech
  • Robotics
AI-trends.todayAI-trends.today
  • AI
  • Content Creation
  • Tech
  • Robotics
Trending
  • Dragos Finds Immediate Leaks and Stolen Keys in AI Provide Chains
  • Lean and Mathlib Communities Certify Claude-Assisted Riemann Proof – Unite.AI
  • AWS Routes HyperPod Inference Throughout Areas From One Endpoint – Unite.AI
  • DailyAI Briefing: A Lean-checked Riemann proof, plus 4 extra
  • Anthropic Shares Drop 8.5% in Second Session Throughout AI Selloff – Unite.AI
  • OpenAI Ships GPT-Stay-1.1 for Voice Brokers, Cuts Idle Value to $0.02/Min
  • Copywriting: The Full Information | Copyblogger
  • AI Governance in 2027: Accountability Strikes Into the Workflow – Unite.AI
AI-trends.todayAI-trends.today
Home»Tech»How to implement OAuth 2.1 with Scalekit for MCP servers: A step-by-step coding tutorial

How to implement OAuth 2.1 with Scalekit for MCP servers: A step-by-step coding tutorial

Tech By Gavin Wallace01/09/202510 Mins Read
Facebook Twitter LinkedIn Email
Can LLMs Really Judge with Reasoning? Microsoft and Tsinghua Researchers
Can LLMs Really Judge with Reasoning? Microsoft and Tsinghua Researchers
Share
Facebook Twitter LinkedIn Email

We’ll look at how OAuth 2.1 can be implemented for MCP in this tutorial. serverIt’s step-by-step. Scalekit is a powerful tool for setting up OAuth that will make the process faster.

Scalekit allows us to expose an endpoint metadata URL to MCP clients so they can discover our server. We then add middleware to authorize token-based secure authentication. Scalekit manages all complex OAuth 2.0 flows in the background, so there’s no need for you to implement, maintain, or validate tokens manually. After this is done, the MCP server will be ready to authenticate requests. Look at the FULL CODES here.

Alpha Vantage API

We’ll be using the Alpha Vantage API to fetch sentiment on stock news. Get a free API Key:

  • Alpha Vantage is available on this platform. link
  • Fill in your details and email.
  • You’ll receive your API key—copy it and store it securely, as you’ll need it to authenticate your requests.

Node JS

Run the MCP Inspector Node.js is required to test our application.

  • Node.js Download Latest Version nodejs.org
  • Download and install the installer.
  • Install the program using the default options.

Python Dependencies

Pip install fastapi mcp fastmcp Scalekit-Sdk-Python

Scalekit

Start using ScalekitFollow these steps to get started:

Scalekit accounts can be created by logging into your account.

  • Click here to go scalekit.com Sign up for our newsletter.
  • Scalekit has a free version, which means you won’t have to deal with billing.
  • Click “Sign in” to continue. “Activate Full-Stack Auth.”

Install Permissions

  • The Authorization Panel will open.
  • In the Permissions Section, click “Add Permission.”
  • You can use the following values to calculate your value:

Permission name: news:read

Description: You can use Alpha Vantage for Stock Sentiment

Scalekit’s permissions allow you to manage and define scopes, which control the features or resources that your application has access to. As an example, you can use the news:read Other permissions can be added to your application to allow you to add additional features and APIs.

You can add your MCP server

  • Click on the MCP Servers link. “Add MCP Server.”
  • Complete the fields required:

Server Name Any name you prefer.

Resource Identifier A unique identifier for your MCP server. This value helps the server to validate requests by including it in the aud claims of access tokens.

Set the local test as follows:

http://localhost:10000/mcp/

FastMCP adds the /mcp endpoint automatically. Include the trailing slash to prevent configuration problems. See the FULL CODES here.

You can now set the scope of the permission that you have just created. news:read

Scalekit creates resource metadata after the server has already been set up. Note down the MCP Server Identifier, which is located next to the name of the server, e.g. res_88056357768398086), as you’ll need it later.

Sample Metadata for Resource

This is what your metadata should look like (but will be unique to you):

Metadata Endpoint URL:

/.well-known/oauth-protected-resource/mcp

Resource Metadata in JSON

{
  "authorization_servers": [
    "https://zapp.scalekit.dev/resources/res_88056357768398086"
  ],
  "bearer_methods_supported": ["header"],
  "resource": "http://localhost:10000/mcp/",
  "resource_documentation": "http://localhost:10000/mcp/docs",
  "scopes_supported": ["news:read"]
}

API Credentials

  • Go to Settings → API Credentials.
  • Your Client ID, Environment URL and the client’s name will be copied.
  • To create your secret key, click Generate New Secret.

Store these values securely — we’ll need them later for configuration.

.env

Now we will create an.env with the variables below

ALPHA_VANTAGE_API_KEY=
METADATA_JSON_RESPONSE=

SCALEKIT_ENVIRONMENT_URL=
SCALEKIT_CLIENT_ID=
SCALEKIT_CLIENT_SECRET=
SCALEKIT_RESOURCE_METADATA_URL=
SCALEKIT_AUTHORIZATION_SERVERS=
SCALEKIT_AUDIENCE_NAME=
SCALEKIT_RESOUCE_NAME=
SCALEKIT_RESOUCE_DOCS_URL=

ALPHA_VANTAGE_API_KEY

Alpha Vantage’s API Key is used to retrieve stock sentiment information.

METADATA_JSON_RESPONSE

Scalekit’s JSON response when configuring your MCP server.

This document contains information such as authorization servers, scopes supported, and URLs for documentation.

SCALEKIT_ENVIRONMENT_URL

Under the section Settings, you can find the URL for your environment.

SCALEKIT_CLIENT_ID

Client ID is the client number that appears in Settings.

SCALEKIT_CLIENT_SECRET

The secret key you generate under Settings → API Credentials.

SCALEKIT_RESOURCE_METADATA_URL

This is the URL that your MCP Server exposes for requests of metadata.

Example:

http://localhost:10000/.well-known/oauth-protected-resource/mcp

SCALEKIT_AUTHORIZATION_SERVERS

Scalekit will provide the URL pointing at its MCP Server Identifier.

Example:

https://.scalekit.dev/resources/res_***************

Subdomains can be found in the JSON resource metadata

SCALEKIT_AUDIENCE_NAME

Use the Audience (aud claim) in your access tokens for validating requests. See the FULL CODES here.

http://localhost:10000/mcp/

SCALEKIT_RESOUCE_NAME

It is also called the MCP resource name. This is usually the same name as SCALEKIT_AUDIENCE_NAME. Click here to find out more FULL CODES here.

SCALEKIT_RESOUCE_DOCS_URL

You can find the documentation for your MCP server at this URL.

Example:

http://localhost:10000/mcp/docs

Create a file to store all environment variables that you will use later. You can check out the FULL CODES here.

Import os
Dotenv Import Load_dotenv

load_dotenv()

Class Settings():
    ALPHA_VANTAGE_API_KEY = os.environ.get('ALPHA_VANTAGE_API_KEY')
    METADATA_JSON_RESPONSE = os.environ.get('METADATA_JSON_RESPONSE')
    SCALEKIT_ENVIRONMENT_URL = os.environ.get('SCALEKIT_ENVIRONMENT_URL')
    SCALEKIT_CLIENT_ID = os.environ.get('SCALEKIT_CLIENT_ID')
    SCALEKIT_CLIENT_SECRET = os.environ.get('SCALEKIT_CLIENT_SECRET')
    SCALEKIT_RESOURCE_METADATA_URL = os.environ.get('SCALEKIT_RESOURCE_METADATA_URL')
    SCALEKIT_AUTHORIZATION_SERVERS = os.environ.get('SCALEKIT_AUTHORIZATION_SERVERS')
    SCALEKIT_AUDIENCE_NAME = os.environ.get('SCALEKIT_AUDIENCE_NAME')
    SCALEKIT_RESOUCE_NAME = os.environ.get('SCALEKIT_RESOUCE_NAME')
    SCALEKIT_RESOUCE_DOCS_URL = os.environ.get('SCALEKIT_RESOUCE_DOCS_URL')
 Port = 10000
    

Setting = Setting()

This code block retrieves news sentiment in real time for a specific stock ticker by using Alpha Vantage API. This code block retrieves three of the most recent articles and summarizes their summary, title, source, publication date, for quick insight. Look at the FULL CODES here.

FastMCP import from mcp.server.fastmcp
You can import any text by typing in Any
Import os
Import httpx
From typing, import List
Import settings from the config

# Create an MCP service
FastMCP = mcp"finance-news")

BASE_URL = "https://www.alphavantage.co/query"

async def call_alpha_vantage(endpoint: str, params: dict[str, Any]) -> dict[str, Any] | None:
    """Generic async caller to Alpha Vantage."""
 амм["apikey"] = settings.ALPHA_VANTAGE_API_KEY
 Please params["function"] = endpoint
 Async client with HTTPx() As a client
        try:
            response = await client.get(BASE_URL, params=params, timeout=30.0)
            response.raise_for_status()
 Return response.json()
 The exception:
 Return None

@mcp.tool()
async def get_news_sentiment(ticker: str) -> str:
    ""Get news sentiment data on a ticker.

    Args:
 Stock ticker symbols (e.g. AAPL, MSFT)
    """
    data = await call_alpha_vantage("NEWS_SENTIMENT", {"tickers": ticker.upper()})
 If not data "feed" Not in Data:
 Return to the Homepage "Couldn't retrieve news sentiment."

    articles = data["feed"][:3]
 Result = []
 For item in article:
        result.append(f"""
    📰 {item['title']}
    Summary: {item['summary']}
    Source: {item['source']} | Published: {item['time_published']}
    """)
 Return to the Homepage "n---n".join(result)

The middleware is an authorization layer that ensures only authenticated requests will be processed by your MCP servers. It utilizes the ScaleKit clients To validate the access tokens of every incoming response. The middleware checks the public status of the requested path, for example, metadata endpoints. /.well-known/. 

The request will be rejected if the header Authorization does not contain a Bearer token. ScaleKit validates the token. Middleware responds immediately if the token is not present, it’s invalid or has expired. 401 Unauthorized error A structured error message. You can check out the FULL CODES here.

If the token passes the test, it is sent to the following layer. A logging system is used to record key events and make it easier to track, debug, and audit the authentication flow.

This middleware is then added to all the secure endpoints. Visit the FULL CODES here.

Import json
import logging
Fastapi HTTPException import request
Import HTTPBearer from fastapi.security
From fastapi.responses, import JSONResponse
ScalekitClient can be imported from Scalekit
from starlette.middleware.base import BaseHTTPMiddleware

Import settings from the config

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Security scheme for Bearer token
HTTPBearer = security()

ScaleKit Initialize client
scalekit_client = ScalekitClient(
    settings.SCALEKIT_ENVIRONMENT_URL,
    settings.SCALEKIT_CLIENT_ID,
    settings.SCALEKIT_CLIENT_SECRET
)

# Authentication middleware
class AuthMiddleware(BaseHTTPMiddleware):
 Async Def Dispatcher(self: request, Call_Next)
        if request.url.path.startswith("/.well-known/"):
            return await call_next(request)

        try:
            auth_header = request.headers.get("Authorization")
            if not auth_header or not auth_header.startswith("Bearer "):
                raise HTTPException(status_code=401, detail="Missing or invalid authorization header")

            token = auth_header.split(" ")[1]

            request_body = await request.body()
            
 # Parse JSON using bytes
            try:
                request_data = json.loads(request_body.decode('utf-8'))
            except (json.JSONDecodeError, UnicodeDecodeError):
                request_data = {}
            
            try:
                scalekit_client.validate_access_token(token)
                
 Except Exception As e.
                raise HTTPException(status_code=401, detail="Token validation failed")

 Except HTTPException e.
 Return JSONResponse (
                status_code=e.status_code,
                content={"error": "unauthorized" If e.status_code is 401 then "forbidden", "error_description": e.detail},
                headers={
                    "WWW-Authenticate": f'Bearer realm="OAuth", resource_metadata="{settings.SCALEKIT_RESOURCE_METADATA_URL}"'
                }
            )

        return await call_next(request)

This script integrates an MCP Server with a FastAPI Application for Stock News Sentiment Analysis. This script starts by importing libraries such as FastAPI and middleware CORS, along with custom authentication middleware. See the FULL CODES here.

An asynchronous contextmanager is used to control the lifecycle of an application using a context that includes both lifecycle and context. finance_news_server.session_manager is what we call the stock sentiment logic. It runs perfectly during app runtime. CORS is set up to accept cross-origin calls, which can be useful in development environments but shouldn’t be allowed for production.

A new endpoint, /.well-known/oauth-protected-resource/mcpThe.metadata endpoint is now available for the OAuth 2.1 resource discovery. This endpoint provides important details such as supported authorization servers, bearer token methods, resource name, documentation URL, and supported scopes — in this case, mcp:tools:news:read.

The MCP server is created using the finance_news_server.streamable_http_app() The MCP functionality is accessible via the app’s main menu. The authentication is enforced through the integration of the AuthMiddlewareThis script adds the middleware to the file of the server. 

Last but not least, there is also the primary() The function will run the application on uvicorn with debug logging and binding to the localhost port. See the FULL CODES here.

Im contextl
import uvicorn
FastAPI can be imported from FastAPI
from fastapi.middleware.cors import CORSMiddleware
Import json
AuthMiddleware imports auth
Import settings from the config
Import mcp to finance_news_server

# Create a combined life span to manage MCP session managers
@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
    async with finance_news_server.session_manager.run():
 

app = FastAPI(lifespan=lifespan)

# Add CORS Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"]If you are in production, please specify where your origins actually come from.
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

MCP is a well-known Endpoint
@app.get("/.well-known/oauth-protected-resource/mcp")
async def oauth_protected_resource_metadata():
    """
 Endpoint OAuth 2.0 protected resource metadata for client discovery in MCP
 MCP specifies that authorization servers must be discovered.Return
    """

    return {
        "authorization_servers": [settings.SCALEKIT_AUTHORIZATION_SERVERS],
        "bearer_methods_supported": ["header"],
        "resource": settings.SCALEKIT_RESOURCE_NAME,
        "resource_documentation": settings.SCALEKIT_RESOURCE_DOCS_URL,
        "scopes_supported": [
          "mcp:tools:news:read"
        ],
    }

# Mount the MCP Server with authentication
mcp_server = finance_news_server.streamable_http_app()
app.add_middleware(AuthMiddleware)
app.mount("/", mcp_server)

Def main():
    """Main entry point for the MCP server."""
    uvicorn.run(app, host="localhost", port=settings.PORT, log_level="debug")

If __name__ is equal to "__main__":
 The main reason for this is that()

Start the server by running pythonserver.py. This will launch the application at localhost:10000. Test the configuration by opening another terminal. Run:

npx @modelcontextprotocol/inspector

When the MCP inspector is running enter http://localhost:10000/mcp As the server URL. You will receive the following error if you try to connect with invalid credentials:

The connection is not working. Check that your MCP Server and the proxy The token has been configured correctly.

Once you have entered the Secret ID generated by Scalekit, please provide the Bearer token. After entering the secret ID, your authentication will be successful and you’ll be able to start using tool calls.


Click here to find out more FULL CODES here. Please feel free to browse our GitHub Page for Tutorials, Codes and Notebooks. Also, feel free to follow us on Twitter Don’t forget about our 100k+ ML SubReddit Subscribe Now our Newsletter.


I graduated in Civil Engineering (2022), from Jamia Millia Islamia (New Delhi). I am interested in Data Science in particular, Neural Networks, and their applications in many areas.

coding
Share. Facebook Twitter LinkedIn Email
Avatar
Gavin Wallace

Related Posts

OpenAI Ships GPT-Stay-1.1 for Voice Brokers, Cuts Idle Value to $0.02/Min

21/11/2026

Meet Pondering Machines Inkling 2 Mini: 26B Looped MoE Runs on a 32GB Mac

21/11/2026

Baseten Releases Bison-1 and Groundhog-1, Topping Choice Mannequin Index

21/11/2026

RadixArk Ships DaisyRose-27B, a 27B Agentic Coding Mannequin Skilled With Reinforcement Studying Solely

20/11/2026
Top News

How intelligent were Neanderthals? AI Blog

Anthropic claims that Claude has its own set of emotions

Google DeepMind Staffers Ask Leaders to Keep Them ‘Physically Safe’ From ICE

Advertisements in Chatbots Have Arrived. Right here’s What’s Working—and What’s Not

The Georgia cop used Flock to track 2 other officers: his ex-girlfriend and her friend

Load More
AI-Trends.Today

Your daily source of AI news and trends. Stay up to date with everything AI and automation!

X (Twitter) Instagram
Top Insights

AutoAgent is an open-source AI library which allows you to optimize and engineer your own Agent.

05/04/2026

Incomes Overseas, Spending at Residence: Making AI Finance Instruments Work for You – Unite.AI

13/10/2026
Latest News

Dragos Finds Immediate Leaks and Stolen Keys in AI Provide Chains

22/11/2026

Lean and Mathlib Communities Certify Claude-Assisted Riemann Proof – Unite.AI

21/11/2026
X (Twitter) Instagram
  • Privacy Policy
  • Contact Us
  • Terms and Conditions
© 2026 AI-Trends.Today

Type above and press Enter to search. Press Esc to cancel.