Understanding the Model Context Protocol (MCP) โ
The Model Context Protocol (MCP) is a revolutionary standard that enables AI models to securely access and interact with external data sources, tools, and services. This guide will help you understand MCP's core concepts, architecture, and how it transforms AI application development.
๐ฏ What is MCP? โ
MCP is an open standard that provides:
- ๐ Universal connectivity between AI models and external systems
- ๐ก๏ธ Secure, controlled access to tools and data
- ๐๏ธ Standardized architecture for AI-powered applications
- ๐ Bidirectional communication between clients and servers
- ๐ Scalable integration patterns for complex systems
Think of MCP as the "HTTP for AI" - a protocol that makes it easy for AI models to interact with any system in a standardized way.
๐๏ธ Core Architecture โ
The MCP Ecosystem โ
โโโโโโโโโโโโโโโโโโโ MCP Protocol โโโโโโโโโโโโโโโโโโโ
โ โโโโโโโโโโโโโโโโโโโโโบโ โ
โ MCP Client โ โ MCP Server โ
โ โ โ โ
โ (AI Model/App) โ โ (Tools/Data/AI) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Claude AI โ โ File System โ
โ ChatGPT โ โ Database โ
โ Custom Apps โ โ APIs โ
โ Agents โ โ Services โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
Key Components โ
- MCP Client - Consumes capabilities (AI models, applications)
- MCP Server - Provides capabilities (tools, resources, prompts)
- Transport Layer - Communication mechanism (STDIO, HTTP, WebSocket)
- Protocol Messages - Standardized request/response format
๐ง Core Concepts โ
1. Tools โ
Tools are functions that AI models can call to perform actions.
// Example: Calculator tool
$server->tool(
'calculate',
'Perform mathematical calculations',
[
'type' => 'object',
'properties' => [
'expression' => ['type' => 'string']
]
],
function (array $args): array {
$result = eval("return {$args['expression']};");
return [
'content' => [
['type' => 'text', 'text' => "Result: {$result}"]
]
];
}
);
When to use Tools:
- Performing actions (send email, create file, API calls)
- Calculations or data processing
- External service integration
- System operations
2. Resources โ
Resources provide access to data that AI models can read.
// Example: File resource
$server->resource(
'project-readme',
'file:///project/README.md',
'text/markdown',
function (): array {
return [
'contents' => [[
'uri' => 'file:///project/README.md',
'mimeType' => 'text/markdown',
'text' => file_get_contents(__DIR__ . '/README.md')
]]
];
}
);
When to use Resources:
- Static or dynamic data access
- File system content
- Database queries
- API responses
- Configuration data
3. Prompts โ
Prompts are reusable conversation templates that guide AI interactions.
// Example: Code review prompt
$server->prompt(
'code_review',
'Review code for best practices and issues',
[
[
'name' => 'code',
'description' => 'Code to review',
'required' => true
],
[
'name' => 'language',
'description' => 'Programming language',
'required' => true
]
],
function (array $args): array {
return [
'description' => 'Code Review Assistant',
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => "Please review this {$args['language']} code:\n\n{$args['code']}"
]
]
]
]
];
}
);
When to use Prompts:
- Standardized AI interactions
- Complex query templates
- Domain-specific guidance
- Workflow automation
4. Sampling โ
Sampling allows servers to request AI model completions.
// Example: Content generation
$completion = $client->requestSampling([
'messages' => [
[
'role' => 'user',
'content' => [
['type' => 'text', 'text' => 'Generate a summary of this data...']
]
]
],
'maxTokens' => 500
])->await();
When to use Sampling:
- Content generation
- Data analysis
- Decision making
- Text transformation
๐ Protocol Flow โ
Basic Request-Response Cycle โ
Client Discovery:
php// Client discovers server capabilities $capabilities = $client->initialize()->await(); $tools = $client->listTools()->await(); $resources = $client->listResources()->await(); $prompts = $client->listPrompts()->await();
Tool Execution:
php// Client calls a tool $result = $client->callTool('calculate', [ 'expression' => '2 + 2' ])->await();
Resource Access:
php// Client reads a resource $content = $client->readResource('file:///data/config.json')->await();
Prompt Usage:
php// Client gets a prompt template $prompt = $client->getPrompt('code_review', [ 'code' => $sourceCode, 'language' => 'php' ])->await();
Message Types โ
Requests โ
initialize
- Establish connection and capabilitiestools/list
- Get available toolstools/call
- Execute a toolresources/list
- Get available resourcesresources/read
- Read resource contentprompts/list
- Get available promptsprompts/get
- Get prompt templatesampling/createMessage
- Request AI completion
Responses โ
- Success responses with requested data
- Error responses with error codes and messages
- Progress notifications for long-running operations
Notifications โ
notifications/cancelled
- Operation cancellednotifications/progress
- Progress updatesnotifications/initialized
- Initialization complete
๐ Transport Layers โ
STDIO Transport โ
Best for: Command-line tools, desktop applications
// Server
$transport = new StdioServerTransport();
// Client
$transport = new StdioClientTransport(['php', 'server.php']);
Characteristics:
- Process-to-process communication
- Simple to implement and debug
- Perfect for local integrations
- Used by Claude Desktop
HTTP Transport โ
Best for: Web services, microservices, cloud deployments
// Server
$transport = new HttpServerTransport(['host' => 'localhost', 'port' => 8080]);
// Client
$transport = new HttpClientTransport('http://localhost:8080');
Characteristics:
- Network-based communication
- Scalable and distributed
- Standard web protocols
- Load balancing support
WebSocket Transport โ
Best for: Real-time applications, persistent connections, multiple concurrent clients
// Server with configuration
$transport = new WebSocketServerTransport([
'host' => '127.0.0.1',
'port' => 8080,
'maxConnections' => 100
]);
// Client
$transport = new WebSocketClientTransport('ws://localhost:8080');
Characteristics:
- Bidirectional real-time communication
- Low latency
- Persistent connections
- Perfect for interactive applications
๐ Security Model โ
Authentication โ
// OAuth 2.0 Bearer Token
$server->setAuthProvider(new OAuth2Provider([
'bearer_token' => 'your-secure-token'
]));
// Custom Authentication
$server->setAuthProvider(new CustomAuthProvider([
'validate' => function($credentials) {
return validateUser($credentials);
}
]));
Authorization โ
// Tool-level permissions
$server->tool(
'admin_tool',
'Administrative function',
$schema,
function($args, $context) {
if (!$context->user->hasRole('admin')) {
throw new McpError(ErrorCode::Forbidden, 'Admin access required');
}
// Tool logic here
}
);
Safe Execution โ
// Input validation
$server->tool(
'file_reader',
'Read file contents',
[
'type' => 'object',
'properties' => [
'path' => [
'type' => 'string',
'pattern' => '^[a-zA-Z0-9./\-_]+$' // Restrict allowed characters
]
]
],
function($args) {
// Validate path is safe
if (!isSafePath($args['path'])) {
throw new McpError(ErrorCode::InvalidParams, 'Invalid path');
}
return readFile($args['path']);
}
);
๐๏ธ Design Patterns โ
1. Service-Oriented Architecture โ
// Database Service Server
$dbServer = new McpServer(new Implementation('database-service'));
$dbServer->tool('query', 'Execute database query', $schema, $queryHandler);
$dbServer->tool('insert', 'Insert database record', $schema, $insertHandler);
// File Service Server
$fileServer = new McpServer(new Implementation('file-service'));
$fileServer->tool('read', 'Read file', $schema, $readHandler);
$fileServer->tool('write', 'Write file', $schema, $writeHandler);
// API Gateway Server
$apiServer = new McpServer(new Implementation('api-gateway'));
$apiServer->tool('proxy_request', 'Proxy API request', $schema, $proxyHandler);
2. Plugin Architecture โ
// Plugin Manager Server
class PluginServer extends McpServer {
private array $plugins = [];
public function loadPlugin(string $pluginClass): void {
$plugin = new $pluginClass();
// Register plugin tools
foreach ($plugin->getTools() as $tool) {
$this->tool($tool['name'], $tool['description'], $tool['schema'], $tool['handler']);
}
// Register plugin resources
foreach ($plugin->getResources() as $resource) {
$this->resource($resource['name'], $resource['uri'], $resource['mimeType'], $resource['handler']);
}
$this->plugins[] = $plugin;
}
}
๐ Real-World Use Cases โ
1. AI-Powered Development Tools โ
// Code Analysis Server
$server->tool('analyze_code', 'Analyze code quality', $schema, function($args) {
$ast = parseCode($args['code']);
$issues = analyzeAST($ast);
return formatIssues($issues);
});
$server->tool('suggest_improvements', 'Suggest code improvements', $schema, function($args) {
$suggestions = analyzeCodeQuality($args['code']);
return formatSuggestions($suggestions);
});
$server->resource('project-metrics', 'project://metrics', 'application/json', function() {
return ['contents' => [['uri' => 'project://metrics', 'mimeType' => 'application/json', 'text' => json_encode(getProjectMetrics())]]];
});
2. Business Process Automation โ
// CRM Integration Server
$server->tool('create_lead', 'Create new lead', $schema, function($args) {
return $this->crmApi->createLead($args);
});
$server->tool('send_follow_up', 'Send follow-up email', $schema, function($args) {
return $this->emailService->sendTemplate($args['template'], $args['contact']);
});
$server->resource('crm-pipeline', 'crm://pipeline', 'application/json', function() {
return ['contents' => [['uri' => 'crm://pipeline', 'mimeType' => 'application/json', 'text' => json_encode($this->crmApi->getPipelineData())]]];
});
3. Content Management โ
// Content Server
$server->tool('generate_content', 'Generate content', $schema, function($args) {
return $this->aiService->generateContent($args['prompt'], $args['style']);
});
$server->tool('optimize_seo', 'Optimize content for SEO', $schema, function($args) {
return $this->seoService->optimizeContent($args['content']);
});
$server->resource('cms-templates', 'cms://templates', 'application/json', function() {
return ['contents' => [['uri' => 'cms://templates', 'mimeType' => 'application/json', 'text' => json_encode($this->cms->getTemplates())]]];
});
๐ฎ Advanced Concepts โ
Error Handling โ
// Structured error responses
throw new McpError(
ErrorCode::InvalidParams, // Standard JSON-RPC error code
'Invalid parameters',
[
'parameter' => 'email',
'issue' => 'Invalid email format',
'expected' => 'user@domain.com'
]
);
Progress Reporting โ
// Long-running operations with progress
$server->tool('process_large_file', 'Process large file', $schema, function($args) {
$file = $args['file'];
$totalLines = countLines($file);
for ($i = 0; $i < $totalLines; $i++) {
processLine($file, $i);
// Report progress
if ($i % 100 === 0) {
$this->sendProgress([
'progress' => $i / $totalLines,
'message' => "Processed {$i}/{$totalLines} lines"
]);
}
}
return ['content' => [['type' => 'text', 'text' => "Processed {$totalLines} lines successfully"]]];
});
Resource Subscriptions โ
// Dynamic resources that can change
$server->resource('system-stats', 'live://system-stats', 'application/json', function() {
return [
'contents' => [[
'uri' => 'live://system-stats',
'mimeType' => 'application/json',
'text' => json_encode([
'cpu' => getCpuUsage(),
'memory' => getMemoryUsage(),
'disk' => getDiskUsage(),
'timestamp' => time()
])
]]
];
});
// Notify clients of changes
$server->onResourceChange('live://system-stats', function() {
// Resource content has changed
});
๐ Learning Path โ
Beginner Level โ
- Start with Examples: Run hello-world server and client
- Understand Tools: Create simple tools with basic input/output
- Explore Resources: Add static and dynamic resources
- Try Transports: Test STDIO and HTTP transports
Intermediate Level โ
- Error Handling: Implement robust error handling
- Authentication: Add security to your servers
- Complex Tools: Build tools that interact with external APIs
- Resource Management: Create dynamic, data-driven resources
Advanced Level โ
- Custom Transports: Build custom transport layers
- Protocol Extensions: Extend MCP for specialized use cases
- Performance Optimization: Scale servers for production
- Architecture Patterns: Design complex, distributed MCP systems
๐ Benefits of MCP โ
For Developers โ
- ๐ Rapid Development: Standard patterns and tools
- ๐ Built-in Security: Authentication and authorization
- ๐งช Easy Testing: Standardized interfaces
- ๐ Rich Ecosystem: Growing library of servers and tools
For AI Applications โ
- ๐ฏ Focused Capabilities: Specific, well-defined tools
- ๐ Dynamic Content: Real-time data access
- ๐ก๏ธ Controlled Access: Secure, permission-based operations
- ๐ Scalable Architecture: From simple tools to complex systems
For Organizations โ
- ๐๏ธ Standardized Integration: Consistent approach across teams
- ๐ง Modular Architecture: Composable, reusable components
- ๐ Better Governance: Centralized control and monitoring
- ๐ฐ Cost Effective: Reduced development and maintenance costs
๐ฏ Next Steps โ
Now that you understand MCP's core concepts:
- Try the Examples: Start with Quick Start and First Server
- Build Something: Create a server for your specific use case
- Explore Integration: Connect MCP to your existing systems
- Join the Community: Contribute to the MCP ecosystem
MCP represents the future of AI-system integration - secure, standardized, and infinitely extensible. Welcome to the revolution! ๐