Skip to content
AI & Development

Python FastMCP Server Script: Build Local AI CLI Tools (2027)

Copy-paste a production Python FastMCP server script to expose safe system diagnostics and CLI tools over stdio or Streamable HTTP to AI agents in 2027.

Updated: 10 min read 1 views
Share: Facebook X LinkedIn WhatsApp

A production-ready python fastmcp server script lets you expose local DevOps utilities, log readers, and system diagnostics directly to AI coding agents over a typed, schema-validated protocol without writing brittle JSON-RPC boilerplate. Before the Model Context Protocol (MCP) standardized tool discovery, connecting Claude Code, Cursor, or a local Ollama agent to your server meant wrapping every CLI command in custom function-calling glue code. With FastMCP, a single Python file turns type-annotated functions into discoverable MCP tools, read-only resources, and reusable prompt templates. Built for Linux and macOS environments running Python 3.10+ and FastMCP, the script below implements a read-only server diagnostics MCP server with strict path allowlisting, a --dry-run self-test mode, dual stdio and Streamable HTTP transport support, and systemd deployment.

Key Takeaways & Script Specs

  • Runtime & Dependencies: Python 3.10+ and fastmcp (managed cleanly via uv or venv).
  • Supported Transports: Local stdio for desktop/CLI clients and Streamable HTTP (http://127.0.0.1:8000/mcp) for remote or containerized agents.
  • Included Capabilities: 3 typed MCP tools (disk usage, service status, bounded log tail) plus 1 dynamic resource template.
  • Safety Controls: Read-only command execution (no shell interpolation), explicit directory/service allowlists, --dry-run verification, and localhost-only HTTP binding by default.

Why FastMCP Replaced Raw JSON-RPC Boilerplate in 2027

Writing an MCP server against raw protocol primitives requires manually registering capability schemas, serializing JSON-RPC envelopes, handling stdio framing without polluting stdout, and validating tool arguments by hand. As documented in the official FastMCP Create an MCP Server tutorial, FastMCP infers JSON schemas directly from Python type hints and docstrings, handles both stdio and Streamable HTTP transports, and ships with a dedicated CLI for local inspection and client installation.

For DevOps engineers and AI builders, the real win is operational safety. Instead of handing an LLM raw bash execution over your entire machine, an MCP server exposes narrow, deterministic Python functions. You decide which systemd units can be queried, which log directories can be tailed, and how many lines can be returned—making it a natural companion to your local Python and Ollama agent workflow.

Architecture and Transport Flow

An MCP server acts as a strict boundary between an AI client (such as Claude Code, Cursor, or a custom Python agent) and your host operating system. Every tool invocation passes through schema validation and allowlist checks before touching disk or subprocesses:

+-------------------------------------------------------------------+

|  1. AI Client / CLI (Claude Code, Cursor, MCP Inspector, Ollama)  |
|---|
                                  | (stdio pipe OR Streamable HTTP)
                                  v
+-------------------------------------------------------------------+
|  2. FastMCP Protocol Layer (@mcp.tool / @mcp.resource)            |
|     - Validates argument types via Pydantic / Python type hints   |
|     - Enforces stdout purity in stdio mode (logs go to stderr)    |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  3. Guarded Execution & Allowlists                                |
|     - ALLOWED_LOG_DIRS (canonical Path.resolve() check)           |
|     - ALLOWED_SERVICES (exact match, shell=False subprocess)      |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  4. Structured JSON / Text Response Back to AI Client             |
+-------------------------------------------------------------------+

Notice one critical rule in stdio mode: standard output (stdout) is reserved exclusively for JSON-RPC protocol frames. Any stray print() call corrupts the stream and crashes the client connection. Our script routes all diagnostics to sys.stderr via Python’s logging module so stdio remains completely clean.

Comparing MCP Transport and Tooling Options in 2027

Choosing between stdio and Streamable HTTP depends on whether your AI client runs on the same workstation or connects across a private network.

Transport / PatternExecution ModelBest Use CaseAuth & Network SurfaceDebugging Tool
stdio TransportClient spawns subprocessLocal IDE & CLI agentsOS user permissions onlyMCP Inspector CLI
Streamable HTTPPersistent daemon (/mcp)Remote servers & containersBind 127.0.0.1 + bearer authfastmcp CLI / HTTP
Legacy SSE TransportDeprecated dual-endpointOlder 2024–2025 clientsReplaced by Streamable HTTPBrowser / curl
Raw Shell ToolingUnbounded bash -cPrototyping only (risky)Full shell blast radiusManual logs

Whenever you run tools on a production VPS, pair your MCP server with dedicated single-purpose monitors like a Docker health check script or an Nginx log analyzer script so the AI agent can inspect structured health summaries rather than parsing gigabytes of raw text.

Prerequisites and Virtual Environment Setup

Isolate FastMCP inside a dedicated virtual environment (or manage it with uv, as recommended in the FastMCP CLI documentation). Run the commands below to create the project directory and install fastmcp:

sudo mkdir -p /opt/syshealth-mcp
sudo chown "$USER":"$USER" /opt/syshealth-mcp
cd /opt/syshealth-mcp

python3 -m venv .venv
source .venv/bin/activate

pip install --upgrade pip
pip install "fastmcp>=2.10.0"

If you plan to test the server interactively from the terminal without attaching a full desktop IDE, install Node.js 20+ so you can invoke the official MCP Inspector CLI via npx @modelcontextprotocol/inspector.

Complete Production Python FastMCP Server Script

Save the script below as /opt/syshealth-mcp/syshealth_mcp.py. It uses Python’s argparse module to support --transport, --host, --port, and --dry-run self-checks, and exposes three read-only DevOps tools plus a dynamic resource template.

#!/usr/bin/env python3
"""
Production Python FastMCP Server Script (2027)
Exposes read-only system health, service status, and bounded log-tail tools
over stdio or Streamable HTTP with strict allowlists and --dry-run checks.
"""

import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
from collections import deque
from pathlib import Path
from typing import Dict, List

from fastmcp import FastMCP
CRITICAL: Always log to stderr so stdio JSON-RPC framing stays clean
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("syshealth_mcp")

mcp = FastMCP(
name="syshealth-mcp",
instructions="Read-only server diagnostics for disk usage, allowed systemd services, and bounded log tails.",
)

ALLOWED_SERVICES = {
s.strip()
for s in os.getenv("MCP_ALLOWED_SERVICES", "docker,nginx,postgresql").split(",")
if s.strip()
}

ALLOWED_LOG_DIRS = [
Path(p.strip()).resolve()
for p in os.getenv("MCP_ALLOWED_LOG_DIRS", "/var/log/nginx,/var/log").split(",")
if p.strip()
]

def _is_path_allowed(target: Path) -> bool:
"""Verify target resolves inside an allowlisted log directory."""
try:
resolved = target.resolve(strict=True)
except OSError:
return False
return any(
resolved == base or base in resolved.parents for base in ALLOWED_LOG_DIRS
)

@mcp.tool()
def get_disk_usage(mount_path: str = "/") -> Dict[str, object]:
"""Return total, used, free gigabytes and usage percentage for a mount path."""
path = Path(mount_path)
if not path.exists():
return {"error": f"Mount path does not exist: {mount_path}"}

usage = shutil.disk_usage(path)
gb = 1024 ** 3
pct = round((usage.used / usage.total) * 100.0, 2) if usage.total else 0.0
return {
    "mount": str(path),
    "total_gb": round(usage.total / gb, 2),
    "used_gb": round(usage.used / gb, 2),
    "free_gb": round(usage.free / gb, 2),
    "used_percent": pct,
}

@mcp.tool()
def check_service_status(service_name: str) -> Dict[str, str]:
"""Check systemd active state for an allowlisted service without shell interpolation."""
clean_name = service_name.strip()
if clean_name not in ALLOWED_SERVICES:
return {
"service": clean_name,
"error": f"Service not in allowlist: {sorted(ALLOWED_SERVICES)}",
}

try:
    proc = subprocess.run(
        ["systemctl", "is-active", clean_name],
        capture_output=True,
        text=True,
        timeout=5,
        check=False,
    )
    state = proc.stdout.strip() or proc.stderr.strip() or "unknown"
    return {"service": clean_name, "state": state}
except FileNotFoundError:
    return {"service": clean_name, "error": "systemctl not available on this host"}
except subprocess.TimeoutExpired:
    return {"service": clean_name, "error": "systemctl timed out"}

@mcp.tool()
def tail_allowed_log(file_path: str, lines: int = 40) -> Dict[str, object]:
"""Read the last N lines (max 200) of an allowlisted plain-text log file."""
bounded_lines = max(1, min(lines, 200))
target = Path(file_path)
if not _is_path_allowed(target) or not target.is_file():
return {
"file": file_path,
"error": "Access denied or file missing outside MCP_ALLOWED_LOG_DIRS",
}

try:
    with target.open("r", encoding="utf-8", errors="replace") as handle:
        tail: List[str] = list(deque(handle, maxlen=bounded_lines))
    return {
        "file": str(target.resolve()),
        "line_count": len(tail),
        "content": "".join(tail),
    }
except OSError as exc:
    return {"file": file_path, "error": str(exc)}

@mcp.resource("syshealth://allowlist")
def get_allowlist_resource() -> str:
"""Expose active service and directory allowlists as a read-only MCP resource."""
return json.dumps(
{
"allowed_services": sorted(ALLOWED_SERVICES),
"allowed_log_dirs": [str(p) for p in ALLOWED_LOG_DIRS],
},
indent=2,
)

def run_dry_run_checks() -> int:
"""Validate configuration, allowlists, and disk probe without starting a transport."""
logger.info("[DRY-RUN] Validating FastMCP server configuration...")
logger.info("[DRY-RUN] Allowed services: %s", sorted(ALLOWED_SERVICES))
logger.info("[DRY-RUN] Allowed log dirs: %s", [str(p) for p in ALLOWED_LOG_DIRS])
disk = get_disk_usage("/")
logger.info("[DRY-RUN] Root disk check: %s", json.dumps(disk))
return 0

def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run the syshealth FastMCP server over stdio or Streamable HTTP."
)
parser.add_argument(
"--transport",
choices=("stdio", "http"),
default=os.getenv("MCP_TRANSPORT", "stdio"),
help="MCP transport protocol (default: stdio)",
)
parser.add_argument(
"--host",
default=os.getenv("MCP_HOST", "127.0.0.1"),
help="Bind host for HTTP transport (default: 127.0.0.1)",
)
parser.add_argument(
"--port",
type=int,
default=int(os.getenv("MCP_PORT", "8000")),
help="Bind port for HTTP transport (default: 8000)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Validate allowlists and run a local disk probe without starting the server",
)
return parser.parse_args()

def main() -> int:
args = parse_args()
if args.dry_run:
return run_dry_run_checks()

logger.info("Starting syshealth-mcp using transport=%s", args.transport)
if args.transport == "http":
    mcp.run(transport="http", host=args.host, port=args.port)
else:
    mcp.run(transport="stdio")
return 0

if name == "main":
sys.exit(main())

Before registering the script with an AI client, verify allowlists and stderr logging safely using --dry-run, then list your exposed tools with the MCP Inspector CLI:

chmod +x /opt/syshealth-mcp/syshealth_mcp.py
/opt/syshealth-mcp/.venv/bin/python /opt/syshealth-mcp/syshealth_mcp.py --dry-run

# Inspect tools over stdio without launching a full IDE:
npx @modelcontextprotocol/inspector --cli /opt/syshealth-mcp/.venv/bin/python /opt/syshealth-mcp/syshealth_mcp.py --method tools/list

Connecting Clients and Running Streamable HTTP via Systemd

For local desktop tools like Claude Desktop or Cursor, register the script in your mcp.json configuration using the virtual environment’s absolute Python path so dependencies always resolve cleanly. You can also explore other free developer CLI tools to complement your terminal workflow:

{
  "mcpServers": {
    "syshealth": {
      "command": "/opt/syshealth-mcp/.venv/bin/python",
      "args": ["/opt/syshealth-mcp/syshealth_mcp.py", "--transport", "stdio"],
      "env": {
        "MCP_ALLOWED_SERVICES": "docker,nginx,postgresql",
        "MCP_ALLOWED_LOG_DIRS": "/var/log/nginx"
      }
    }
  }
}

