TaskoTools
AI & Automation Tutorials

How to Build a Custom Model Context Protocol (MCP) Server in TypeScript & Python

The Model Context Protocol (MCP) has become the universal USB-C port for AI agents. Learn how to build, test, and secure a production MCP server from scratch.

TaskoTools Engineering & Editorial TeamPublished Updated 9 min read
3D isometric illustration of an AI hub connecting via modular MCP protocol connectors to databases and APIs

Why MCP Exists: Solving the N × M Integration Problem

Before MCP, connecting N AI applications (Cursor, VS Code, Claude Desktop, custom internal agents) to M data sources (PostgreSQL, GitHub, Slack, Jira, local files) required writing N × M bespoke plugins. Each integration had its own authentication flow, tool-calling schema, and error format.

The Model Context Protocol replaces fragmented glue code with a single client-server specification built on JSON-RPC 2.0. You write an MCP server once for your database or internal API, and any MCP-compatible AI host can discover and invoke its capabilities immediately.

  • MCP Host: The user-facing AI application (e.g., Cursor, Claude Code, Antigravity, or a custom agent runtime).
  • MCP Client: The protocol connector inside the host that maintains a 1:1 stateful session with a server.
  • MCP Server: A lightweight process exposing Tools, Resources, and Prompts over stdio or Streamable HTTP.

Understanding the Three Core MCP Primitives

Designing a clean MCP server starts with choosing the right primitive for each capability. Mixing read-only context into imperative tools bloats token usage and increases accidental side effects.

  • Tools (Model-Controlled): Executable functions with JSON Schema inputs (e.g., `query_analytics`, `create_jira_issue`). The LLM decides when to call them.
  • Resources (Application-Controlled): URI-addressed read-only context such as `db://schema/users` or `logs://app/latest`. The host attaches them explicitly or via @-mentions.
  • Prompts (User-Controlled): Reusable parameterized workflow templates (slash commands) like `/review-migration` or `/debug-500`.

Step-by-Step: Building a TypeScript MCP Server

Initialize a Node.js project, install `@modelcontextprotocol/sdk` and `zod`, and register a typed tool. Never write `console.log()` to stdout in a `stdio` server—stdout is reserved exclusively for JSON-RPC frames; use `console.error()` for diagnostics.

typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "metrics-mcp",
  version: "1.0.0",
});

server.tool(
  "get_service_latency",
  "Fetch p95 latency (ms) and error rate for a microservice",
  {
    service: z.string().min(2).describe("Service name, e.g. auth-api"),
    windowMinutes: z.number().int().min(5).max(1440).default(60),
  },
  async ({ service, windowMinutes }) => {
    // Replace with your real Prometheus / Datadog / SQL query
    const metrics = {
      service,
      windowMinutes,
      p95LatencyMs: 42.8,
      errorRatePercent: 0.03,
    };

    return {
      content: [{ type: "text", text: JSON.stringify(metrics, null, 2) }],
    };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);

Building the Equivalent Server in Python with FastMCP

If your AI stack lives in Python, the official `mcp` package includes `FastMCP`, which automatically generates JSON Schemas from Python type hints and docstrings.

python
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("metrics-mcp")

@mcp.tool()
def get_service_latency(service: str, window_minutes: int = 60) -> dict:
    """Fetch p95 latency (ms) and error rate for a microservice."""
    return {
        "service": service,
        "window_minutes": window_minutes,
        "p95_latency_ms": 42.8,
        "error_rate_percent": 0.03,
    }

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

Security & Production Hardening Checklist

Because MCP servers give LLMs direct reach into real systems, treat every tool parameter as untrusted input. Enforce strict allowlists, read-only database roles by default, and human confirmation for destructive mutations.

  • Use parameterized SQL queries—never interpolate LLM strings into raw SQL or shell commands.
  • Restrict filesystem MCP servers to explicit workspace root directories and reject `..` path traversal.
  • Return actionable error messages (`isError: true`) so the agent can self-correct invalid arguments without hallucinating.
  • For remote multi-user deployments, use Streamable HTTP transport behind OAuth 2.1 bearer tokens instead of static shared API keys.

Frequently Asked Questions

What is the difference between stdio and Streamable HTTP in MCP?

stdio runs the MCP server as a local child process communicating over standard input/output—ideal for local IDE tools. Streamable HTTP runs the server over HTTPS with Server-Sent Events (SSE) for remote, cloud-hosted, multi-user integrations.

Why does console.log break a local MCP server?

In stdio transport, the host parses every line on stdout as a JSON-RPC 2.0 message. Any plain-text console.log corrupts the protocol stream. Always write logs to stderr (console.error) or a dedicated log file.

How many tools should a single MCP server expose?

Keep each server focused on 5 to 15 cohesive tools. Exposing 50+ overlapping tools inflates the model's context window and degrades tool-selection accuracy.

Related Guides