English
Week 3: Multi-Agent
04. MCP Protocol

04. MCP Protocol Deep Dive

Overview

Instead of hard-coding tool functions inside your agent, MCP (Model Context Protocol) allows you to connect to external servers (like database connectors, Slack integrations, or file system access) in a standardized way.

Key Concepts

ConceptDescription
MCP ServerExposes Resources, Prompts, and Tools
MCP ClientThe agent that connects to the server and discovers capabilities
HandshakeThe process of the client asking the server "What can you do?"
ResourcesData exposed by servers (files, DB records, logs)
ToolsExecutable functions (get_user(), send_message())

MCP Server Implementation

class MockMCPServer:
    """A minimal MCP server implementation"""
 
    def __init__(self, name: str):
        self.name = name
        self.tools = {}
 
    def register_tool(self, name: str, description: str, handler: Callable):
        self.tools[name] = {
            "description": description,
            "handler": handler
        }
 
    def list_tools(self) -> List[Dict]:
        """Discovery endpoint - what can this server do?"""
        return [
            {"name": name, "description": tool["description"]}
            for name, tool in self.tools.items()
        ]
 
    def call_tool(self, name: str, arguments: Dict) -> Any:
        """Execute a tool by name"""
        if name not in self.tools:
            raise ValueError(f"Unknown tool: {name}")
        return self.tools[name]["handler"](**arguments)

MCP Client (Agent Side)

class MCPClient:
    """Client that connects to MCP servers"""
 
    def __init__(self, servers: List[MockMCPServer]):
        self.servers = servers
 
    def discover_all_tools(self) -> List[Dict]:
        """Discover tools from all connected servers"""
        all_tools = []
        for server in self.servers:
            tools = server.list_tools()
            for tool in tools:
                tool["server"] = server.name
            all_tools.extend(tools)
        return all_tools
 
    def execute(self, server_name: str, tool_name: str, args: Dict):
        """Execute a tool on a specific server"""
        server = next(s for s in self.servers if s.name == server_name)
        return server.call_tool(tool_name, args)

The MCP Handshake Flow

Why MCP Matters

Universal Connectivity: Write your integration once, use it with any LLM

Before MCPWith MCP
N×M integrations (N LLMs × M tools)N+M integrations
Custom code per LLMStandardized interface
Inconsistent implementationsEcosystem of connectors

Hands-on Practice

Build a Mock Server

Create an MCP server with user data tools

Implement Discovery

Let clients dynamically discover available tools

Connect to LLM

Use OpenAI function calling with MCP tools

Test the Flow

Run queries and observe the handshake process

References