If you want a persistent Streamable HTTP endpoint (http://127.0.0.1:8000/mcp) on a Linux server, run it behind a systemd unit with NoNewPrivileges=true and an isolated 0600 environment file:

sudo tee /etc/systemd/system/syshealth-mcp.service >/dev/null <<'EOF'
[Unit]
Description=SysHealth FastMCP Streamable HTTP Server
After=network-online.target

[Service]
Type=simple
WorkingDirectory=/opt/syshealth-mcp
Environment=MCP_TRANSPORT=http
Environment=MCP_HOST=127.0.0.1
Environment=MCP_PORT=8000
ExecStart=/opt/syshealth-mcp/.venv/bin/python /opt/syshealth-mcp/syshealth_mcp.py --transport http
Restart=always
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now syshealth-mcp

Troubleshooting and Security Hardening

Because MCP servers bridge untrusted LLM tool calls to real host resources, enforce these three guardrails before exposing any server beyond localhost:

  • Prevent Stdout Corruption in Stdio Mode: Never use bare print() statements in a stdio MCP server. Even a single debug print breaks JSON-RPC framing; always configure logging with stream=sys.stderr.
  • Guard Against Path Traversal: Never concatenate user-supplied filenames with string prefixes. Always call Path.resolve(strict=True) and check base in resolved.parents so ../../etc/shadow is rejected before opening the file.
  • Bind Localhost or Terminate TLS + Auth: Keep --host 127.0.0.1 by default. If remote agents must reach the /mcp endpoint over a network, place Nginx or Caddy in front of port 8000 with HTTPS and bearer token authentication—never expose an unauthenticated MCP HTTP port to 0.0.0.0.

Frequently Asked Questions

What is the difference between FastMCP stdio and Streamable HTTP transports?

Stdio spawns the Python script as a local subprocess per client session and communicates over standard input/output, making it ideal for local IDEs. Streamable HTTP runs a persistent web endpoint (/mcp) suitable for remote servers, containers, or shared team agents.

Why does logging to stdout break an MCP stdio server?

In stdio mode, the client reads JSON-RPC messages directly from the server’s stdout stream. Any non-JSON text written via print() corrupts the protocol stream, so all logs must be directed to stderr.

How does this Python FastMCP server script prevent command injection?

It avoids shell=True completely, validates service names against an explicit ALLOWED_SERVICES set, and passes fixed argument lists directly to subprocess.run() with a 5-second timeout.

Can I test FastMCP tools without connecting Claude or Cursor?

Yes. Run the script with –dry-run to verify allowlists and disk probes, or use npx @modelcontextprotocol/inspector –cli to invoke tools/list and tools/call directly from your terminal.

How do I add more allowed log directories or systemd services?

Set the MCP_ALLOWED_LOG_DIRS and MCP_ALLOWED_SERVICES environment variables as comma-separated lists in your mcp.json env block or systemd unit file.

Is it safe to bind Streamable HTTP to 0.0.0.0 in production?

No. Binding an unauthenticated MCP server to 0.0.0.0 exposes your tools to any network host. Always bind to 127.0.0.1 and put an authenticated TLS reverse proxy in front if remote access is required.

Leave a Reply

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

Stay ahead of the curve. Zero spam.

Get our weekly curation of tested scripts, DevOps blueprints, and new dev tools.