Complete 11-phase guide for building production-ready MCP (Model Context Protocol) servers with semantic layer integration. Covers foundation to deployment, including agent-centric design, tool development, testing, error handling, performance optimization, monitoring, security, governance, and sema
npx playbooks add skill jgtolentino/insightpulse-odoo --skill mcp-complete-guide
A Comprehensive Guide to Building Production-Ready MCP Servers
From Foundation to Semantic Layer Integration
---
---
Before writing any code, invest time in deep research and strategic planning. This phase sets the foundation for a high-quality MCP server.
Build for Workflows, Not Just API Endpoints:
schedule_event that both checks availability and creates event)Optimize for Limited Context:
Design Actionable Error Messages:
Follow Natural Task Subdivisions:
Load the complete MCP specification:
# Fetch the latest MCP protocol documentation
https://modelcontextprotocol.io/llms-full.txt
This comprehensive document contains the complete MCP specification and guidelines.
For Python implementations:
https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.mdFor Node/TypeScript implementations:
https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.mdTo integrate a service, read through ALL available API documentation:
Based on your research, create a detailed plan:
Tool Selection:
Shared Utilities:
Input/Output Design:
Error Handling Strategy:
---
With a comprehensive plan in place, begin systematic implementation following language-specific best practices.
project/
├── src/
│ ├── __init__.py
│ ├── server.py # Main MCP server
│ ├── tools.py # Tool implementations
│ ├── utils.py # Shared utilities
│ └── models.py # Pydantic models
├── tests/
│ ├── test_tools.py
│ └── test_utils.py
├── requirements.txt
├── pyproject.toml
└── README.md
project/
├── src/
│ ├── index.ts # Main MCP server
│ ├── tools/ # Tool implementations
│ ├── utils/ # Shared utilities
│ └── types.ts # Type definitions
├── tests/
├── package.json
├── tsconfig.json
└── README.md
from mcp import FastMCP
from pydantic import BaseModel, Field
import httpx
import asyncio
# Initialize server
mcp = FastMCP("your-service-name")
# Module-level constants
CHARACTER_LIMIT = 25000
API_BASE_URL = "https://api.example.com"
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
const server = new Server({
name: "your-service-name",
version: "1.0.0"
}, {
capabilities: {
tools: {}
}
});
Create shared utilities before implementing tools:
async def make_api_request(
endpoint: str,
method: str = "GET",
params: dict | None = None,
data: dict | None = None
) -> dict:
"""Make authenticated API request with error handling."""
async with httpx.AsyncClient() as client:
response = await client.request(
method=method,
url=f"{API_BASE_URL}/{endpoint}",
params=params,
json=data,
headers={"Authorization": f"Bearer {API_TOKEN}"},
timeout=30.0
)
response.raise_for_status()
return response.json()
def format_response(data: dict, format_type: str = "json") -> str:
"""Format response as JSON or Markdown."""
if format_type == "json":
return json.dumps(data, indent=2)
else:
# Convert to markdown format
return convert_to_markdown(data)
def truncate_content(content: str, max_chars: int = CHARACTER_LIMIT) -> str:
"""Truncate content with ellipsis if exceeds limit."""
if len(content) <= max_chars:
return content
return content[:max_chars] + "\n\n[Content truncated...]"
async def paginate_results(
endpoint: str,
max_results: int = 100,
page_size: int = 50
) -> list:
"""Fetch paginated results up to max_results."""
results = []
page = 1
while len(results) < max_results:
data = await make_api_request(
endpoint,
params={"page": page, "per_page": page_size}
)
if not data.get("items"):
break
results.extend(data["items"])
if not data.get("has_more"):
break
page += 1
return results[:max_results]
---
Implement tools systematically, following consistent patterns and best practices.
from pydantic import BaseModel, Field
from typing import Literal
class SearchInput(BaseModel):
"""Input schema for search tool."""
query: str = Field(
description="Search query string",
min_length=1,
max_length=200
)
filter_type: Literal["all", "active", "archived"] = Field(
default="active",
description="Filter results by status"
)
max_results: int = Field(
default=50,
ge=1,
le=100,
description="Maximum number of results to return"
)
response_format: Literal["json", "markdown"] = Field(
default="markdown",
description="Format for response data"
)
@mcp.tool()
async def search_items(
query: str,
filter_type: str = "active",
max_results: int = 50,
response_format: str = "markdown"
) -> str:
"""
Search for items matching the query.
This tool searches across all items in the system and returns
matching results with their key attributes.
Args:
query: Search query string
filter_type: Filter by status (all/active/archived)
max_results: Maximum number of results (1-100)
response_format: Response format (json/markdown)
Returns:
Formatted search results with item details
Example:
>>> search_items("project alpha", filter_type="active", max_results=10)
Returns active items matching "project alpha"
Hints:
readOnly: true
destructive: false
idempotent: true
openWorld: true
"""
try:
# Validate and prepare request
params = {
"q": query,
"status": filter_type,
"limit": min(max_results, 100)
}
# Fetch results
results = await make_api_request("search", params=params)
# Format response
formatted = format_response(results, response_format)
# Apply character limit
return truncate_content(formatted)
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
return "No items found matching your query. Try broader search terms."
elif e.response.status_code == 401:
return "Authentication failed. Please check API credentials."
else:
return f"Search failed: {str(e)}. Please try again."
except Exception as e:
return f"Unexpected error during search: {str(e)}"
For each tool, ensure:
@mcp.tool()
async def list_resources(
limit: int = 50,
offset: int = 0,
response_format: str = "markdown"
) -> str:
"""
List all available resources.
Hints:
readOnly: true
destructive: false
idempotent: true
"""
results = await paginate_results("resources", max_results=limit)
return format_response(results, response_format)
@mcp.tool()
async def create_resource(
name: str,
description: str,
metadata: dict | None = None
) -> str:
"""
Create a new resource.
Hints:
readOnly: false
destructive: true
idempotent: false
"""
data = {
"name": name,
"description": description,
"metadata": metadata or {}
}
result = await make_api_request("resources", method="POST", data=data)
return f"✅ Resource created successfully: {result['id']}"
---
Comprehensive testing ensures your MCP server works reliably in production scenarios.
import pytest
from unittest.mock import AsyncMock, patch
from your_server import search_items, make_api_request
@pytest.mark.asyncio
async def test_search_items_success():
"""Test successful search returns formatted results."""
mock_response = {
"items": [
{"id": "1", "name": "Item 1"},
{"id": "2", "name": "Item 2"}
]
}
with patch('your_server.make_api_request', return_value=mock_response):
result = await search_items("test query")
assert "Item 1" in result
assert "Item 2" in result
assert len(result) < CHARACTER_LIMIT
@pytest.mark.asyncio
async def test_search_items_not_found():
"""Test 404 returns helpful error message."""
with patch('your_server.make_api_request', side_effect=httpx.HTTPStatusError(
"Not Found", request=None, response=AsyncMock(status_code=404)
)):
result = await search_items("nonexistent")
assert "No items found" in result
assert "broader search terms" in result
Create 10 realistic evaluation questions to test agent effectiveness:
<evaluation>
<qa_pair>
<question>What are the top 5 most active projects in the last 30 days, and who are their lead contributors?</question>
<answer>Project Alpha (John Doe), Project Beta (Jane Smith), Project Gamma (Bob Johnson), Project Delta (Alice Williams), Project Epsilon (Charlie Brown)</answer>
</qa_pair>
<!-- More qa_pairs... -->
</evaluation>
Each question must be:
---
Robust error handling ensures your MCP server handles failures gracefully and provides actionable feedback.
async def handle_network_error(error: Exception) -> str:
"""Handle network-related errors with retries."""
if isinstance(error, httpx.TimeoutException):
return "Request timed out. The service may be slow - try reducing max_results or try again later."
elif isinstance(error, httpx.ConnectError):
return "Cannot connect to service. Please check your network connection and try again."
else:
return f"Network error: {str(error)}. Please try again."
import time
from functools import wraps
def rate_limit_handler(max_retries: int = 3):
"""Decorator to handle rate limiting with exponential backoff."""
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
return await func(*args, **kwargs)
except httpx.HTTPStatusError as e:
if e.response.status_code == 429:
if attempt < max_retries - 1:
wait_time = 2 ** attempt # Exponential backoff
await asyncio.sleep(wait_time)
continue
else:
return "Rate limit exceeded. Please wait a moment and try again."
raise
return await func(*args, **kwargs)
return wrapper
return decorator
@mcp.tool()
@rate_limit_handler(max_retries=3)
async def rate_limited_search(query: str) -> str:
"""Search with automatic rate limit handling."""
return await search_items(query)
Prevent cascading failures:
class CircuitBreaker:
"""Circuit breaker to prevent cascading failures."""
def __init__(self, failure_threshold: int = 5, timeout: int = 60):
self.failure_count = 0
self.failure_threshold = failure_threshold
self.timeout = timeout
self.last_failure_time = None
self.state = "closed" # closed, open, half_open
def call(self, func):
"""Execute function with circuit breaker protection."""
async def wrapper(*args, **kwargs):
if self.state == "open":
if time.time() - self.last_failure_time > self.timeout:
self.state = "half_open"
else:
return "Service temporarily unavailable due to repeated failures. Please try again later."
try:
result = await func(*args, **kwargs)
if self.state == "half_open":
self.state = "closed"
self.failure_count = 0
return result
except Exception as e:
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = "open"
raise
return wrapper
---
Optimize your MCP server for speed, efficiency, and scalability.
from functools import lru_cache
from datetime import datetime, timedelta
class TimedCache:
"""Simple timed cache for API responses."""
def __init__(self, ttl_seconds: int = 300):
self.cache = {}
self.ttl = timedelta(seconds=ttl_seconds)
def get(self, key: str) -> dict | None:
"""Get cached value if not expired."""
if key in self.cache:
value, timestamp = self.cache[key]
if datetime.now() - timestamp < self.ttl:
return value
else:
del self.cache[key]
return None
def set(self, key: str, value: dict):
"""Cache value with timestamp."""
self.cache[key] = (value, datetime.now())
# Global cache instance
api_cache = TimedCache(ttl_seconds=300)
@mcp.tool()
async def cached_search(query: str) -> str:
"""Search with caching for repeated queries."""
cache_key = f"search:{query}"
# Check cache
cached_result = api_cache.get(cache_key)
if cached_result:
return format_response(cached_result, "markdown") + "\n\n📦 (Cached result)"
# Fetch fresh data
result = await make_api_request("search", params={"q": query})
# Cache result
api_cache.set(cache_key, result)
return format_response(result, "markdown")
Process multiple items efficiently:
@mcp.tool()
async def batch_fetch_resources(
resource_ids: list[str],
max_concurrent: int = 10
) -> str:
"""Fetch multiple resources concurrently."""
async def fetch_one(resource_id: str) -> dict:
"""Fetch single resource."""
try:
return await make_api_request(f"resources/{resource_id}")
except Exception as e:
return {"id": resource_id, "error": str(e)}
# Limit concurrency to avoid overwhelming API
semaphore = asyncio.Semaphore(max_concurrent)
async def fetch_with_limit(resource_id: str):
async with semaphore:
return await fetch_one(resource_id)
# Execute concurrent requests
results = await asyncio.gather(
*[fetch_with_limit(rid) for rid in resource_iWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.