Building AI Systems
October 15, 2026•10 min read

The Model Context Protocol (MCP) Deep Dive: Building Production MCP Servers in TypeScript & Python

A complete architectural guide to building, testing, and securing stdio and SSE-based MCP servers for Claude Desktop, Cursor, and enterprise AI hosts.

AIStoreHub
AIStoreHub
Open AI Registry & Developer Platform
Executive Blueprint & Summary (BLUF)

The Model Context Protocol (MCP) by Anthropic standardizes how frontier LLMs interface with local and remote data. By separating transport layers (stdio for local desktop clients, SSE/HTTP for remote microservices) from tool definitions and resource schemas, MCP allows developers to write an integration once and execute it seamlessly across Claude Desktop, Cursor, Windsurf, and enterprise orchestrators.

1-Click Install via AIStoreHub CLI
$ aihub mcp install community/postgres-mcp --client cursor
Requires: pip install aistorehubCLI Docs

What is Model Context Protocol & Why It Replaced Custom APIs

Before the Model Context Protocol (MCP), connecting an LLM to external data was chaotic. Every developer wrote custom JSON function definitions, built unique REST wrappers, and spent hours copying auth headers into idiosyncratic configuration files for each AI client.

MCP solves this the same way the Language Server Protocol (LSP) revolutionized IDEs: by creating a single, open standard for how AI clients query and invoke external tools, context resources, and prompt templates.

code
┌────────────────────────────────────────────────────────┐
│                   AI HOST CLIENTS                      │
│      Claude Desktop  •  Cursor  •  AIStoreHub CLI      │
└──────────────────────────┬─────────────────────────────┘
                           │  JSON-RPC 2.0 (MCP Protocol)
                           ▼
┌────────────────────────────────────────────────────────┐
│                  MCP SERVER BOUNDARY                   │
│  • Resources: Read-only files, schemas, database docs  │
│  • Tools: Executable functions with JSON Schema        │
│  • Prompts: Pre-engineered slash command templates     │
└──────────────────────────┬─────────────────────────────┘
                           │
                           ▼
           Databases • Git Repos • Cloud APIs

With MCP, an integration written once works universally across any MCP-compliant host.


Architecture Breakdown: Stdio vs. SSE (Server-Sent Events)

MCP supports two primary transport mechanisms. Choosing the correct transport depends on your deployment target:

TransportCommunicationProcess ModelBest Used For
stdio (Standard I/O)Subprocess stdin / stdoutChild process spawned by hostLocal desktop tools, CLI utilities, local SQLite databases
SSE (Server-Sent Events)HTTP POST + persistent SSE streamRemote daemon or cloud serviceCloud microservices, multi-user platforms, hosted SaaS tools

For local developer workflows, stdio requires zero networking configuration. For cloud monetization on AIStoreHub, SSE allows you to host the server behind a secure proxy, authenticate buyers via bearer tokens, and meter usage per invocation.


Step-by-Step: Building an MCP Server in TypeScript

Let's build a production-grade MCP server that inspects Git repositories and formats branch status for LLMs:

typescript
// src/git-inspector.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  ListToolsRequestSchema,
  CallToolRequestSchema,
  ErrorCode,
  McpError,
} from "@modelcontextprotocol/sdk/types.js";
import { execFile } from "child_process";
import { promisify } from "util";

const exec = promisify(execFile);

const server = new Server(
  {
    name: "aistorehub/git-inspector-mcp",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 1. Declare available tools with JSON Schema validation
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "get_git_status",
      description: "Returns branch status, staged changes, and recent commit diffs for a local repository",
      inputSchema: {
        type: "object",
        properties: {
          repoPath: {
            type: "string",
            description: "Absolute filesystem path to the repository directory",
          },
        },
        required: ["repoPath"],
      },
    },
  ],
}));

// 2. Implement execution handler with safety boundaries
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "get_git_status") {
    const repoPath = String(request.params.arguments?.repoPath);

    // Prevent path traversal outside allowed boundaries
    if (repoPath.includes("..") || repoPath.startsWith("/etc")) {
      throw new McpError(ErrorCode.InvalidParams, "Access denied: Path out of bounds.");
    }

    try {
      const { stdout } = await exec("git", ["status", "--short"], { cwd: repoPath });
      return {
        content: [
          {
            type: "text",
            text: stdout.trim() || "Working tree clean. No uncommitted changes.",
          },
        ],
      };
    } catch (err: any) {
      throw new McpError(ErrorCode.InternalError, `Git execution failed: ${err.message}`);
    }
  }

  throw new McpError(ErrorCode.MethodNotFound, "Unknown tool requested");
});

