{"slug": "building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-ai", "title": "Building Your First MCP Server with Python FastMCP: A Hands-On Guide to Enterprise AI Integrations", "summary": "A hands-on guide demonstrates building an MCP server in Python with the FastMCP library, exposing employee leave-management tools — balance checks, leave submission and leave history — to AI applications through the Model Context Protocol. The tutorial, released under an MIT license, scaffolds the project with `uv init my-first-mcp-server` and `uv add mcp[cli]`, and uses an in-memory mock database seeded with 10 leave days per employee plus an `lru_cache` capped at 5 entries for faster balance retrieval. The approach lets an LLM discover and invoke tools dynamically instead of hardcoding each API specification, and allows multiple MCP servers to connect to a single AI application.", "body_md": "**Why Do We Need an MCP Server?**\n\nTraditionally, 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.\n\nWith 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.\n\nThis is where the **Model Context Protocol (MCP)** and MCP servers become particularly powerful.\n\nMCP 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.\n\nBased 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.\n\nAnother 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.\n\nThis 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.\n\nThe 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.\n\n**How to build a MCP server ?**\n\nWe 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.\n\nThe following Python libraries are required to build and run our MCP server:\n\n```\npip install uvpip install - upgrade typeruv add mcp[cli]# this will build the scaffolding of projectuv init my-first-mcp-server\n```\n\n**Let’s Build Your First MCP Server: Employee Leave Management**\n\nIn 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.\n\nWe will use the FastMCP library to implement the server and expose these functionalities as MCP tools.\n\nThe entire project is open source and MIT licensed:\n\n``` python\nfrom 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\")\n```\n\n**How to Run the MCP Server?**\n\nThere 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.\n\nIn 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.\n\n```\n# ==========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\n```\n\nFirst, ensure that Claude Desktop is installed on your machine. Lauch the application and navigate to the following menu :-\n\nNew -> Settings -> Plugins.\n\nThis is where the mcp server gets added as a plugin. If not, you can also add it manually.\n\nClaude 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.\n\nEnter 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.\n\n*You may also choose to add some of the default plugins ( viz MCP servers) available from library.*\n\n2. With MCP Inspector\n\n```\n# ==========option 2: this will install and run the mcp inspectoruv run mcp dev main.py\n```\n\nExecuting 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.\n\nThe 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.\n\nMCP Inspector url follow this format :-\n\n[http://127.0.0.1:6274/?MCP_INSPECTOR_API_TOKEN=<auth-token](http://127.0.0.1:6274/?MCP_INSPECTOR_API_TOKEN=%3cauth-token)>\n\n3. In Editor\n\n```\n# ==========option 3: this will install and run with mcp.json in editoruv run mcp run main.py\n```\n\nOf 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.\n\nIn 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.\n\nStay tuned!\n\n[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.", "url": "https://wpnews.pro/news/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-ai", "canonical_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_at": "2026-11-25 03:07:02+00:00", "updated_at": "2026-11-25 03:42:58.706279+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "ai-tools", "developer-tools", "artificial-intelligence"], "entities": ["Model Context Protocol", "FastMCP", "Python", "uv", "LeaveManager"], "also_reported_by": [], "takeaway": "Expose enterprise functions as FastMCP tools with docstring-described capabilities and cache hot lookups with `lru_cache(maxsize=5)`, so an LLM can discover and call them without hardcoded API specs.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-ai", "markdown": "https://wpnews.pro/news/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-ai.md", "text": "https://wpnews.pro/news/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-ai.txt", "jsonld": "https://wpnews.pro/news/building-your-first-mcp-server-with-python-fastmcp-a-hands-on-guide-to-ai.jsonld"}}