Generative AI

Getting Starting Oaty 2.1 of the MCP server with scaluut: Lesson to enter the step codes

In this lesson, we will investigate how we can use Oauth 2.1 of MCP Servers Step by step. To keep things working, we will build an analyzing a simple financial feelings and protects us to use a scalelit, a tool that makes the oauth quick and easy.

With Sclakit, all we need to do to display the Metadata Endpoint URL customer URL for MCP Customer to find the server and add Middlerware authorization to ensure the Token authentication. The SCALUVET treats all the complex OATH A 2.1 flows after scenes, so you do not need to manage or manage your generation, update, or verification. When this setup has been completed, your MCP server is ready to manage certified applications. Look Full codes here.

Alpha Vantage API

To download stock-outs, we will use ApaCante Acanta. To get the free API free key:

  • Visit the Alpha Vantage platform using this link
  • Enter your email and information required.
  • You will receive your API key and save it safely, as you will need to be confirmed by your applications.

Node Js

Run MCP inspector By checking our app, we need node.js installed.

  • Download the latest version of node.js from Node Node Node .org
  • Run the Installer.
  • Save default settings and complete the installation.

Python is dependent

pip install fastapi fastmcp mcp scalekit-sdk-python

Scalit

To start using ScalitFollow these steps:

Create your Scalelit account

  • Go to the calling.com and register.
  • Scalit gives free tier, so you don't need to worry about billing.
  • If logged in, click “Activate Full-Stack Author. “

Set Permissions

  • Open Authorization Panel.
  • Under the Permission section, click “Permit.”
  • Use the following values:

Permission Name: News: Learn

Description: Use Alpha Ventantage to find the stock feelings

Scalelit permits are used to describe and manage the features that regulate which features or resources for your application may access. For example, News: Learn The permission allows your MCP server to access stock sensitutions from Alpha Vantage, while other permits may be created for additional features or APIs within your application.

Enter your MCP server

  • Go to MCP Server paper and click “Add MCP Server.”
  • Fill in the required fields:

The server name: Any word you like.

Service Compert: The unique MCP server identifier. This value is included in the AUD claim to find tokens, assisting server applications to confirm.

With local examination, set as:

If you are using FastMCP, the method / MCP is automatically added to the endpoint. Verify to enter the trailing slash at the end to prevent configuration issues. Look Full codes here.

Set the limit to the permanent permit: News: Learn

When the server created, the scaleleit will produce your metadata. Make sure you do not recognize the MCP server (located next to the server name, e.g. Res_88056357768398086), as you will need later.

An example of Metadata of service

Your Metadata will look like this (but different with your account):

Metadata Endpoint Url:

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

Metadata Json apps:

{
  "authorization_servers": [
    "
  ],
  "bearer_methods_supported": ["header"],
  "resource": "",
  "resource_documentation": "docs",
  "scopes_supported": ["news:read"]
}

Find API guarantees

  • Go to Settings → API credentials.
  • Copy your client ID and environmental URL.
  • Click the New secret secret to create your secret key.

Keep these treasures safely – we will need them later for repair.

.een

We will now create a .env file with the following variations

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

Your API API key from Alpha Vantage, which is used to download stock view data.

Metadata_json_response

JSON's response is issued by scalelit when preparing your MCP server.

It contains detail such as authorization servers, supported shoes, and writing URLs.

Slakit_enviromerment_url

Environmental URL under the Settings section.

Scalit_Client_id

Client ID specified under part of the setting.

Scalit_Client_seecret

The secret key that you have taken from the Mets → API credentials.

Scalit_Resource_Metadata_url

URL exposed to your MCP server for Metadata applications.

For example:

Scalit_aithorization_sservers

The URL identifies the MCP server displays issued by Scalit.

For example:

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

You can get a domain from Metadata Json

Scalit_audence_name

Audistrative claim (AUD) is used to access tokens to confirm applications. Look Full codes here.

Scalit_resoup_name

Name of your MCP server services. In most cases, this is the same Scalit_audence_name. Look Full codes here.

Scalit_remouce_docs_url

URL where your MCP server texts are stored.

For example:

docs

We will start creating a prepared file to load everything in the natural variable. Look Full codes here.

import os
from 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
    

settings = Settings()

This code block is a real-time news story data using ALPHA VANTAC API. Returns the latest three articles, summarizing their title, a summary, the source and time of publication of immediate understanding. Look Full codes here.

from mcp.server.fastmcp import FastMCP
from typing import Any
import os
import httpx
from typing import Dict, List
from config import settings

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

BASE_URL = "

