Podcast Title

Author Name

0:00
0:00
Album Art

Build Your Own AI Agent: A Guide to Creating MCP Servers in Python

By 10xdev team August 16, 2025

Welcome to this article where we're going to learn how to build an MCP server in Python and then connect it to an AI agent like Claude Desktop. If you haven't heard of the term MCP before, it stands for Model Context Protocol, and it describes itself as a "USB-C for AI applications." Instead of building one-off integrations for everything, MCP provides a standard way for AI models to connect to any tool or data source where you'd normally use a REST API. This is very important for building autonomous AI agents, because any tool or data source that you want your agent to have will probably need to have an MCP server.

Let's look at a quick demo of the project we'll be building. We will connect two custom MCP tools to our application. First, there's a tool that can fetch the current weather for a city, and another tool that can create and modify spreadsheets in a Google Drive folder. The first tool is implemented ourselves in Python and will live locally on our machine. The second tool is a third-party implementation that we're just going to set up.

With both of these tools set up, we can give our agent instructions, like "get the current weather for all cities in Australia, and put them into a Google Sheet for me." The agent will then process this request and use the configured MCP servers with the right parameters to get the information it needs. It doesn't just retrieve information; it can also perform actions like creating and updating spreadsheets in a Google Drive folder. The result is a Google Sheet created entirely by the AI agent, leveraging both of the MCP servers we provided.

In this article, we'll walk you through how to build your own MCP server from scratch using the official SDK for Python. For this project, it will just call an API to fetch the weather, but this is a useful skill for building custom MCP servers for your own services. Next, we'll look at how to set up a Google Sheets MCP server, which is an existing third-party integration. Finally, we'll finish up by connecting everything to Claude Desktop so that you can test and use all of these tools together. Let's get started.

A High-Level Look at MCP

Before we get into the code, let's first take a high-level look at what we'll be working on. MCP uses a simple client-server architecture, just like traditional REST APIs.

On one side, you have MCP clients. These are AI applications like Claude Desktop or Cursor. On the other side, you have MCP servers. These are the tools and the data sources that you want your AI to be able to access.

Implementation-wise, MCP servers are basically just tiny programs that can run anywhere—remotely or locally on your system. In this guide, both of the MCP servers we're using will run locally on our machine. The MCP server will be the one to communicate externally with those APIs, even though the server itself is local.

By setting this up, you'll be able to chat with your AI agent like normal, but now it has these tools available. It will be able to do things that an LLM model wouldn't normally be able to do by itself, like checking the current weather or creating and updating a spreadsheet in your Google Drive. You can probably imagine that with the right set of tools, an AI agent can be very powerful, especially if you consider that it can use all of these tools together.

The whole idea behind MCP is that any client can talk to any server as long as they both follow the MCP protocol. It doesn't even matter what programming language it's implemented in. So if you build an MCP server today, it will work with Claude Desktop, but it will also work with any other MCP-compatible client out there, including ones that come out in the future.

MCP servers expose three main types of capabilities: - Tools: Functions that AI can call to perform actions, like getting weather data, sending emails, or updating a spreadsheet. - Resources: Data sources that the AI can read from, such as files or databases. - Prompts: Templates that help the AI use tools and resources more effectively.

In today's example, we're just going to build a single tool called GetWeather. The AI will be able to call this tool to get real-time weather data for any location using the OpenWeather API.

Setting Up Your Project Environment

First, we'll need to set up a project environment. We recommend using uv for Python package management, since it works really well for this type of project. You can run these commands to get started:

uv venv
source .venv/bin/activate
uv pip install -r requirements.txt

Next, you need to get an API key from OpenWeatherMap. Head over to their website, openweathermap.org, sign up, and then create an API key. Once you have the key, you can set it as an environment variable like this:

export OPENWEATHER_API_KEY="your_api_key_here"

One of the dependencies you've installed is the official MCP Python SDK. This is what we're going to be using to create our MCP server. Here is a snippet of the core code:

import fastmcp

mcp = fastmcp.MCP()

This single line creates a fast MCP instance, which will be the server that hosts all of our tools, resources, and prompts. One server can host multiple capabilities. Then, we'll use the @mcp.tool decorator on any function that we want to expose as a tool.

@mcp.tool(
    name="get_weather",
    description="Gets the current weather for a given city.",
    dependencies={"requests": "requests"},
)
def get_weather(city: str) -> dict:
    # Function implementation goes here
    ...

Fast MCP will automatically read the function signature and its docstring to understand what parameters the tool needs and what the tool does. Our AI will know that this tool takes a city name and returns weather information. If your tool has any dependencies, you can also specify them with a dependencies parameter. Here, we need the requests library because we're going to be making an HTTP request to fetch the weather via that API. This ensures that when we configure the MCP server, it prepares all of these dependencies for us in the Python environment where the server will run.

Here is a more complete version of the function:

import os
import requests

# ... (mcp instance defined above)

@mcp.tool(
    name="get_weather",
    description="Gets the current weather for a given city.",
    dependencies={"requests": "requests"},
)
def get_weather(city: str) -> dict:
    """
    Gets the current weather for a given city.
    """
    api_key = os.environ["OPENWEATHER_API_KEY"]
    base_url = "http://api.openweathermap.org/data/2.5/weather"

    # Get coordinates for the city
    geo_url = "http://api.openweathermap.org/geo/1.0/direct"
    geo_params = {"q": city, "limit": 1, "appid": api_key}
    geo_res = requests.get(geo_url, params=geo_params).json()
    lat, lon = geo_res[0]["lat"], geo_res[0]["lon"]

    # Get weather data
    weather_params = {"lat": lat, "lon": lon, "appid": api_key, "units": "metric"}
    weather_res = requests.get(base_url, params=weather_params).json()

    return {
        "location": weather_res["name"],
        "temperature": weather_res["main"]["temp"],
        "description": weather_res["weather"][0]["description"],
    }

The function is still pretty straightforward. We use the OpenWeatherMap API to first get the coordinates for the city, and then we use those coordinates to fetch the weather data. We then return a simple dictionary with the location, temperature, and weather description. The point is that any code you can write with Python can easily become an MCP tool. You can use this to write your own custom logic, use any dependency you need, or call an API as we're doing here. You can choose to return your results as a dictionary or just as a text string.

Now that we've written all of this up, there's a really easy way to test this using an MCP inspector. You can start it by running this command:

mcp inspect mcp_weather_server:mcp --dev

Testing the Weather Server

Let's see the project in action. If you've set up the project, you should have an mcp_weather_server.py file. The important thing is remembering to set the API key in the Python environment you will use to run this. Another important detail is that we have a command to run this MCP server if this file is the entry point for our application.

In your terminal, run the following command to start the development server:

python mcp_weather_server.py

The server will start and provide a session token for authentication. You must click the authenticated link, not the base URL, because the token is required. A web UI will open up so that we can test our server before connecting it with anything else. Press the button to connect the server, and you'll see it's connected, with sections for resources, prompts, and tools.

We only created a single tool, so we can expect it to show up here. When you list the tools, the get_weather tool will appear. If you click on it, we can try it out. We can put in the name of the city we want, for example, "Tokyo." You will see the results: the tool call was a success, and the temperature in Tokyo is 29 degrees and it's cloudy. This is really good because you can use this interface to debug the server as much as you want before you plug it in as part of a bigger workflow.

Integrating with Google Sheets

Next, let's connect our AI to Google Sheets. Spreadsheets are something that people work with all the time, and it's going to be super useful for us to have this as part of our AI workflow. For many popular external tools, chances are that there's already an existing MCP server that someone else has created that we can just use. For Google Sheets, a great third-party server is available that we will use. The setup instructions involve configuring Google Cloud, which we will now walk through.

The easiest way to run this is using the uvx command, which will automatically download and run the latest version of this MCP server for us. This is a major advantage of using uv as a package manager over pip at the moment. If you're working with MCP servers, you don't have to set up your own environment; you can just run a command and it will download and manage that environment for you.

Setting Up Google Cloud Credentials

But before any of that works, we'll need to set up Google Cloud credentials so that the tool can have access to our Google Sheets. This is the most complex part of the setup, but here are the steps:

  1. Go to the Google Cloud Console and create a new project or select an existing one.
  2. Enable two APIs: the Google Sheets API and the Google Drive API. You can simply search for them in the toolbar at the top and click to enable them. Make sure you see the "API enabled" checkmark for both.
  3. Set up authentication. We'll use a service account because it will give us a long-lived credential as a JSON file that we can provide to our MCP server. To do that, search for "IAM" and click on "IAM & Admin." In the tab to the left, click on "Service Accounts."
  4. Create a service account. Click "Create service account" at the top, fill in a name, and click "Create." For the role, search for "Editor." If you want to be more secure, you can give it very specific roles, but this takes more time. We'll go with Editor for now. Then click "Continue."
  5. Generate a key. Once you have the account, click the three dots in the "Actions" column and go to "Manage keys." Then click "Add Key" and "Create new key." Choose JSON as the key type and click "Create." This will save a JSON file to your computer. It's very important to keep this file private. Move it to a secure location and remember the path, because we're going to give that path to our MCP server.
  6. Create and share a Google Drive folder. Create a new folder in your Google Drive and name it whatever you want. Then, share it with your service account's email address. You can find this email address on the service account details page in the Google Cloud console. Make sure the service account has the "Editor" role for the folder.
  7. Copy the Folder ID. This is the part of the URL that's a long string of numbers and letters. Copy that, because we're going to need it later.

You will need two environment variables for the MCP server: the path to your service account JSON file and the Google Drive folder ID.

Using the Tools with an AI Agent

Now comes the fun part: actually using these tools with an AI agent. While any MCP-compatible client will work, this guide uses Claude Desktop for its straightforward, built-in MCP support. We just need to edit the configuration file to tell Claude about our servers.

  • On Mac, the config file is located at: ~/Library/Application Support/Claude/mcp-servers.json
  • On Windows, it's in your AppData folder.

Here is a snippet of the configuration for the weather server:

{
  "mcp_weather_server": {
    "command": [
      "uv",
      "run",
      "--",
      "python",
      "/path/to/your/mcp_weather_server.py"
    ],
    "env": {
      "OPENWEATHER_API_KEY": "your_api_key_here"
    }
  }
}

Because this MCP server code exists on our machines, we'll need the absolute path to that server file. This configuration tells Claude Desktop to run this command with these arguments to start up an instance of your MCP server locally on your machine. This will be a separate process running alongside Claude Desktop, available for the AI to use when you chat with it.

The setup for the Google Sheets server is similar, but what's cool is that we can just use uvx to run the package for us directly without having to download or install it first.

{
  "google_sheets_mcp_server": {
    "command": [
      "uvx",
      "google-sheets-mcp-server"
    ],
    "env": {
      "MCP_SERVICE_ACCOUNT_FILE": "/path/to/your/service-account.json",
      "MCP_DRIVE_FOLDER_ID": "your_folder_id_here"
    }
  }
}

Again, we'll need some environment variables here. Replace these with the path to your service account JSON and the ID of the drive folder that you created earlier.

Note: In the Claude Desktop app, you can also access this configuration by going to Settings > Developer. Here you'll find all your connected tools and a button to edit the config, which will take you to the folder where the config file is located.

Your final config file should look similar to this, with both tools added. After you've saved your config file, you should be able to restart Claude Desktop and see the tools come online. If they don't work, you'll see an error message and a link to logs on how you can debug them. In this case, our tools should work and be connected. If you open the "Tools and Integrations" tab, you'll be able to see them appear.

Putting It All Together

With these tools configured, the AI agent now has enhanced capabilities. We can now ask it, for example, "What's the weather like in Tokyo?" It will figure out that it should use the get_weather tool and what the request should look like. The tool call is hidden away as part of the internal process, and the agent is able to respond with the answer.

Similarly, we can test that the Google Sheets tool works. I can say, "Create a new spreadsheet with 10 movie recommendations." Once that's completed, we can go back to our Google Drive folder and see that it's created the spreadsheet for us and has filled it in.

The agent can understand what tools are available and how to use them based on natural language. You don't have to remember specific commands or syntax. You can just ask what you want in English, and it will figure out how to use the tools and how to combine them. For example, we could say, "I'm going on holiday to London and then Bangkok for a week each, and I want to get the weather there so I know what I should pack." It will fetch the weather for both locations and provide a recommendation.

Of course, we can combine the use of tools as well, getting it to fetch the weather for a bunch of different locations and then put that into a spreadsheet, like in the demo at the start of the article.

This simple project demonstrates the power of AI agents, which is only just beginning to be explored. There are already numerous MCP servers available, with more being developed constantly.

Join the 10xdev Community

Subscribe and get 8+ free PDFs that contain detailed roadmaps with recommended learning periods for each programming language or field, along with links to free resources such as books, YouTube tutorials, and courses with certificates.

Recommended For You

Up Next