// 3. Connect to stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Git Inspector MCP Server running on stdio");

Step-by-Step: Building an MCP Server with Python FastMCP

For Python developers, the official FastMCP framework offers an expressive, decorator-driven developer experience:

python
# server.py - FastMCP Server Example
from mcp.server.fastmcp import FastMCP
import httpx

mcp = FastMCP("Weather & Air Quality Inspector")

@mcp.tool()
async def get_air_quality(latitude: float, longitude: float) -> str:
    """Fetch real-time air quality index and particulate data for given coordinates."""
    url = f"https://air-quality-api.open-meteo.com/v1/air-quality?latitude={latitude}&longitude={longitude}&current=european_aqi,pm2_5"
    async with httpx.AsyncClient(timeout=10.0) as client:
        res = await client.get(url)
        res.raise_for_status()
        data = res.json()
        aqi = data.get("current", {}).get("european_aqi", "Unknown")
        return f"Air Quality Index (AQI): {aqi} | PM2.5: {data.get('current', {}).get('pm2_5')} ug/m3"

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

Securing Production MCP: Auth, Scopes, and Rate Limiting

When exposing an MCP server over the network (SSE) or packaging it for community consumption:

  1. Enforce Read-Only Defaults: Unless a tool explicitly requires write operations, configure database connection pools with READ ONLY transaction semantics.
  2. Sanitize Shell Arguments: Always use execFile or array-based argument vectors. Never execute raw interpolated strings through child_process.exec or os.system.
  3. Bearer Token Authentication: When running in SSE mode, validate the Authorization: Bearer <key> header on every incoming HTTP POST before delegating to the tool runner.
  4. Per-Client Rate Limits: Prevent denial-of-service token floods by limiting client requests to a maximum of 60 tool calls per minute.

1-Click Client Configuration for Claude Desktop & Cursor

To connect your MCP server to Claude Desktop, add the configuration to claude_desktop_config.json:

json
{
  "mcpServers": {
    "git-inspector": {
      "command": "node",
      "args": ["/Users/developer/mcp-servers/dist/git-inspector.js"]
    },
    "air-quality": {
      "command": "python3",
      "args": ["/Users/developer/mcp-servers/server.py"]
    }
  }
}

For Cursor or Windsurf, navigate to Settings → Features → Model Context Protocol and paste the same JSON snippet or use the AIStoreHub 1-Click Client Config generator.


Packaging and Distributing on AIStoreHub

Package your MCP server for distribution with an AIStoreHub manifest:

yaml
# aistorehub.json
{
  "name": "Git Repository Inspector MCP",
  "slug": "git-inspector-mcp",
  "type": "mcp_server",
  "version": "1.0.0",
  "description": "Standardized Model Context Protocol server exposing repository branch status, staged diffs, and commit history to Claude Desktop and Cursor.",
  "transport": "stdio",
  "runtime": "node22"
}

Run aihub publish from the command line, and your MCP server is immediately indexed on AIStoreHub's marketplace storefront.

Interactive Registry Preview

Featured Systems in the AIStoreHub Registry

Verified packages installable directly via terminal into Cursor, Claude Desktop, and Python runtimes.

Browse all 143 systems
MCP Server
PostgreSQL & SQLite Inspector

Inspect schema, explain queries, and generate zero-downtime migrations in Cursor.

Autonomous Agent
Harvey 24/7 AI Sales Agent

Autonomous prospecting, cold emails, and meeting booking with zero API token bills.

Claude Skill
Day Trader Skills: 11 Claude Skills

Scan charts, calculate risk/reward brackets, and backtest setups via Claude Code.

Frequently Asked Questions

Essential clarifications for developers and engineering teams building and operating AI systems.

An MCP Tool is an executable function that performs actions (like running a query, creating a file, or calling an API) and can change external state. An MCP Resource is a read-only stream of context (like documentation, system logs, or database schemas) that the model can inspect passively.
AIStoreHub
Written by AIStoreHub
Open AI Registry & Developer Platform

AIStoreHub is the open registry and 1-click CLI for discovering, running, and installing production-grade AI systems, Model Context Protocol (MCP) servers, and autonomous agents.

Topics:#Model Context Protocol#MCP#TypeScript#Python#Tool Integration#Claude Desktop

Related Engineering Guides

Continue learning how to build, monetize, and operate AI systems effectively.