{"id":9261,"date":"2026-11-30T23:16:26","date_gmt":"2026-11-30T23:16:26","guid":{"rendered":"https:\/\/lockitsoft.com\/?p=9261"},"modified":"2026-11-30T23:16:26","modified_gmt":"2026-11-30T23:16:26","slug":"building-an-mcp-client-in-python-from-scratch","status":"publish","type":"post","link":"https:\/\/lockitsoft.com\/?p=9261","title":{"rendered":"Building an MCP Client in Python from Scratch"},"content":{"rendered":"<p>The Model Context Protocol (MCP) has emerged as a foundational standard for bridging the gap between artificial intelligence agents and the vast, fragmented landscape of local and remote data sources. As developers increasingly look to move beyond simple chat interfaces, the ability to build a custom MCP client using the official Python SDK 2.0 has become a critical skill for creating autonomous, tool-capable AI applications. By leveraging the stdio transport mechanism, developers can establish a robust, bi-directional communication channel between an AI host and a server, enabling models to execute complex tasks by chaining together specialized functions.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#The_Architectural_Shift_in_AI_Integration\" >The Architectural Shift in AI Integration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#Prerequisites_and_the_Modern_Development_Environment\" >Prerequisites and the Modern Development Environment<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#Project_Initialization_and_Server_Setup\" >Project Initialization and Server Setup<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#Implementing_the_Test_Server\" >Implementing the Test Server<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#Communication_Mechanics_The_Client_Perspective\" >Communication Mechanics: The Client Perspective<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#The_Role_of_Chained_Tool_Execution\" >The Role of Chained Tool Execution<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#Implications_for_Future_AI_Development\" >Implications for Future AI Development<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/lockitsoft.com\/?p=9261\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h3><span class=\"ez-toc-section\" id=\"The_Architectural_Shift_in_AI_Integration\"><\/span>The Architectural Shift in AI Integration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The MCP architecture relies on a three-tier model designed to standardize how AI applications interact with external tools and resources. At the top of this hierarchy sits the &quot;host,&quot; typically an AI application or agent framework. The &quot;server&quot; acts as the provider of capabilities\u2014exposing specific tools, data resources, or prompt templates\u2014while the &quot;client&quot; functions as the connective tissue residing within the host. <\/p>\n<p>Prior to the formalization of MCP, developers often relied on proprietary, ad-hoc integrations for every individual API or database, leading to significant technical debt and maintenance overhead. The introduction of MCP, particularly with the 2.0.0 release, provides a vendor-neutral protocol that allows a client to dynamically discover and execute tools without requiring hard-coded logic for every specific service. This decoupling represents a major shift toward modular AI development, where tools can be swapped, updated, or removed with minimal disruption to the core application logic.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Prerequisites_and_the_Modern_Development_Environment\"><\/span>Prerequisites and the Modern Development Environment<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Building a production-ready MCP client requires a modern Python toolchain. Developers should ensure they are operating on Python 3.10 or higher. The use of the &#8216;uv&#8217; package manager has become the industry standard for this workflow, as it offers significantly faster dependency resolution and environment management compared to traditional &#8216;pip&#8217; and &#8216;venv&#8217; setups.<\/p>\n<p>The transition to the SDK 2.0.0 is non-negotiable for developers building today. The 2026-07-28 specification revision introduced breaking changes to the way sessions are initialized and how tool schemas are validated. Codebases still referencing the v1 &#8216;ClientSession&#8217; or &#8216;session.initialize()&#8217; patterns will fail against the current protocol, necessitating a migration to the updated &#8216;Client&#8217; and &#8216;StdioServerParameters&#8217; classes.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Project_Initialization_and_Server_Setup\"><\/span>Project Initialization and Server Setup<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To initiate the project, developers should first install the necessary environment using the following terminal commands:<\/p>\n<pre><code class=\"language-bash\">curl -LsSf https:\/\/astral.sh\/uv\/install.sh | sh\nuv init mcp-client\ncd mcp-client\nuv venv\nsource .venv\/bin\/activate\nuv add \"mcp[cli]\" anthropic python-dotenv<\/code><\/pre>\n<p>This configuration ensures that the client is strictly isolated from the global Python environment. The &#8216;mcp[cli]&#8217; package provides the necessary primitives for both server and client implementations, while &#8216;python-dotenv&#8217; ensures that sensitive credentials\u2014such as Anthropic API keys\u2014are managed via environment variables, adhering to security best practices by preventing hard-coded keys in source control.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Implementing_the_Test_Server\"><\/span>Implementing the Test Server<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>A functional MCP client requires a responsive server. Using the &#8216;MCPServer&#8217; class (which replaces the older &#8216;FastMCP&#8217;), developers can define tools using decorators that automatically generate JSON-RPC schemas. The following example demonstrates how to implement a weather-querying tool that utilizes the Open-Meteo API:<\/p>\n<pre><code class=\"language-python\">import logging\nfrom mcp.server import MCPServer\nfrom typing import Any\n\nmcp = MCPServer(\"weather-tools\")\n\n@mcp.tool()\nasync def get_weather(city: str) -&gt; str:\n    \"\"\"Get the current temperature and wind speed for a city.\"\"\"\n    # Logic to fetch geocoding and forecast data\n    return f\"Weather data for city is currently available.\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")<\/code><\/pre>\n<p>The critical constraint here is the stdio transport. Because the protocol communicates via JSON-RPC over the standard input and output streams, any stray &#8216;print()&#8217; statement or logging directed to stdout will corrupt the data stream, leading to immediate connection failures. All debugging information must be routed through &#8216;stderr&#8217;.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Communication_Mechanics_The_Client_Perspective\"><\/span>Communication Mechanics: The Client Perspective<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The client\u2019s responsibility is to bridge the gap between the model and the server. When the client executes <code>client.list_tools()<\/code>, it performs a <code>tools\/list<\/code> JSON-RPC handshake. The server responds with the schema definitions, which the client then translates into a format compatible with the Anthropic Messages API. <\/p>\n<p>When the model decides a tool is required, it returns a <code>tool_use<\/code> request. The client intercepts this, maps it to a <code>tools\/call<\/code> command, and waits for the server to return a <code>CallToolResult<\/code>. This result contains an <code>is_error<\/code> flag. A professional implementation must handle this flag gracefully, passing the error message back to the AI model so it can attempt a self-correction\u2014a process known as recursive tool invocation.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"The_Role_of_Chained_Tool_Execution\"><\/span>The Role of Chained Tool Execution<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>A common pitfall in early MCP development is failing to account for multi-turn conversations. Simple implementations often assume a single round-trip interaction. However, complex queries\u2014such as &quot;Check the temperature in Tokyo, then convert that value to Fahrenheit&quot;\u2014require the client to maintain a stateful loop.<\/p>\n<p>The client must append the assistant&#8217;s initial tool request to the history, execute the tool, and then append the <code>tool_result<\/code> to the message chain before sending the updated context back to the model. By limiting this loop (e.g., to 8 turns), developers can prevent infinite recursion while still providing the model enough &quot;runway&quot; to solve complex multi-step problems.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Implications_for_Future_AI_Development\"><\/span>Implications for Future AI Development<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>The adoption of MCP is set to accelerate the development of agentic AI. By standardizing the interface between models and local environments, developers can move away from building custom connectors for every new tool. Instead, the focus shifts to designing better tools and more capable prompt strategies.<\/p>\n<p>From an enterprise perspective, the implications are significant. Security and observability are improved because the client acts as a gatekeeper for all tool calls. Organizations can audit every interaction between their internal tools and the LLM via the logs generated by the client. As the MCP standard matures, it is likely that we will see a proliferation of &quot;MCP Hubs,&quot; where pre-built, high-quality servers are distributed, allowing developers to plug-and-play complex capabilities into their AI agents.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Building an MCP client in Python 2.0 is a rigorous exercise in understanding the modern AI stack. By mastering the stdio transport, the nuances of the JSON-RPC lifecycle, and the necessity of maintaining stateful message histories, developers can create AI agents that are not merely chatbots, but functional assistants capable of interacting with the real world. As the industry moves toward deeper integration, the ability to architect these connections from scratch remains a foundational capability for any engineer working in the field of artificial intelligence.<\/p>\n<!-- RatingBintangAjaib -->","protected":false},"excerpt":{"rendered":"<p>The Model Context Protocol (MCP) has emerged as a foundational standard for bridging the gap between artificial intelligence agents and the vast, fragmented landscape of local and remote data sources. As developers increasingly look to move beyond simple chat interfaces, the ability to build a custom MCP client using the official Python SDK 2.0 has &hellip;<\/p>\n","protected":false},"author":20,"featured_media":9258,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[23,567,5729,25,24,688,4277],"class_list":["post-9261","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-artificial-intelligence","tag-ai","tag-building","tag-client","tag-data-science","tag-machine-learning","tag-python","tag-scratch"],"_links":{"self":[{"href":"https:\/\/lockitsoft.com\/index.php?rest_route=\/wp\/v2\/posts\/9261","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/lockitsoft.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lockitsoft.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lockitsoft.com\/index.php?rest_route=\/wp\/v2\/users\/20"}],"replies":[{"embeddable":true,"href":"https:\/\/lockitsoft.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=9261"}],"version-history":[{"count":0,"href":"https:\/\/lockitsoft.com\/index.php?rest_route=\/wp\/v2\/posts\/9261\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/lockitsoft.com\/index.php?rest_route=\/wp\/v2\/media\/9258"}],"wp:attachment":[{"href":"https:\/\/lockitsoft.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=9261"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lockitsoft.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=9261"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lockitsoft.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=9261"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}