Model Context Protocol (MCP) Implementation in AI Engineering: From Stdlib to Production

The Model Context Protocol (MCP) is a JSON-RPC-based wire format that standardizes how large language models communicate with external tools, resources, and prompts through a unified schema with built-in capability negotiation and OAuth 2.1 security.

The Model Context Protocol (MCP) has emerged as the de-facto standard for model-to-tool interoperability in modern AI systems. According to the rohitg00/ai-engineering-from-scratch curriculum, MCP provides a structured approach to building tool-using agents, progressing from low-level Python stdlib implementations to enterprise-grade deployments with governance registries and policy enforcement.

Core Architectural Concepts of MCP

MCP defines three first-class primitives—tools, resources, and prompts—that expose functionality to LLMs through a standardized JSON-Schema contract. As outlined in the repository's metadata configuration, these elements are described with strict typing that includes input parameters, output formats, and required capability scopes.

Unified Schema and First-Class Primitives

Every MCP server declares its capabilities via a structured contract. The schema includes the tool name, input parameters, output types, and required capability scopes. This contract enables clients to validate requests before invocation and automatically generate user interfaces for tool interaction.

Capability Negotiation and Discovery

Before executing tools, clients query the server's .well-known/mcp-capabilities endpoint to retrieve a manifest of available transports and tools. This discovery flow allows agents to dynamically adapt to server capabilities, negotiating whether to use stdio, Server-Sent Events (SSE), or the modern StreamableHTTP transport.

Transport Bindings

While early MCP implementations relied on stdio or SSE, the 2026 specification revision favors StreamableHTTP—a stateless, streaming-friendly HTTP endpoint that simplifies load balancing and horizontal scaling. The curriculum emphasizes this transport for production deployments behind reverse proxies.

Security and Scope Enforcement

MCP implements OAuth 2.1 for authentication and fine-grained RBAC. Each tool call includes scope tokens (e.g., approved:by:human for destructive operations). Production servers integrate Open Policy Agent (OPA) to enforce governance rules before tool execution, ensuring compliance with organizational policies.

MCP Implementation in the Curriculum

The rohitg00/ai-engineering-from-scratch repository teaches MCP implementation through a three-phase progression, from fundamental protocol mechanics to enterprise architecture.

Phase 1: Pure Python Stdlib Server (Lesson 14)

The first implementation in phases/11-llm-engineering/14-model-context-protocol/code/main.py demonstrates the protocol's foundations using only the Python standard library. This baseline server implements a JSON-RPC loop over stdio, manually handling request parsing, tool dispatch, and schema validation.


# phases/11-llm-engineering/14-model-context-protocol/code/main.py

import json
import sys

def echo_tool(params):
    """A trivial tool that returns its input."""
    return {"result": params["message"]}

TOOL_REGISTRY = {
    "echo": {
        "description": "Echoes back a message",
        "parameters": {
            "type": "object",
            "properties": {"message": {"type": "string"}},
            "required": ["message"]
        },
        "handler": echo_tool,
    },
}

def handle_request(request):
    method = request["method"]
    if method not in TOOL_REGISTRY:
        raise ValueError(f"Unknown tool: {method}")
    return TOOL_REGISTRY[method]["handler"](request["params"])

# Simple stdio JSON-RPC loop

for line in sys.stdin:
    req = json.loads(line)
    resp = {"jsonrpc": "2.0", "id": req["id"], "result": handle_request(req)}
    print(json.dumps(resp))
    sys.stdout.flush()

This explicit implementation illustrates how the handle_request function dispatches to registered tools through the TOOL_REGISTRY, validating that the requested method exists before invoking the handler.

Phase 2: FastMCP SDK Abstraction

The curriculum graduates to FastMCP, a decorator-based SDK that automates protocol boilerplate. As shown in the lesson documentation at phases/11-llm-engineering/14-model-context-protocol/docs/en.md, the FastMCP implementation reduces the server to under 80 lines while automatically generating JSON-Schemas and handling transport negotiation.


# phases/11-llm-engineering/14-model-context-protocol/code/main.py

from fastmcp import FastMCP

