Machine Learning

Introducing Model Contextor Protocol Servers

Keep in writing the context of the Model (MCP) in December 2024, just before it grows on Exponential Gogninant in what is present today. I remember at that time I think that one of the important things I felt should happen to MCP to make technology for Game Changes that MCP's incoming MCP clients. What happened already, of course, but what if you want a piece of this act? How do you walk in the remote MCP server, art tools helpful to it, check it outThen use it in the cloud, for example, so that anyone can access any advertising tools at any client supported anywhere in the world?

I will show you how you can do all these things in this article.

Fast Return from that MCP server

There are many meanings for MCP server descriptions. In my view, which is likely to be a little Avertificate, the MCP server enables MCP customers, such as Cursor and Cloud Code, to drive useful tasks that the MCP server contains.
How does that differ from you writing a bundle of important tools and call them in your code?

Well, the key is that u To write those tools. What about the world's existing tools another person Did you write? I'm sure you've heard a talk “… There is an app for that”. In the future not too far, we can “… there is a MCP server for that“Okay, not like snappy but just like sensitive basics.

So far, most of the many MCP servers are written in the form of the Stdio Transport in mind. This means that the ONUS is on you Handling the server in your home system. That sometimes can be fraudulent and tend to error. In addition, only you can reach that server. And that's where HTTP servers live there) or MCP servers enter their own. Hosted, you need to know only the server URL and the words tools that offer you, and you are risen and runs with it in seconds.

So, if you write something for some to find really helpful, why not do a remote MCP server, treating others and can allow others to use?

OK, let's do this.

My setup

I will be developing the MCP server code and its tools using the Windows Visual Studio code. I will be using git bash with my command line as it comes with some services that will use, as grind including stop. You will also need to install Node.js once Uv Python Package Utility. If you want to install the completed MCP server in the cloud, you will need to save your code in GitTub, so you will need the account for that.

The first thing you have to do first is a new project of your code, etc. Use Uv The Tool with the first flag this. Next, we include nature, switch to it and add all the external libraries that our code will use.

$ uv init remote-mcp
Initialized project `remote-mcp` at `/home/tom/projects/remote-mcp`
$ cd remote-mcp
$ ls -al
total 28
drwxr-xr-x 3 tom tom 4096 Jun 23 17:42 .
drwxr-xr-x 14 tom tom 4096 Jun 23 17:42 ..
drwxr-xr-x 7 tom tom 4096 Jun 23 17:42 .git
-rw-r--r-- 1 tom tom 109 Jun 23 17:42 .gitignore
-rw-r--r-- 1 tom tom 5 Jun 23 17:42 .python-version
-rw-r--r-- 1 tom tom 0 Jun 23 17:42 README.md
-rw-r--r-- 1 tom tom 88 Jun 23 17:42 main.py
-rw-r--r-- 1 tom tom 156 Jun 23 17:42 pyproject.toml

$ uv venv && source .venv/bin/activate
# Now, install the libraries we will use.
(remote-mcp) $ uv add fastapi 'uvicorn[standard]' mcp-server requests yfinance python-dotenv

What to Improve

We will develop a MCP server and two different tools for our MCP server for use. The first will be the Nobel Prize Checker. Provides for a year, e.g, 1935, as well as the topic, e.g., Physics, and the MCP server will return the details of who win the prize that day. The second tool will return the high temperature of the city last week

First, we will install our two tools and test it in place. Next, we will install the tools to the MCP server working in your area and checks to set up. If it works as expected, we can submit your MCP server and its tools to a remote cloud server and ensure that it continues to function properly.

Example of Code 1- Finding Bel Prize information

The NO NOP PRINE services website have licenses under the Creative Commons License. You can see information using the link below:

Here is the basic work we will use. Open your code editor and save this content to the file called Pire_Tool.py.

import requests
import os
import io
import csv

# from mcp.server.fastmcp import FastMCP
try:
    from mcp.server.fastmcp import FastMCP
except ModuleNotFoundError:
    # Try importing from a local path if running locally
    import sys
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    from fastmcp import FastMCP

mcp = FastMCP(name="nobelChecker",stateless_http=True)

@mcp.tool()
def nobel_checker(year, subject):
    """
    Finds the Nobel Prize winner(s) for a given year and subject using the Nobel Prize API.

    Args:
        year (int): The year of the prize.
        subject (str): The category of the prize (e.g., 'physics', 'chemistry', 'peace').

    Returns:
        list: A list of strings, where each string is the full name of a winner.
              Returns an empty list if no prize was awarded or if an error occurred.
    """
    BASE_URL = "
    
    # Prepare the parameters for the request, converting subject to lowercase
    # to match the API's expectation.
    params = {
        'year': year,
        'category': subject.lower()
    }
    
    try:
        # Make the request using the safe 'params' argument
        response = requests.get(BASE_URL, params=params)
        
        # This will raise an exception for bad status codes (like 404 or 500)
        response.raise_for_status()

        # If the API returns no data (e.g., no prize that year), the text will
        # often just be the header row. We check if there's more than one line.
        if len(response.text.splitlines()) <= 1:
            return [] # No winners found

        # Use io.StringIO to treat the response text (a string) like a file
        csv_file = io.StringIO(response.text)
        
        # Use DictReader to easily access columns by name
        reader = csv.DictReader(csv_file)
        
        winners = []
        for row in reader:
            full_name = f"{row['firstname']} {row['surname']}"
            winners.append(full_name)
            
        return winners

    except requests.exceptions.RequestException as e:
        print(f"An error occurred during the API request: {e}")
        return [] # Return an empty list on network or HTTP errors

if __name__ == "__main__":
   data =  nobel_checker(1921,"Physics")
   print(data)

This document describes MCP for a small (model model model) that can be conducted in your area or the Fastmcp server. After trying to import FastMCP from the mcp.server Package, and then back to your sibling fastmcp Module if that's the import fails. Then created MCP example called And the Belchecker With the steerbed_http = a true flag, meaning Fastmcp will automatically disclose the HTTP visual conclusion. Decorated work Bel_checker becomes a mcp instrument. When fireEd, creating a query on the rest of API using a given year and story, and returns the name (s) of the prize of that year and the title (or auxiliary message if not).

If we use the above code in the area, we find outgoing such as the following, indicating that the work is effective and performing its intended work.

['Albert Einstein']

Example of Code 2- Finding City Hircles

With our second job, we will write a tool that restore the highest temperature in the city last week. Climate data is provided with Spen-meteo.com. To their license page (“says,

“API data is provided under countries unknown (CC is 4.0)

You Are Free Share: Copy and re-settle material from any medium or format and Convert: Remix, change, and build that. “

I have given the right audit and link to their license, filling their licenses of their license.

Create a Python file temp_tool.py Then add this code.

# temp_tool.py

from mcp.server.fastmcp import FastMCP

mcp = FastMCP(name="stockChecker", stateless_http=True)

import requests
from datetime import datetime, timedelta

# This helper function can be reused. It's not tied to a specific API provider.
def get_coords_for_city(city_name):
    """
    Converts a city name to latitude and longitude using a free, open geocoding service.
    """
    # Using Open-Meteo's geocoding, which is also free and requires no key.
    GEO_URL = "
    params = {'name': city_name, 'count': 1, 'language': 'en', 'format': 'json'}
    
    try:
        response = requests.get(GEO_URL, params=params)
        response.raise_for_status()
        data = response.json()
        
        if not data.get('results'):
            print(f"Error: City '{city_name}' not found.")
            return None, None
            
        # Extract the very first result
        location = data['results'][0]
        return location['latitude'], location['longitude']
        
    except requests.exceptions.RequestException as e:
        print(f"API request error during geocoding: {e}")
        return None, None

@mcp.tool()
def get_historical_weekly_high(city_name):
    """
    Gets the highest temperature for a city over the previous 7 days using the
    commercially-friendly Open-Meteo API.

    Args:
        city_name (str): The name of the city (e.g., "New York", "London").

    Returns:
        float: The highest temperature in Fahrenheit from the period, or None if an error occurs.
    """
    # 1. Get the coordinates for the city
    lat, lon = get_coords_for_city(city_name)
    if lat is None or lon is None:
        return None # Exit if city wasn't found
        
    # 2. Calculate the date range for the last week
    end_date = datetime.now() - timedelta(days=1)
    start_date = datetime.now() - timedelta(days=7)
    start_date_str = start_date.strftime('%Y-%m-%d')
    end_date_str = end_date.strftime('%Y-%m-%d')

    # 3. Prepare the API request for the Historical API
    HISTORICAL_URL = "
    params = {
        'latitude': lat,
        'longitude': lon,
        'start_date': start_date_str,
        'end_date': end_date_str,
        'daily': 'temperature_2m_max', # The specific variable for daily max temp
        'temperature_unit': 'fahrenheit' # This API handles units correctly
    }
    
    try:
        print(f"Fetching historical weekly max temp for {city_name.title()}...")
        response = requests.get(HISTORICAL_URL, params=params)
        response.raise_for_status()
        data = response.json()
        
        daily_data = data.get('daily', {})
        max_temps = daily_data.get('temperature_2m_max', [])
        
        if not max_temps:
            print("Could not find historical temperature data in the response.")
            return None
            
        # 4. Find the single highest temperature from the list of daily highs
        highest_temp = max(max_temps)
        
        return round(highest_temp, 1)

    except requests.exceptions.RequestException as e:
        print(f"API request error during historical fetch: {e}")
        return None

if __name__ == "__main__":
   data =  get_historical_weekly_high("New York")
   print(data)

This work takes the city name and returns the highest temperature in the city last week.

Here is a common result when you run in the area.

Fetching historical weekly max temp for New York...
104.3

To create our MCP server

Now that we show our activities work, let us add them to the MCP server and get that running. Here is the server code you will need.

# mcp_server.py

import contextlib
from fastapi import FastAPI
from temp_tool import mcp as temp_mcp
from prize_tool import mcp as prize_mcp
import os
from dotenv import load_dotenv

load_dotenv()

# Create a combined lifespan to manage both session managers
@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
    async with contextlib.AsyncExitStack() as stack:
        await stack.enter_async_context(temp_mcp.session_manager.run())
        await stack.enter_async_context(prize_mcp.session_manager.run())
        yield


app = FastAPI(lifespan=lifespan)
app.mount("/temp", temp_mcp.streamable_http_app())
app.mount("/prize", prize_mcp.streamable_http_app())

PORT = int(os.getenv("PORT", "10000"))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=PORT)

The only changes in our first pire_tool and Temp_tool deletes three lines at each of them, used for testing. Remove these from both.

if __name__ == "__main__":
    data = nobel_checker(1921,"Physics")
    print(data)

and ...

if __name__ == "__main__":
    data = get_historical_weekly_high("New York")
    print(data)

Running a MCP server in your area

Using our server, type the following command on the end-line-terminal.

$ uvicorn mcp_server:app --reload --port 10000
$ # You can also use python mcp_server.py --reload --port 10000
$ #
INFO: Will watch for changes in these directories: ['C:Usersthomaprojectsremote-mcpremote-mcp']
INFO: Uvicorn running on  (Press CTRL+C to quit)
INFO: Started reloader process [3308] using WatchFiles
INFO: Started server process [38428]
INFO: Waiting for application startup.
[06/25/25 08:36:22] INFO StreamableHTTP session manager started streamable_http_manager.py:109
INFO StreamableHTTP session manager started streamable_http_manager.py:109
INFO: Application startup complete.

Checking our MCP server in your area

We can use Gitbash Command Terminal and Curl for this. Make sure your server is up and running first. Let's try our tool to check the temperature first. Release can always be processed after issuing the content you want in easily useful format.

$ curl -sN -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_historical_weekly_high","arguments":{"city_name":"New York"}}}'  | sed -n '/^data:/{s/^data: //;p}'


{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"104.3"}],"isError":false}}

This shows Max Temp in NY last week there was 104.3 Fahrenheit.

And now we can test the prize test tool.

$ curl -sN -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nobel_checker","arguments":{"year":1921,"category":"Physics"}}}'  | sed -n '/^data:/{s/^data: //;p}' 

{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"Albert Einstein"}],"isError":false}}

Albert Einstein won a Physics prize in 1921.

To move our MCP server remotely

Now that we are satisfied with our code and that the MCP server works as expected in your area, the next section to send away, allow anyone in the world to use. There are a few ways to do this, but maybe easy (and at the beginning cheap) to use the resource like Give.

The Render is a modern grammatical platform – as an easier way to AWs, heroku, or vercel – allowing you to submit full-time apps, APIs, details, low-desks. Much to the point is that it is free to get started and more than enough of our needs. So move on to their website and sign up for.

Before donating, you must do and send your code to GitTub (or gitlab / bitbucket). Then, over the website that provides, select Creating a new Web server,

Picture from the website

The first time, the donation will request access to your Gitity account (or BitBucket / Gitlab).

Picture from the website

After that, you need to provide the instructions to create your submission and start your server. For example ….

Picture from the website

Back to Settings Screen, click Manual Deploy -> Move the recent commitment The menu item, and the Log and the Shipping process will be displayed. After a few minutes, you should see the following messages showing your submission successful.

...
...
==> Build successful 🎉
==> Deploying...
==> Running 'uv run mcp_server.py'
...
...
...
==> Available at your primary URL  Available at your primary URL 
...
Detected service running on port 10000
...
...

The essential address you need is marked as the main URL. To us, this

Checking our remote MCP server

We can do this in the same way that test the local run, which means using curl. First, check the Lamax temperature, in this Chicago. Note the URL conversion to our new remote.

$ curl --ssl-no-revoke -sN -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_historical_weekly_high","arguments":{"city_name":"Chicago"}}}' /temp/mcp/|sed -n '/^data:/{s/^data: //;p}'

And our results?

{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"95.4"}],"isError":false}}

A sharp Exj between you may have seen us wear an additional flag (- SSL-No-Revoke) In the upper curl cirl if compared with what we use in the area. This is due to the quirk way the curl works under the windows. If you use WSL2 with Windows or Linux, you don't need this flad flag.

Next, we test our last Nobel prize. This chemical period in 2024.

$  $ curl --ssl-no-revoke -sN 
-H 'Content-Type: application/json' 
-H 'Accept: application/json, text/event-stream' 
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nobel_checker","arguments":{"year":2024,"subject":"Chemistry"}}}' 
'/prize/mcp/' | sed -n '/^data:/{s/^data: //;p}'

And the result?

{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"David Baker"},{"type":"text","text":"Demis Hassabis"},{"type":"text","text":"John Jumper"}],"isError":false}}

If you want to try access to the MCP server with the code instead of using curl, here is a Python example showing a remote name Bel_checker tool.

import requests
import json
import ssl
from urllib3.exceptions import InsecureRequestWarning
from urllib3 import disable_warnings

# Disable SSL warnings (equivalent to --ssl-no-revoke)
disable_warnings(InsecureRequestWarning)

def call_mcp_server(url, method, tool_name, arguments, request_id=1):
    """
    Call a remote MCP server
    
    Args:
        url (str): The MCP server endpoint URL
        method (str): The JSON-RPC method (e.g., "tools/call")
        tool_name (str): Name of the tool to call
        arguments (dict): Arguments to pass to the tool
        request_id (int): JSON-RPC request ID
    
    Returns:
        dict: Response from the MCP server
    """
    
    # Prepare headers
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream"
    }
    
    # Prepare JSON-RPC payload
    payload = {
        "jsonrpc": "2.0",
        "id": request_id,
        "method": method,
        "params": {
            "name": tool_name,
            "arguments": arguments
        }
    }
    
    try:
        # Make the request with SSL verification disabled
        response = requests.post(
            url,
            headers=headers,
            json=payload,
            verify=False,  # Equivalent to --ssl-no-revoke
            stream=True   # Support for streaming responses
        )
        
        # Check if the request was successful
        response.raise_for_status()
        
        # Try to parse as JSON first
        try:
            return response.json()
        except json.JSONDecodeError:
            # If not JSON, return the text content
            return {"text": response.text}
            
    except requests.exceptions.RequestException as e:
        return {"error": f"Request failed: {str(e)}"}

# Example usage
if __name__ == "__main__":
    
    result = call_mcp_server(
        url="/prize/mcp/",
        method="tools/call",
        tool_name="prize_checker",
        arguments={"year": 2024, "subject": "Chemistry"}
    )
    print("MCP Tool Call Response:")
    print(json.dumps(result, indent=2))

The result is.

MCP Tool Call Response:
{
  "text": "event: messagerndata: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"David Baker"},{"type":"text","text":"Demis Hassabis"},{"type":"text","text":"John Jumper"}],"isError":false}}rnrn"
}

Summary

This scripture introduces how to do it Write, test, and place Your remote server, HTTP Modeme Protocol (MCP) server in the cloud, enables any MCP client to access tasks (tools) remotely.

I showed you how to show other useful activities alone – Nobel award and city temperature tool. After checking these locations using the grind Refused to ensure that they worked as expected, converted them into MCP tools and installed MCP Server. After sending and testing the MCP server in your area, we viewed how to send our server to the cloud.

For that purpose, I show how I can use it to offer, the platform for clouds, and I visit you with registration and sending steps to our MCP app. We then use curl to test a remote server, which ensures that it was working as expected.

Finally, give me some Python code to use to check the MCP server.

Feel free to test my MCP server to make your own. Note that because of the free tier, the server puts down the back of the unemployment, which may have 30-60 delays in return results.

Source link

Related Articles

Leave a Reply

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

Back to top button