How to Intermediate · 3 min read

How MCP client server communication works

Quick answer
The MCP client-server communication uses a protocol where the Server manages requests and responses over standard input/output or SSE transport. The mcp Python SDK provides classes like Server and stdio_server to implement this communication, enabling AI agents to interact with external tools or resources seamlessly.

PREREQUISITES

  • Python 3.8+
  • pip install mcp
  • Basic knowledge of Python async programming

Setup

Install the official mcp Python SDK and prepare your environment to run MCP client-server communication.

bash
pip install mcp

Step by step

This example demonstrates a simple MCP server using the stdio_server transport that listens for client messages and responds accordingly.

python
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server

async def handle_request(request):
    # Process the incoming request and return a response
    return {"result": f"Received: {request.get('input', '')}"}

async def main():
    server = Server(handle_request)
    await stdio_server(server)

if __name__ == "__main__":
    asyncio.run(main())

Common variations

You can implement MCP communication over different transports such as SSE or TCP by using other server implementations. Async handling allows concurrent requests. You can also customize the handle_request function to integrate with AI models or external APIs.

python
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server

async def handle_request(request):
    # Example: echo input with uppercase
    user_input = request.get('input', '')
    return {"result": user_input.upper()}

async def main():
    server = Server(handle_request)
    # Replace stdio_server with your custom transport if needed
    await stdio_server(server)

if __name__ == "__main__":
    asyncio.run(main())

Troubleshooting

  • If the server does not respond, ensure your client sends properly formatted JSON messages over the expected transport.
  • Check that asyncio.run() is used correctly to start the server.
  • For debugging, add logging inside handle_request to trace incoming requests.

Key Takeaways

  • Use the official mcp Python SDK to implement client-server communication for AI agents.
  • The Server class handles requests asynchronously over stdio or other transports.
  • Customize the request handler to integrate AI models or external tools.
  • Always run the server with asyncio.run() for proper async execution.
  • Debug communication by logging requests and verifying JSON message formats.
Verified 2026-04
Verify ↗