app = FastMCP("demo")

@app.tool(name="echo", description="Echo a message")
def echo_tool(message: str):
    return {"result": message}

if __name__ == "__main__":
    app.run()       # defaults to stdio; can be switched to StreamableHTTP via CLI args

The @app.tool decorator registers the function with the FastMCP registry, introspecting type hints to build the parameter schema. Invoking the server with --transport http exposes a StreamableHTTP endpoint compatible with production load balancers.

Phase 3: Production Capstone with Governance (Capstone 13)

The final implementation in phases/19-capstone-projects/13-mcp-server-with-registry/docs/en.md demonstrates enterprise deployment patterns. This capstone extends the FastMCP server with:

  • Registry Integration: Aggregating capability manifests from multiple servers into a central discovery service
  • OAuth 2.1 Enforcement: Validating bearer tokens and scopes before tool execution
  • OPA Policy Gates: Blocking destructive operations without explicit human approval scopes
  • Load Balancing: Deploying behind proxies with StreamableHTTP health checks

# Register the server with the central registry

curl -X POST https://registry.example.com/.well-known/mcp-capabilities \
     -H "Content-Type: application/json" \
     -d @.well-known/mcp-capabilities.json

Client Integration Patterns

Clients communicate with MCP servers through JSON-RPC POST requests, supplying OAuth tokens for authorization. The following pattern from the curriculum demonstrates calling the echo tool:

import requests, json

def call_mcp(tool, params, token):
    payload = {"jsonrpc": "2.0", "id": 1, "method": tool, "params": params}
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    resp = requests.post("https://mcp.example.com/v1/tools", json=payload, headers=headers)
    return resp.json()["result"]

# Example usage:

result = call_mcp("echo", {"message": "Hello, MCP!"}, token="eyJhbGciOi...")
print(result)   # → {"result": "Hello, MCP!"}

The call_mcp function constructs the JSON-RPC envelope, attaches the authorization header, and extracts the result from the response, abstracting the wire protocol from business logic.

Summary

  • The Model Context Protocol standardizes LLM tool-use through JSON-RPC messaging and JSON-Schema contracts for tools, resources, and prompts.
  • FastMCP reduces implementation complexity from ~180 lines of stdlib code to under 80 lines through decorator-based registration and automatic schema generation.
  • Production deployments use StreamableHTTP transport, OAuth 2.1 scopes, and OPA policies to secure tool execution behind registries.
  • The rohitg00/ai-engineering-from-scratch curriculum provides a complete progression from protocol fundamentals to enterprise architecture in phases/11-llm-engineering/14-model-context-protocol/ and phases/19-capstone-projects/13-mcp-server-with-registry/.

Frequently Asked Questions

What is the Model Context Protocol (MCP) used for?

MCP provides a standardized wire format for AI agents to discover and invoke external tools. It replaces ad-hoc API integrations with a unified protocol that supports capability negotiation, type-safe parameters through JSON-Schema, and secure OAuth 2.1 authentication, enabling LLMs to interact with databases, file systems, and SaaS platforms through a consistent interface.

How does FastMCP simplify MCP implementation?

FastMCP automates the boilerplate required for JSON-RPC message handling, transport management, and schema generation. By using the @app.tool decorator, developers register Python functions that FastMCP exposes as MCP tools, automatically introspecting type hints to build valid JSON-Schema definitions and supporting both stdio and StreamableHTTP transports without manual socket management.

What security mechanisms does MCP support for production environments?

Production MCP servers implement OAuth 2.1 with fine-grained scopes attached to each tool invocation. Destructive operations require explicit approved:by:human scopes. Additionally, servers integrate Open Policy Agent (OPA) to evaluate governance rules before execution, while registries audit all capability discoveries and tool calls for compliance monitoring.

How do clients discover available tools on an MCP server?

Clients initiate a capability negotiation by querying the server's .well-known/mcp-capabilities endpoint, which returns a manifest listing available tools, their schemas, and supported transports. This discovery mechanism allows agents to dynamically populate their tool palettes and validate user inputs against the server's JSON-Schema contracts before making requests.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →