# Building Your First MCP Server with Python FastMCP: A Hands-On Guide to Enterprise AI Integrations

> Source: <https://pub.towardsai.net/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-enterprise-ai-integrations-b984e7f512d9?source=rss----98111c9905da---4>
> Published: 2026-11-25 03:07:02+00:00

**Recommendation:** Wrap each enterprise action as a FastMCP tool with a clear description so the LLM can select it dynamically, and cache frequently read values like leave balances with lru_cache to cut repeated lookups.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

**Why Do We Need an MCP Server?**

Traditionally, systems have interacted with one another through APIs. While APIs provide a well-established mechanism for system integration, they require the consuming application to understand the API specifications in advance, including available endpoints, request and response formats, authentication mechanisms and expected behavior. Developers must explicitly implement the appropriate API calls, handle the interaction flow and account for various exception scenarios to ensure reliable communication.

With the advent of AI and Large Language Models (LLMs), the way applications interact with external systems is evolving. Although LLM-powered applications can invoke APIs directly, this approach still requires developers to define and manage the specifications of each API and determine when and how it should be invoked.

This is where the **Model Context Protocol (MCP)** and MCP servers become particularly powerful.

MCP provides a standardized way for AI applications to discover and interact with external tools and resources. An MCP server exposes a set of capabilities (such as tools, resources and prompts) along with descriptions and contextual information about how they can be used. An AI application can discover these capabilities dynamically and make them available to the LLM.

Based on the user’s request and the context of the conversation, the LLM can identify the appropriate tool and request its invocation through the MCP client-server interaction. This significantly reduces the need to hardcode individual API specifications and tool-selection logic into the AI application.

Another important advantage is that **multiple MCP servers can be connected to a single AI application**. Each MCP server can expose its own set of tools and resources, progressively expanding the capabilities available to the LLM. These MCP servers can, in turn, connect to different enterprise systems, APIs, databases, file systems and other services.

This creates a flexible and extensible architecture in which the LLM can interact with a wide range of systems through a standardized protocol, rather than requiring direct integration with every underlying API.

The figure below illustrates this architecture, showing how an LLM interacts with multiple MCP servers through an MCP client, instead of directly managing connections to individual APIs and enterprise systems.

**How to build a MCP server ?**

We will use the Python-based **FastMCP** library to develop our MCP server. FastMCP simplifies the implementation of MCP servers by providing a high-level framework for exposing tools, resources, and other capabilities to AI applications without having to deal with the underlying protocol implementation in detail.

The following Python libraries are required to build and run our MCP server:

```
pip install uvpip install - upgrade typeruv add mcp[cli]# this will build the scaffolding of projectuv init my-first-mcp-server
```

**Let’s Build Your First MCP Server: Employee Leave Management**

In this example, we will build a Python-based MCP server to manage employee leave requests in an enterprise environment. The server will expose tools that allow an AI application to interact with the leave management system, such as checking leave balances, submitting leave requests, and retrieving leave information.

We will use the FastMCP library to implement the server and expose these functionalities as MCP tools.

The entire project is open source and MIT licensed:

``` python
from mcp.server.fastmcp import FastMCPfrom typing import Listfrom functools import lru_cache# Create an MCP servermcp = FastMCP("LeaveManager")# In memory mock database with 10 leaves days to startemployee_leaves = {"E-1": {"balance": 7, "history": ["2025–12–25", "2026–03–01", "2026–04–21"]},"E-2": {"balance": 9, "history": ["2026–11–06"]}# cache leave balance for faster retrieval, with a max cache size of '5' entries@lru_cache(maxsize=5)def get_balance_cached(emp_id: str):    return employee_leaves.get(emp_id)# Tool: check leave balance@mcp.tool()async def get_leave_balance(emp_id: str) -> str:    """get leave balance for employee"""    data = get_balance_cached(emp_id)    if data:        return f"{emp_id} has {data['balance']} leave days remaining. Here is history of past leaves: {data['history']}"    return "Employee ID not found."# Tool: apply for leaves with specific dates@mcp.tool()async def apply_leave(emp_id: str, leave_dates: List[str]) -> str:    """    Apply leave for specific dates (e.g. ["2024-12-25", "2025-01-01"] )    """    if emp_id not in employee_leaves:        return "Employee ID not found."    requested_days = len(leave_dates)    available_leaves = employee_leaves[emp_id]["balance"]    if available_leaves < requested_days:        return f"Insufficient leave balance. You requested {requested_days} leave_days."    # deduct balance and add to history    employee_leaves[emp_id]["balance"] -= requested_days    employee_leaves[emp_id]["history"].extend(leave_dates)    return f"Leave applied for {requested_days} days. Remaining leaves: {employee_leaves[emp_id]['balance']}"# Tool : get leave history@mcp.tool()async def get_employee_history(emp_id: str) -> str:    data = employee_leaves.get(emp_id)    if data:        history = ', '.join(data["history"]) if data["history"] else "No leaves taken."        return f"Leave history for {emp_id}: {history}"    return "Employee ID not found."# Add a greeting resource, data that can be read by clients(API or files)@mcp.resource("greeting://{name}")def get_greeting(name: str) -> str:    """Get a personalized greeting"""    return f"Hello, {name}! How can I assist you?"# Add a prompt@mcp.prompt()def greet_user(name: str, style: str = "friendly") -> str:    """Generate a greeting prompt"""    styles = {        "friendly": "Please write a warm, friendly greeting",        "formal": "Please write a formal, professional greeting",        "casual": "Please write a casual, relaxed greeting",    }    return f"{styles.get(style, styles['friendly'])} for someone named {name}."# Run with streamable HTTP transport:- this is when MCP server is deployed as separate HTTP service.# e.g. transport="streamable-http" or (transport="http", host="0.0.0.0", port=8000)# Run with 'stdio' transport instead when running as a local MCP Serverif __name__ == "__main__":    mcp.run(transport="stdio")
```

**How to Run the MCP Server?**

There are several ways to run and test an MCP server. Depending on the development environment and the intended use case, we can launch the server locally, connect it to an MCP-compatible client or use dedicated tools to validate its functionality.

In this section, we will explore the different ways to execute the MCP server, test its exposed tools and validate that it interacts correctly with the underlying systems.

```
# ==========option 1: this will find the claude installation and update the claude_desktop_config.json# With the details of the path to main.pyuv run mcp install main.py
```

First, ensure that Claude Desktop is installed on your machine. Lauch the application and navigate to the following menu :-

New -> Settings -> Plugins.

This is where the mcp server gets added as a plugin. If not, you can also add it manually.

Claude allows you to enable or disable the plugin directly from the chat window. Make sure the MCP plugin is enabled in the current session before interacting with the server.

Enter your queries in natural language. Claude will automatically identify the most relevant tool based on your query and prompt you for permission before invoking it. Once you grant permission, Claude will execute the selected tool and display the results in the conversation.

*You may also choose to add some of the default plugins ( viz MCP servers) available from library.*

2. With MCP Inspector

```
# ==========option 2: this will install and run the mcp inspectoruv run mcp dev main.py
```

Executing the above command will either automatically launch the MCP Inspector in your browser or display a URL containing an authentication token that you can copy and paste into your browser to access the inspector.

The MCP Inspector is a web-based tool provided by the Model Context Protocol ecosystem (@modelcontextprotocol/inspector@2.x or higher). It allows you to connect to your MCP server, explore its available tools and resources, and interactively test and validate its functionality.

MCP Inspector url follow this format :-

[http://127.0.0.1:6274/?MCP_INSPECTOR_API_TOKEN=<auth-token](http://127.0.0.1:6274/?MCP_INSPECTOR_API_TOKEN=%3cauth-token)>

3. In Editor

```
# ==========option 3: this will install and run with mcp.json in editoruv run mcp run main.py
```

Of course, there are several other ways to run an MCP server, including hosting it remotely or deploying it on the same server as the consuming application.

In a future article, we will explore how to package our MCP server as a Docker container and deploy it using containerized infrastructure. This will provide a more scalable, portable and flexible approach to deploying and managing MCP servers across different environments.

Stay tuned!

[Building Your First MCP Server with Python FastMCP: A Hands-On Guide to Enterprise AI Integrations](https://pub.towardsai.net/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-enterprise-ai-integrations-b984e7f512d9) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.
