Solving the M x N Integration Nightmare with Model Context Protocol
From the publisher’s feed, collected in the ZeroLabs newsroom.
Here’s a simple, meaningful explanation of each section about Model Context Protocol (MCP) — you can use this for notes, docs, or interviews.✅ Why MCP?AI systems often fail not because models are weak, but because they don’t have consistent access to the right context. Data lives across many tools — databases, internal apps, chat systems, code repos — and integrating all of them manually is messy.MCP exists to standardize how AI connects to tools and data, so models can work reliably across environments without custom glue code every time.The Problem of Fragmentation:If you have 5 AI apps and 5 databases, you have to write 25 different integrations, 5 x 5. If you add one more database, you have to update all 5 apps. It quickly becomes a nightmare.This creates an M × N integration problem: M = number of AI apps, N = number of data sourcesEach AI app needs custom integrations for each source.Consequences:❌ Stale or incomplete data❌ Hallucinations (model guesses without context)❌ Rebuilding integrations repeatedly❌ Vendor lock-in❌ Poor reliability in complex workflows (e.g., planning trips, debugging code)👨💻 Common Problems as a Software Engineer:Engineers working with AI tools run into:Constant re-integration: Every project requires wiring new APIs.Context loss: Multi-step workflows break because tools don’t share memory.Maintenance burden: Updating integrations is costly.Security complexity: Permissions and data access are inconsistent.Unpredictable behaviour: Tools behave differently across models.🔧 Function Calling — What’s the Issue?Function calling lets an LLM call APIs, but:It’s stateless (no shared memory across steps).It’s model-specific (each vendor implements differently).It requires manual schema definitions.It’s hard to orchestrate complex workflows.👉 Good for simple tasks, not for real systems.🚀 Rise of Tools — New ComplexityWe now have many:PluginsAgentsConnectorsTool frameworksBut there’s no universal standard — leading to fragmentation again.Every ecosystem reinvents integration.⚠️ Imperfections of Tools & Problems with ToolsMost tools today suffer from:Poor interoperabilityNo shared protocolWeak context sharingSecurity inconsistenciesTight coupling to specific vendorsDifficult debuggingResult: fragile AI systems.🧠 Overview of Problem and SolutionAI lacks a universal way to:Discover toolsShare contextMaintain stateCoordinate workflowsSolution:👉 MCP provides a standard protocol layer between AI and tools.Think of MCP as:“USB for AI integrations”Plug once — use anywhere.📡 MCP OverviewMCP is a protocol that enables:Stateful interactionsTool discoveryContext sharingMulti-step orchestrationModel-agnostic integrationsIt defines how:AI talks to toolsTools expose capabilitiesContext flows safely⚖️ MCP vs Tool CallingFeature Tool Calling MCP State Stateless Stateful Workflow Linear Multi-step Vendor lock-in High Low Context sharing Limited Rich Orchestration Manual Built-in Portability Low High.👉 Tool calling = single action👉 MCP = coordinated system🔌 MCP vs APIAPIs like REST/ GraphQL are designed for developers, not AI.APIs lack: Traditional APIs (like REST) were built for human developers typing out strict commands.They don’t understand conversational context. MCP acts like an AI-native Translator on top of those APIs, allowing the AI to ask questions, discover what a tool can do naturally, and remember the conversation from the previous step.MCP adds an AI-native layer on top, which can do conversational interaction with Host, automatically detect, understand, and integrate external tools, APIs, or operational competencies on the fly, without needing hardcoded programming.🌟 Benefits of MCP✅ Standardized integration✅ Reduced engineering effort✅ Reliable multi-step workflows✅ Better context → fewer hallucinations✅ Cross-model compatibility✅ Improved security patterns✅ Faster development cycles✅ Less vendor lock-in🌍 MCP EcosystemThe ecosystem typically includes:MCP servers (expose tools/data)MCP clients (AI systems)ConnectorsTool providersAgent frameworksObservability layersAs adoption grows, MCP could become the default infrastructure layer for AI applications.🧩 One-Line Summary👉 MCP standardizes how AI systems connect to tools and data, making integrations reliable, portable, and context-aware.MCP Architecture :Host:You can think of this analogy where the Host is like the restaurant dining room, or customer in the restaurant. Where main action happens (e.g. Claude Desktop)The host is the AI application (e.g., Claude Desktop, VS Code, or an IDE) that runs the LLM and initiates connections to external services. It orchestrates workflows, maintains full conversation history, and enforces security by mediating all interactions.Client:The client is like the waiter in the restaurant who is serving the Host. Translates and carries the messages back and forth.The client is a lightweight component created by the host — one per server connection — that manages bidirectional JSON-RPC communication. It handles protocol negotiation, capability exchange, subscriptions, notifications, and message routing while isolating servers from each other.Server:The server is like the kitchen in the restaurant. The isolated area that actually does the specific work (fetches data, runs a query) and hands it back.The server is an independent process exposing specialized capabilities like tools, resources (data), prompts, or notifications from external systems (e.g., GitHub, Slack, databases). Servers operate in isolation, declare their features dynamically, and cannot access full context or other servers directly.Benefits of MCP Architecture:Decoupling: safety and ParallelismScalability: You can add multiple servers with the HostPrimitives:Primitives are things the server offers to the hostTools(Actions): Things the AI can do (e.g., fetch a database row, create a GitHub repo). Actions that the AI requests the server to perform. Dynamic data includes metrics such as the number of commits or repositories.Resources(Data): Things the AI can read (e.g., a local file, a database schema, an API response). Structured data sources that the AI can access. Static data falls under the category of resources.Prompts(Templates): Shortcuts or instructions the server gives the AI (e.g., a built-in template for “Review this code for bugs”).Predefined templates or instructions provided by the server to help shape the AI’s behaviour.MCP Data Layer:Data Layer: The data layer is the language and grammar of the MCP ecosystem that everyone agrees upon to communicate.In MCP, JSON-RPC 2.0 serves as the foundation of the data layer.Think of JSON-RPC as a standardized script. Instead of guessing how to ask for data, the AI sends a strict note: `Run this specific function with these specific details.`JSON RPC 2.0 stands for JavaScript Object Notation Remote Procedure Call.A Remote Procedure Call (RPC) allows a program to execute a function as if it were local, hiding the details of network communication and data transfer. This abstraction makes it easier to build distributed applications.Instead of writing add(2,3) locally, you send a request to the server saying “please run add with parameters 2 and 3.”JSON RPC combines the concept of Remote Procedure Calls with the simplicity of JSON, allowing developers to structure RPC requests and responses in standardized JSON format.Example of CommunicationWhy do we use JSON RPC in MCP?Its lightweightSupports bi-directional communicationsIt is transport-agnosticSupport batchingSupports notificationsTransport LayerNow that our client and server speak the same language (JSON-RPC), how do they actually send messages to each other? It depends on where they live(Server Type):Types of ServerIf they are on the same computer (Local): They use STDIO (Standard Input/Output). It’s like typing directly into a terminal backend — fast, simple, and secure.stdin ( Input the program reads)stdout (Output the program writes)2. If they live on different computers (Remote): They use HTTP + SSE (Server-Sent Events). This is just standard web traffic, allowing an AI app on your desktop to talk to a secure server running in the cloud.STDIO vs HTTP/SSE: Frame STDIO as “Internal Chat” (processes talking inside the same computer) and HTTP/SSE as “Phone Calls” (talking across the internet).MCP Lifecycle:The MCP life cycle is the complete sequence of steps that govern how a host (Client) and a server establish, use and end a connection during a session.Stages of MCP Lifecycle:Think of the MCP Lifecycle as a 3-step handshake:Hello & Version Check: The client says hello and asks if they speak the same version of MCP.Showing Off Capabilities: The server says, ‘Yes! And here is a list of tools and files I can give you access to.’Ready to Work: The client acknowledges it, and they start talking.Initialization:The client sends an initialisation request to the server. The server sends its own capabilities and info. After successful initialization, the client MUST send an initialized notification to indicate it is ready to begin normal operations. Now the client and Server are connected.Client-to-Server: initialize Request{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-03-26", # MCP Protocol Version "capabilities": { # Client capabilities "roots": { "listChanged": true }, "sampling": {} }, "clientInfo": { # Client Implementation Info "name": "ExampleMCPClient", "version": "1.0.0" } }}# # Step-2: Server-to-Client: initialize Response{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-03-26", # MCP Protocol Version "capabilities": { # Server capabilities "prompts": { "listChanged": true }, "resources": { "subscribe": true, "listChanged": true }, "tools": { "listChanged": true } }, "serverInfo": { # Server Implementation Info "name": "ExampleMCPServer", "version": "1.0.0" } }}# Step-3: Client-to-Server: initialized Notification{ "jsonrpc": "2.0", "method": "notifications/initialized"}# Now Client and Server are Connected.1. The client MUST wait for the server's response to the initialize request before sending operational requests, except for pings. 2. The server MUST wait for the client's initialized notification before sending operational requests or custom responses, except for pings and logging messages.Version Negotiation: Before exchanging data, the client and server must agree on which version of the Model Context Protocol they will use. Since the client triggers the connection, it initiates this process.i. Client Proposal: The client sends an initialize request containing the highest MCP version it supports (or a list of versions).ii. Server Decision: The server reviews the version.If it supports that version, it responds back confirming it.If it doesn’t, it responds with the highest version it does support that is compatible, or throws an error if there is a complete mismatch.# Client Request (initialize):{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "ExampleClient", "version": "1.0.0" } }}# Server Response (Confirming Version):{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": {}, "serverInfo": { "name": "ExampleServer", "version": "2.4.1" } }}Capability Negotiation: Once the protocol version is locked in, both sides need to declare what they can do. MCP is highly modular; a server might only provide Prompts, while another might provide Tools or Resources. Similarly, a client might support dynamic logging or roots management.Instead of assuming features, they explicitly declare their features inside the capabilities object during the exact same initialize handshake.# Client Request (Declaring Client Capabilities):{ "jsonrpc": "2.0", "id": 2, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "clientInfo": { "name": "ClaudeDesktop", "version": "1.2.0" }, "capabilities": { "experimental": {}, "sampling": {}, "roots": { "listChanged": true } } }}# Server Response (Declaring Server Capabilities):{ "jsonrpc": "2.0", "id": 2, "result": { "protocolVersion": "2024-11-05", "serverInfo": { "name": "Postgres-Database-MCP", "version": "1.0.0" }, "capabilities": { "resources": { "subscribe": true, "listChanged": true }, "tools": { "listChanged": true }, "prompts": {} } }}Operation:During the operation phase, the client and server exchange messages according to the negotiated capabilities. Respect the negotiated protocol version. Only use capabilities that were successfully negotiated.Capability Discovery: Once the initialization handshake is complete and the protocol version is locked in, Capability Discovery allows the client to dynamically find out exactly what resources, tools, and prompts the server has to offer. Instead of guessing what a server can do, the client calls specific “list” methods to discover its features.# Discover all tools present in the Server # Client Request:{ "jsonrpc": "2.0", "id": 3, "method": "tools/list"}# Server Response:{ "jsonrpc": "2.0", "id": 3, "result": { "tools": [ { "name": "execute_query", "description": "Run a read-only SQL query against the database", "inputSchema": { "type": "object", "properties": { "sql": { "type": "string" } }, "required": ["sql"] } } ] }}Tool Calling: While Capability Discovery lets the client know what tools are available, Tool Calling is where the actual execution happens.# Client Request (tools/call):{ "jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": { "name": "execute_query", "arguments": { "sql": "SELECT name, email FROM users WHERE status = 'active' LIMIT 3;" } }}# Server Response:{ "jsonrpc": "2.0", "id": 6, "result": { "content": [ { "type": "text", "text": "[{\"name\": \"Alice\", \"email\": \"alice@example.com\"}, {\"name\": \"Bob\", \"email\": \"bob@example.com\"}]" } ], "isError": false }}Shutdown of MCP:One side (typically the client) initiates shutdown. No special JSON RPC shutdown messages are defined. The transport layer is responsible for signalling.i. Shutdown in STDIO:a) Client-initiated shutdown:Close the Stream: The host application (Client) explicitly closes its stdin stream (the input stream feeding into the child process server).Await Exit: The client pauses brieflyrocess to notice the closed stream, wrap up its current execution, and exit naturally.Enforce Termination: If the server fails to exit within a reasonable, predefined timeout window, the client steps in and sends a SIGTERM or SIGKILL signal to terminate the process forcefully.b) Server-Initiated Shutdown: When a local STDIO server needs to shut down independently (for example, due to a critical internal error, an unhandled exception, or a self-assigned idle timeout), it initiates the teardown by closing its standard output (stdout) or standard error (stderr) streams.ii. Shutdown in HTTP:a) Client-initiated shutdown: When the host application no longer needs the server’s capabilities, it takes the initiative to clean up the network footprint:The client (Host) explicitly closes the active HTTP connection(s) and terminates the SSE event stream it opened to the server.This drops the network socket, signaling to the remote server that it can safely free up the session memory and resources allocated to that specific client.b) Server-Initiated Shutdown (The Resilient Case): In a remote architecture, a server might need to go offline for maintenance, experience a deployment update, or encounter an internal error:The server may close the connection from its side, cutting off the SSE stream.Because network drops can happen unexpectedly, the MCP specification dictates a strict rule: The client must be prepared to detect a dropped connection and handle it gracefully (e.g., attempting a structured exponential backoff reconnect or alerting the user, rather than crashing).Special Cases in MCP:Pings: Ping is a lightweight request/response method defined by MCP. The purpose is to check whether the other side (Host or Server) is still alive and whether the connection is responsive.# Client --> Server Ping Request{ "jsonrpc": "2.0", "id": 100, "method": "ping"}# Server --> Client Ping Response{ "jsonrpc": "2.0", "id": 100, "result": {}}If no response is received within a reasonable timeout period, the sender MAY: a) consider the connection stale, b) terminate the connection, c) Attempt reconnection proceduresHow use MCPType of ConnectionsUsing a config fileUsing ConnectorWhat is a Connector?A connector is a built-in feature that automatically links Claude to MCP, eliminating the need for manual setup or configuration.This keeps things easy, safe and Consistent.Why not always use Connectors?Connectors are officially built, hosted, and maintained by Anthopic. But it is not scalable.MCP is an open standard. MCP is designed so that anyone can write a server. Not dependent on the Anthopic Team.How to make a server and client?Two libraries are available: 1) MCP SDK, 2) FASTMCPFASTMCP is beginner-friendly. Easy to make the MCP Server and the MCP Client.Quick Start Of MCP using FASTMCPStep-1:pip install fastmcp# check fastmcp versionfastmcp versionStep-2:i) Create a project folder name "MY MCP"ii) Open the folder in VS Code iii) create to file 'my_server.py' and 'my_client.py'Step-3: my_server.pyfrom fastmcp import FastMCPmcp=FastMCP("First MCP Server")## Add tool to the MCP server@mcp.tooldef greet(name: str) -> str: """Greet a person by name.""" return f"Hello, {name}!"@mcp.tooldef add(a: float, b: float) -> float: """Add two numbers.""" return a + bif __name__ == "__main__": mcp.run(transport="http", port=8000)Step-4: my_client.pyimport asynciofrom fastmcp import Clientclient=Client("http://localhost:8000/mcp")async def call_tool(name: str): """Call the greet tool on the MCP server.""" async with client: result = await client.call_tool("greet", {"name": name}) print(result) asyncio.run(call_tool("Debasish"))Step-5:# run server fastmcp run my_server.py:mcp --transport http --port 8000Output of CLI Results# run client python my_client.pyOutput of Client Tool CallConclusionThe Model Context Protocol isn’t just another framework; it is the universal adapter the AI ecosystem desperately needed. By separating the client application from the underlying tools and data sources, MCP effectively destroys the M x N integration nightmare.Whether you are building complex multi-agent workflows for production or just trying to give an LLM access to your local notes, using MCP ensures your integrations remain modular, highly secure, and entirely model-agnostic.What are you planning to build with MCP? Let me know in the comments below! If you found this guide helpful, don’t forget to leave some claps 👏 and follow for more practical AI engineering guides.Solving the M x N Integration Nightmare with Model Context Protocol was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.