developer-guide-building-securing-mcp-servers

Developer Guide to Building and Securing MCP Servers

Learn how to build, test, and secure Model Context Protocol (MCP) servers. Covers Tools, Resources, stdio vs HTTP transports, FastMCP Python code, and security.

Are you tired of writing custom glue code every time you want an AI assistant to read your database, check logs, or call an internal API?

Without a standard protocol, every model and IDE requires a different plugin format, which turns simple integrations into fragile maintenance headaches.

The good news is that the Model Context Protocol (MCP) solves this by giving AI agents a single, universal way to connect to local tools and data. In this master guide, we will show you how to build, test, and secure MCP servers from scratch.

Executive Summary

  • One Standard Protocol: MCP acts like a USB-C port for AI applications, letting any MCP-compatible client talk to any MCP server.
  • Three Core Primitives: Servers expose Tools (executable functions), Resources (read-only data), and Prompts (reusable workflow templates).
  • Two Main Transports: Use stdio for local desktop tools and Streamable HTTP for remote cloud services.
  • Security First: Never trust raw model arguments; validate file paths, enforce read-only database roles, and log only to stderr on stdio servers.

Table of Contents

How the Model Context Protocol Works

MCP uses a simple client-server architecture built on JSON-RPC 2.0. An AI application (such as an IDE, desktop assistant, or custom agent) runs an MCP Client, which connects to one or more lightweight MCP Servers.

When the session starts, the client asks the server what capabilities it offers. The server replies with a typed list of available tools, their JSON Schema parameters, and readable resources.

Because the protocol separates the AI model from the integration code, you write your server once and reuse it across multiple AI clients.

MCP Core Primitives and Transports

Before writing code, it helps to understand the three building blocks an MCP server can expose and the two transport layers that carry messages.

ComponentPurposeWho Controls ItCommon Example
ToolsExecute actions or query APIsModel-controlled (with user approval)search_logs, create_ticket, run_sql_select
ResourcesExpose read-only contextApplication-controlledfile://docs/api.md, db://schema/users
PromptsProvide reusable slash workflowsUser-controlled/review-pr, /summarize-incident
stdio TransportLocal subprocess pipes (stdin/stdout)Local host machineLocal filesystem, Git, or SQLite tools
Streamable HTTPRemote HTTP POST + SSE streamingCloud / internal networkShared team APIs, SaaS connectors
Developer Guide to Building and Securing MCP Servers Data Chart

Method 1: Test an MCP Server Using the MCP Inspector (Quick Start)

Before connecting a new MCP server to an AI agent, test it directly in your browser using the official MCP Inspector. This lets you inspect JSON schemas and call tools manually without burning LLM tokens.

Step 1: Launch the MCP Inspector

Make sure Node.js is installed on your machine, then run the inspector via npx against your server script (for example, server.py):

npx @modelcontextprotocol/inspector python server.py

The command starts a local proxy and opens a web dashboard where you can inspect every tool and resource your server registers.

Step 2: Inspect Tool Schemas and Test Inputs

In the Inspector UI, click Connect, then open the Tools tab. Select any tool to view its auto-generated JSON Schema, enter sample parameters, and click Run Tool to verify the exact JSON response.

Pro Tip: Use the MCP Inspector whenever a client fails to parse your tool arguments. Seeing the raw JSON-RPC payload immediately reveals missing descriptions or mismatched types.

Method 2: Build a Secure Python MCP Server with FastMCP

You can build a clean, production-ready MCP server in Python using the official mcp SDK and its FastMCP helper.

Step 1: Install the Official MCP SDK

Create a virtual environment and install the mcp package (pip install "mcp[cli]"). Avoid printing anything to standard output (stdout) in stdio servers, because stdout is reserved strictly for JSON-RPC protocol messages.

Step 2: Define Typed Tools with Input Validation

Write a server that restricts file reads to a single safe directory. Notice how Path.resolve() blocks ../ path traversal attacks before opening any file.

import logging
from pathlib import Path
from mcp.server.fastmcp import FastMCP

# Log only to stderr so stdout stays clean for JSON-RPC
logging.basicConfig(level=logging.INFO)

BASE_DIR = Path("/srv/safe-docs").resolve()
mcp = FastMCP("safe-docs-reader")


@mcp.tool()
def read_doc(relative_path: str) -> str:
    """Read a UTF-8 markdown or text file inside the allowed docs folder."""
    target = (BASE_DIR / relative_path).resolve()
    if not target.is_relative_to(BASE_DIR) or not target.is_file():
        raise ValueError("Access denied: invalid or outside allowed directory.")
    return target.read_text(encoding="utf-8")[:20000]


if __name__ == "__main__":
    mcp.run(transport="stdio")

Step 3: Register the Server in Your MCP Client

Add the server command to your client’s MCP configuration file (such as mcp.json or claude_desktop_config.json):

{
  "mcpServers": {
    "safe-docs-reader": {
      "command": "python",
      "args": ["/absolute/path/to/server.py"]
    }
  }
}

Restart your client and ask it to list or read a file inside /srv/safe-docs. Any attempt to read /etc/passwd or ../../secrets.env will be rejected cleanly.

Note: Always cap returned text length (such as [:20000] characters) in document-reading tools so a single huge log file does not overflow the AI model’s context window.

Security Checklist for Production MCP Servers

Connecting AI models to live tools introduces new risks, especially indirect prompt injection from untrusted web pages or tickets. Apply these four safeguards to every server you ship:

  • Enforce Least Privilege: Give database tools a read-only SQL user instead of admin credentials, and never expose raw eval() or unrestricted shell execution tools.
  • Validate Every Path and URL: Always resolve file paths against an allowlisted base directory, and block internal network IPs (127.0.0.1, 169.254.169.254) in HTTP fetch tools to prevent SSRF.
  • Require Human Approval for Writes: Mark destructive or state-changing tools clearly and keep client confirmation prompts enabled for POST, DELETE, or email-sending actions.
  • Authenticate Remote Transports: When deploying over Streamable HTTP, require OAuth 2.1 or scoped Bearer tokens and bind local dev servers strictly to 127.0.0.1 instead of 0.0.0.0.

Frequently Asked Questions

What is the difference between MCP and standard OpenAI or Anthropic function calling?

Function calling is a model-specific API feature where you send tool schemas in every prompt request. MCP is an open client-server protocol that standardizes how tools, resources, and prompts are hosted, discovered, and shared across any AI app.

Why did my stdio MCP server crash with a JSON parse error?

In almost every case, a print() statement or third-party library wrote plain text to stdout. On stdio servers, stdout must carry only JSON-RPC frames, so always route logs to stderr.

Should I use stdio or Streamable HTTP for my MCP server?

Use stdio when the server runs locally on the developer’s machine (such as reading local Git repos or files). Use Streamable HTTP when hosting a shared server in the cloud for multiple team members.

Can an MCP server connect to existing REST APIs?

Yes. Wrapping an internal REST API inside an MCP server is one of the most common patterns, because it lets you curate safe, simplified tool inputs instead of exposing dozens of raw endpoints to the model.

You May Also Like

We hope this guide helped you understand how to build and secure MCP servers. Written by the TeckScaler Editorial Engineering Team. Explore more developer guides and free tools:

Primary Sources and References

Leave a Reply

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