MCP Client Implementation in Python and TypeScript
Learn how to build MCP clients with the updated 2026-07-28 specification.

Implementing an MCP client in Python or TypeScript follows a clear pattern of transport selection, connection setup, capability exchange, and tool invocation. The SDKs make that pattern straightforward. Production reliability depends on the surrounding work, including process ownership, response validation, recovery, and OAuth boundaries. The 2026-07-28 specification revision changes how those responsibilities fit together, so current implementations must start from its stateless model.
What MCP clients do and where they sit in the protocol architecture
An MCP client lives inside a host application, such as an IDE, chat interface, or agent loop, and owns the protocol relationship with a server. It is not a thin HTTP wrapper. The client initiates connections, selects a transport, manages capabilities, and invokes server operations, while the server exposes those operations without initiating the connection. The client discovers three kinds of things: resources for data, tools for actions, and prompts for templates.
The official MCP project designates Python and TypeScript as Tier 1 SDKs that track the specification directly. Both are suitable starting points for new clients. Their APIs differ, but the architectural boundary stays clear between the host’s application logic and the client’s protocol responsibilities. That boundary becomes especially important when a specification change alters connection behavior without changing what a tool does.
How the 2026-07-28 spec revision changed the structural pattern every client must follow
The 2026-07-28 revision removed protocol-level session tracking and the initialize handshake. It was characterized as the most substantial change since authorization was added. Protocol version, client identity, and capabilities now travel in _meta on every request, rather than through a separate setup exchange before tool calls.
Control flow changed as well as request metadata. Multi Round-Trip Requests replace server-initiated callbacks with an InputRequiredResult, after which the client gathers the requested input and retries the original call with answers attached. Clients need a response loop that can keep an operation going when a reply leaves it unfinished.
The revision also deprecated HTTP+SSE, Roots, Sampling, Logging, includeContext values, and OAuth 2.0 Dynamic Client Registration. Tutorials built around /sse, separate /messages endpoints, or a standalone GET stream describe the deprecated transport. The GitHub MCP Server illustrates the operational consequence of the redesign. Its upgrade removed all Redis session storage, so calls no longer read from or write to the database.
Choosing between stdio and Streamable HTTP before writing a line of code
For a same-machine or container integration, stdio is the default choice. Remote or shared deployments require Streamable HTTP. With stdio, the client launches a child process and exchanges JSON-RPC through stdin and stdout, so it also owns that process’s lifecycle. Cursor and VS Code Copilot use this model for desktop integrations. Its scaling pattern remains per-client processes, reaching roughly hundreds of concurrent processes.
Stdout must remain reserved for protocol messages. A startup banner or log line can corrupt the JSON-RPC stream and produce a parse error that conceals the cause. Integration testing should therefore check what the server sends, and logs should go to stderr.
Streamable HTTP sends messages to a single /mcp endpoint and receives JSON or an event stream over that connection. It needs no separate GET stream. After the revision, protocol routing no longer requires session headers or sticky sessions, although an optional Mcp-Session-Id supports resumability for long-running calls. A small replica set can serve several clients behind one ingress. Because the SDKs separate transport from tool logic, migration from stdio typically requires only a small transport change.
Installing the SDKs and understanding the current package names
The TypeScript v2 client package is @modelcontextprotocol/client, installed with npm install @modelcontextprotocol/client. Servers use the separate @modelcontextprotocol/server package, with optional adapters for Express, Fastify, Hono, and Node.js. The old @modelcontextprotocol/sdk package is still maintained as v1. Watching that package alone will not reveal the v2 release, and new clients should use the split packages. The SDK runs on Node.js, Bun, and Deno.
Python requires version 3.11 or later. The latest release in this baseline is mcp 2.3.0, released on 2 Oct 2026, installed with uv add "mcp[cli]" or pip install "mcp[cli]". The extra adds mcp dev, mcp run, and mcp install. Plain mcp is enough when those commands are not needed. The official client tutorial needs SDK 2.0.0 or higher, while the server tutorial still has an older minimum of 1.2.0. For language selection, the recommended fit is TypeScript v2 for Node, Vercel, and gateway work, and Python 2.x for data tools and agent loops.
Building the Python client with transport wiring and tool invocation
The official client tutorial starts with uv init mcp-client && cd mcp-client, followed by uv add mcp anthropic python-dotenv. The Anthropic API key goes in .env, and that file should be added to .gitignore. Transport configuration enters Client, and the async with block defines the live connection’s scope and centralizes cleanup.
The server_params() helper turns a script path into StdioServerParameters, selecting python for a .py script or node for a .js script. Those parameters describe a process. They do not start one. stdio_client(server_params(path)) supplies the transport to Client, which opens it on entering the context. Exiting closes the transport and terminates the subprocess cleanly. For a remote server, passing its URL string directly to Client selects Streamable HTTP instead.
Inside that context, await client.list_tools() discovers the available tools, including their names, descriptions, and input JSON Schemas. The catalog can vary by authenticated account and server configuration, so the client caches it for the local session and refreshes it after a server change notification or a “tool not found” response. This local cache does not reintroduce protocol-level session tracking.
The process_query() function connects the conversation to discovered tools through anthropic.messages.create() and its tools parameter. When Claude returns a tool_use block, the function extracts the tool name and arguments, calls await client.call_tool(tool_name, tool_args), and appends a tool_result before the next API request. Results need typed handling. The client narrows content blocks to TextContent before reading .text, preserves is_error=True for the model, and uses structured_content when supplied.
The chat_loop() function keeps taking user queries while the connection is open. It uses asyncio.to_thread(input, ...) so typing does not block the event loop. Within query processing, an InputRequiredResult triggers input collection and another attempt at the original call with answers in _meta.
Building the TypeScript client in the v2 SDK
The TypeScript implementation begins with import { Client } from "@modelcontextprotocol/client", selecting the v2 successor to @modelcontextprotocol/sdk. That distinction selects the v2 implementation. The client constructor receives identity fields such as the name my-app and version 1.0.0, while its options declare capabilities, including tools and resources. Construction and connection remain SDK operations.
To run locally, StdioClientTransport takes a command and an array of arguments. The supplied filesystem example uses npx with arguments -y, @modelcontextprotocol/server-filesystem, and /data, followed by await client.connect(transport). For HTTP, the transport takes a URL object first. Its requestInit provides headers, including Authorization and an optional Mcp-Session-Id, whose returned value is retained for reconnection.
Discovery and invocation then follow the Python pattern through await client.listTools() and client.callTool(). Before dispatch, arguments need validation against the server’s JSON Schema. The SDK supports Standard Schema-compatible validators, including Zod v4, Valibot, and ArkType. A misspelled argument key explains the need. A lenient server can accept the call, treat the intended field as undefined, and run it the wrong way, so the failure becomes visible only later in business logic.
Strict Rust or Go servers can explicitly reject malformed calls, but client validation catches the mistake before the call is sent. Language choice does not change that responsibility. A Python client can call a TypeScript server over Streamable HTTP, or the reverse. The invariantlabs example repository demonstrates that interoperability with a weather server.
Session lifecycle management and error recovery in production
Silent process death requires bounded transport operations. When a stdio server crashes, a read may hang or return EOF instead of throwing an exception that explains what went wrong. Timeouts detect the hang, while EOF signals that the subprocess needs restarting. This recovery belongs with process ownership.
“Parse error on line 1” can mean that a startup banner or log entered stdout. Auditing server output during integration testing identifies the misplaced text. Keeping it on stderr restores the protocol boundary.
HTTP interruption calls for reconnection. The client captures Mcp-Session-Id from response headers when available and sends it again on reconnection to support resumption. A dropped connection during a long-running call is retriable. Stateless routing frees protocol state from being tied to one instance, but the client still needs a recovery path.
Catalog drift appears as a “tool not found” response after a restart or configuration change. The client invalidates its cache, calls list_tools() or listTools(), and then retries against the refreshed catalog. Python 2.3.0 adds an important recovery boundary. Client.call_tool does not automatically re-list tools or retry after a HeaderMismatch rejection with code -32020, leaving that recovery to the caller.
Multi Round-Trip Requests use an InputRequiredResult to ask for additional values, such as user confirmation, before the original operation can proceed. The response loop collects those values and reissues the call with answers in _meta. Stateless transport removes initialization and pinned-routing failures, but schema differences and provider-specific behavior still require integration work.
OAuth and the security boundary every HTTP client must enforce
An HTTP client can manage credentials for many MCP servers and identity providers simultaneously. That creates an OAuth mix-up exposure beyond a single-provider API integration. In September 2026, the Python and TypeScript SDKs published high-severity advisories within two days of each other for a flaw through which a malicious server could redirect OAuth credentials to an attacker-controlled authorization server. Discovery was the critical boundary.
The Python advisory describes a fallback after HTTP 404 from the standard discovery endpoint. The SDK retrieved OAuth configuration from the MCP server itself, then skipped issuer validation because the authorization-server URL was not yet set. Affected versions were 1.9.1 through 1.29.1 and 2.0.0 through 2.1.1 when using OAuth providers with untrusted HTTP servers. Python fixes shipped in 1.30.0 and 2.2.0. The TypeScript fixes shipped in @modelcontextprotocol/sdk 1.31.0 and @modelcontextprotocol/client 2.2.0 under CVE-2026-104850. The Python advisory has no assigned CVE.
The deployment rule is to pin Python to at least 2.2.0, or 1.30.0 on v1, and the TypeScript client package to at least 2.2.0. Patching is only the starting point. When connecting to untrusted HTTP servers, clients need issuer validation that does not depend on what those servers tell them. Discovery fallback needs close checks, and clients should use standard discovery when it is served correctly. New clients should not implement deprecated OAuth Dynamic Client Registration.
Keeping a client current as the spec and SDKs continue to evolve
Maintenance needs to track compatibility and changes in behavior as well as package activity. The typescript-sdk and python-sdk READMEs document the revision each release implements, while the modelcontextprotocol GitHub organization provides a place to track changes. Transport separation can keep transport revisions out of tool logic and limit the upgrade surface, which is a primary reason to use official SDKs.
Python 2.x supports the 2026-07-28 revision and still works with earlier revisions from the same server. Existing clients, proxies, or hosts that still need to complete the compatibility pass are a reason to keep v1 for now. That window needs an explicit migration plan. The TypeScript v1 branch receives fixes and security updates for at least six months after the v2 release on 2026-07-27.
Python 2.3.0 shows why wire-level behavior deserves attention even in a maintenance release. Empty _meta and params are no longer sent, requiring updates to middleware or tests that expect them. Invalid x-mcp-header annotations now fail at registration. Across more than 10,000 community servers with varying schemas and conformance, a durable client depends on explicit validation, owned connections, and recovery paths that remain separate from the tools themselves.
Sources
- Model Context Protocol · GitHub
Cited as the GitHub organization where readers can track MCP specification and SDK changes.
- GitHub - invariantlabs-ai/mcp-streamable-http: Example implementation of MCP Streamable HTTP client/server in Python and TypeScript. · GitHub
Cited directly as a demonstration of cross-language MCP interoperability using a weather server example.
- GitHub - modelcontextprotocol/typescript-sdk: The official TypeScript SDK for Model Context Protocol servers and clients · GitHub
Referenced for the TypeScript SDK README, v1/v2 package split, and the six-month v1 support commitment after v2 release.
- GitHub - modelcontextprotocol/python-sdk: The official Python SDK for Model Context Protocol servers and clients · GitHub
Sourced details on the Python SDK including version requirements, package naming, and the python-sdk README.
- Build an MCP client - Model Context Protocol
Provided the official client tutorial steps used in the Python and TypeScript implementation sections.
- SDKs - Model Context Protocol
Informed the description of Tier 1 SDKs, transport options, and the 2026-07-28 specification revision's structural changes.
- @modelcontextprotocol/sdk - npm
Referenced for details on the old @modelcontextprotocol/sdk v1 package and its maintenance status relative to the v2 split packages.


