MCP-Server

sandeep-13-dev/MCP-Server

3.2

If you are the rightful owner of MCP-Server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

This repository provides a generic, production-ready FastMCP server template for creating and testing Model Context Protocol (MCP) servers.

Tools
2
Resources
0
Prompts
0

🧠 FastMCP Generic Server Template

Build, Run, and Inspect Your Own MCP Server

This repository provides a generic, production-ready FastMCP server that you can connect to MCPJam Inspector — a developer tool for testing and inspecting Model Context Protocol (MCP) servers.


Table of Contents

  1. Overview
  2. Project Structure
  3. Installation
  4. Server Setup
  5. Running the Server
  6. Testing with MCPJam Inspector
  7. Docker Setup
  8. Example Output
  9. Customization
  10. Environment Variables
  11. Next Steps

Overview

This project demonstrates how to create a FastMCP-compatible HTTP server using FastAPI and FastMCP. It defines:

  • Tools: Callable functions (e.g., summarizer, translator)
  • Resources: Structured data sources (e.g., server info)
  • Prompts: Instruction templates for LLMs

You can test and inspect this server easily using MCPJam Inspector.


Project Structure

fastmcp-server/
├── main.py               # MCP Server entry point
├── pyproject.toml        # uv project file
├── docker-compose.yml    # Docker Compose for local container setup
├── Dockerfile            # Lightweight image definition
├── .env                  # Environment configuration
└── README.md             # Technical documentation

Installation

1. Initialize Project

pip install uv
uv init .

2. Add Required Dependencies

uv add "fastapi>=0.121.0" "fastmcp>=2.13.0.2" "uvicorn>=0.29.0"

3. Sync Project

uv sync

Server Setup

Below is the generic FastMCP server template:

"""
FastMCP Generic Server Template
===============================
A reusable template for creating FastMCP-compatible servers.

Author: Your Name
Version: 1.0.0
"""

from fastmcp import FastMCP
from fastmcp.prompts import Prompt
import uvicorn
import os
from datetime import datetime
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# ============================================================
# MCP SERVER CONFIGURATION
# ============================================================

mcp = FastMCP(
    name="Example MCP Server",
    instructions="""
Welcome to the Example MCP Server!

This server exposes generic tools, resources, and prompts
to demonstrate the MCP protocol.
"""
)

# ============================================================
# TOOLS
# ============================================================

@mcp.tool()
def echo(input_text: str) -> dict:
    """Echoes the input text."""
    return {"result": f"You said: {input_text}"}

@mcp.tool()
def summarize(text: str) -> dict:
    """Returns a short summary of input text."""
    summary = text[:50] + "..." if len(text) > 50 else text
    return {"summary": summary, "original_length": len(text)}

# ============================================================
# RESOURCES
# ============================================================

@mcp.resource("server://info")
def get_server_info() -> dict:
    """Returns information about this MCP server."""
    return {
        "server_name": "Example MCP Server",
        "version": "1.0.0",
        "protocol": "MCP 2025-03-26",
        "transport": "Streamable HTTP",
        "available_tools": ["echo", "summarize"],
        "endpoint": f"http://{os.getenv('MCP_HOST', '127.0.0.1')}:{os.getenv('MCP_PORT', '7007')}/mcp"
    }

@mcp.resource("server://status")
def get_status() -> dict:
    """Provides runtime status."""
    return {
        "status": "active",
        "timestamp": datetime.now().isoformat()
    }

# ============================================================
# PROMPTS
# ============================================================

@mcp.prompt(name="default_prompt")
def default_prompt() -> str:
    """Provides guidance for AI models."""
    return (
        "You are connected to Example MCP Server. Use the tools "
        "'echo' and 'summarize' to process user text efficiently."
    )

# ============================================================
# SERVER STARTUP
# ============================================================

if __name__ == "__main__":
    host = os.getenv("MCP_HOST", "127.0.0.1")
    port = int(os.getenv("MCP_PORT", "7007"))
    path = os.getenv("MCP_PATH", "/mcp")

    print("=" * 60)
    print("🚀 FastMCP Server")
    print("=" * 60)
    print(f"Server Name: {mcp.name}")
    print(f"Transport: Streamable HTTP")
    print(f"Endpoint: http://{host}:{port}{path}")
    print(f"Inspector: MCPJam Inspector (see below)")
    print("=" * 60)

    mcp_app = mcp.http_app(path=path)
    app = FastAPI(lifespan=mcp_app.lifespan)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["GET", "POST", "OPTIONS"],
        allow_headers=["*"],
        expose_headers=["mcp-session-id", "mcp-protocol-version"],
    )
    app.mount("", mcp_app)
    uvicorn.run(app, host=host, port=port, log_level="info")

Testing with MCPJam Inspector

1. Install MCPJam Inspector

npm install -g @mcpjam/inspector
# or
npx @mcpjam/inspector

2. Start Server

uv run main.py

3. Run Inspector

npx @mcpjam/inspector

Then enter:

http://127.0.0.1:7007/mcp

You’ll see:

  • Tools: echo, summarize
  • Resources: server://info, server://status
  • Prompts: default_prompt

Docker Setup

Dockerfile

Use a lightweight image for faster build and lower memory usage.

# Dockerfile
FROM python:3.11-slim-bookworm

WORKDIR /app

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
ENV UV_PROJECT_ENVIRONMENT=/app/.venv

COPY . /app

RUN pip install uv && uv sync

EXPOSE 7007

CMD ["uv", "run", "python", "main.py"]

docker-compose.yml

Run the MCP server easily via Docker Compose.

version: "3.9"
name: Greet-MCP-Server

services:
  mcp-server:
    container_name: FastMCP-Server
    image: python:3.11-slim-bookworm
    working_dir: /app
    environment:
      - UV_PROJECT_ENVIRONMENT=/app/.venv
      - UV_LINK_MODE=copy
    env_file:
      - .env
    ports:
      - "${MCP_PORT}:${MCP_PORT}"
    volumes:
      - ./:/app
      - venv-data:/app/.venv
    command: >
      sh -c "pip install uv && uv run python main.py"

volumes:
  venv-data:

.env Example

MCP_HOST=0.0.0.0
MCP_PORT=7007
MCP_PATH=/mcp

Run with Docker Compose

docker compose up --build

Output:

FastMCP-Server  | FastMCP Server
FastMCP-Server  | Endpoint: http://0.0.0.0:7007/mcp
FastMCP-Server  | Inspector: MCPJam Inspector

Then connect via:

npx @mcpjam/inspector
# Endpoint: http://127.0.0.1:7007/mcp

Example Output

============================================================
 FastMCP Server
============================================================
Server Name: Example MCP Server
Transport: Streamable HTTP
Endpoint: http://127.0.0.1:7007/mcp
Inspector: MCPJam Inspector
============================================================

Customization

FeatureDescriptionExample
Add new toolDefine new @mcp.tool() functionsText analysis, translation
Add resourceProvide structured data sourcesSystem info, logs
Add promptCreate AI instruction templatesConversational roles
Modify transportSwitch to WebSocket if neededmcp.ws_app()

Environment Variables

Create a .env file (optional):

MCP_HOST=0.0.0.0
MCP_PORT=7007
MCP_PATH=/mcp

Next Steps

You can extend this project with:

  • Database or vector search tools
  • Ollama / LangChain integration
  • Agent orchestration (n8n / FastMCP Framework)
  • Monitoring via MCPJam Inspector