async def call_alpha_vantage(endpoint: str, params: dict[str, Any]) -> dict[str, Any] | None:
    """Generic async caller to Alpha Vantage."""
    params["apikey"] = settings.ALPHA_VANTAGE_API_KEY
    params["function"] = endpoint
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(BASE_URL, params=params, timeout=30.0)
            response.raise_for_status()
            return response.json()
        except Exception:
            return None

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

    Args:
        ticker: Stock ticker symbol (e.g., MSFT, AAPL)
    """
    data = await call_alpha_vantage("NEWS_SENTIMENT", {"tickers": ticker.upper()})
    if not data or "feed" not in data:
        return "Couldn't retrieve news sentiment."

    articles = data["feed"][:3]
    result = []
    for item in articles:
        result.append(f"""
    📰 {item['title']}
    Summary: {item['summary']}
    Source: {item['source']} | Published: {item['time_published']}
    """)
    return "n---n".join(result)

This information is active as a layer of your MCP server's authorization, to ensure that only certified applications are processed. Uses Scalit client In order to ensure access to tokens in all incoming applications. When an application is entered, the first Middlerawware checks if the method in front of public, such as metadata endpoints under the /.Well-.

If the application is not a public form, it looks at the Head of Authorization of a valid valid token. The token is confirmed using a scalelit. If the token is lost, it does not work, or expire, the Middlerdler responds immediately with 401 Unauthorized Error and a formal error message. Look Full codes here.

If the token is valid, the application is transferred to the following section of the application. In addition, logging integrated into the entire process of hosting important events, making it easier to pollution and the authentication of approval.

Finally, these communities will be imported and added to the server file to protect all secure conclusions. Look Full codes here.

import json
import logging
from fastapi import HTTPException, Request
from fastapi.security import HTTPBearer
from fastapi.responses import JSONResponse
from scalekit import ScalekitClient
from starlette.middleware.base import BaseHTTPMiddleware

from config import settings

# 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
security = HTTPBearer()

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

# Authentication middleware
class AuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: 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 from 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 as e:
            return JSONResponse(
                status_code=e.status_code,
                content={"error": "unauthorized" if e.status_code == 401 else "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 sets the Fastapi app compiled with the MCP server for the analysis of stock. The first time introduces the required libraries, including the Fastapi, the Middler, Cortdleware, and customization Middleware. Look Full codes here.

The LifecyCcle application is held in the context of the Asynchronous manager, to ensure that Financial_NewSverver.SSSession_manager, which is actually the basic of the feelings of the stock that created, works well during the application function. The CortTro MiddlerWare is prepared to allow the origin of the origin, which are useful during development but must be limited to production locations.

A new ending, /.Yegnellen/aauth-prot.Resource/MCPIt has been added to the performance of the OAUTHA Metadata 2.1 protected to regenerate resources. This conclusion provides important information as a server supported, Preser Token server, Name of URL, URL URL, and supported symptoms – in this case, reading.

The MCP server is made using Financial_strowder.Sreamable_http_app () Path work and installed on the root method /, performs the basic MCP function available through the main app. Verification is forced by integration AuthormiddareAnd the text confirms that this medium is well included in the server file.

Finally, the main function () is conducting the app using Uvicorn, by composing the Debug Effective level, arresting a server in the localhost in a prepared port. Look Full codes here.

import contextlib
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import json
from auth import AuthMiddleware
from config import settings
from finance import mcp as finance_news_server

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

app = FastAPI(lifespan=lifespan)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify your actual origins
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# MCP well-known endpoint
@app.get("/.well-known/oauth-protected-resource/mcp")
async def oauth_protected_resource_metadata():
    """
    OAuth 2.0 Protected Resource Metadata endpoint for MCP client discovery.
    Required by the MCP specification for authorization server discovery.
    """

    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"
        ],
    }

# Create and 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__ == "__main__":
    main()

To start server, issue the Psythi.thon.py server, which will start the app on the localhost: 10000. Checking to set, open the other end and run:

npx @modelcontextprotocol/inspector

When the MCP inspector runs, entering as a server URL. If you try to connect without providing valid authentication, you will meet the following error:

Connectular error: Check that your MCP server is valid and if the representative token is well prepared.

Now, provide the carrying token using a secret ID you have produced in scalelit. Once you have entered, you will be confirmed successfully and you can start doing tools tools.


Look Full codes here. Feel free to look our GITHUB page for tutorials, codes and letters of writing. Also, feel free to follow it Sane and don't forget to join ours 100K + ml subreddit Then sign up for Our newspaper.


I am the student of the community engineering (2022) from Jamia Millia Islamia, New Delhi, and I am very interested in data science, especially neural networks and their application at various locations.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button