MCP: Model Context ProtocolBeginnerModule 02 — MCP architecture and components
What is an MCP client, and how does it operate?
Question 14 of 43 · Updated
On this page
- Direct answer
- 1. Where the client fits in an application
- 2. What is inside a client implementation?
- 3. Establishing a connection
- 4. Initialization and capability negotiation
- 5. Walk through one ordinary client interaction
- 6. Discovery and invocation are separate operations
- 7. Requests, responses and notifications
- 8. Error handling: preserve the failure category
- 9. Tested implementation: model a client's protocol state
- 10. Connection lifetime and shutdown
- 11. Practical troubleshooting by layer
- 12. Common misconceptions
- Interview-ready answer
Direct answer#
An MCP client is the protocol-speaking component of an application that communicates with an MCP server. It establishes a supported connection, exchanges initialization and capability information, sends requests, correlates responses, processes notifications, handles supported server-initiated requests, and exposes the resulting capabilities to its host application.
The host decides what the user wants and which operations are allowed. The client handles the communication needed to perform an approved operation. The server implements the capability and independently authorizes access to its underlying resources.
In the historical session-oriented MCP architecture, a host can manage several clients, each with a dedicated connection to a particular server. A logical client-server connection is not necessarily a single physical network socket. A client does not require an LLM to perform ordinary protocol operations.
Learning continuity: Q16 defined the host as the application-level coordinator. Q17 follows one client connection from setup through discovery, invocation and closure. Q18 introduces the server. Later modules cover JSON-RPC message schemas, concurrency, initialization, transports, SDK implementations and error handling in depth.
Verification scope: Prepared under the authorized offline research and changelog exceptions. The historical MCP 2025-06-18 specification is used as a reference baseline, not claimed to be the latest revision. Official documentation links were not checked live. The standard-library Python example was syntax-compiled and executed with Python 3.13.5; all 12 explicit checks passed. It models client state and message handling using in-memory fixtures, not a full MCP SDK or network session. The two Mermaid diagrams were structurally reviewed; the local Mermaid package was unavailable, so parsing and frontend rendering remain unverified.
1. Where the client fits in an application#
Consider the retailer's support assistant. The host provides a user interface, determines which facts the user is entitled to receive and may use an LLM to interpret a request for product availability. It connects to an inventory server and a separate policy server.
The inventory client sends inventory requests and interprets protocol responses from that server. The policy client handles the separate policy-server connection. Neither client needs to understand the entire customer-support conversation.
The diagram describes logical communication paths. SDKs and transports may introduce additional objects, streams or HTTP requests inside each path. The host is responsible for creating the appropriate clients and deciding whether a particular connection should be used.
| Component | Main responsibility |
|---|---|
| Host | Task orchestration, model integration, user consent and context policy |
| Client | Protocol lifecycle, request correlation, supported message exchange and result delivery |
| Server | Capability exposure and execution |
| Business service | Authoritative data, permissions and domain invariants |
The client is not the LLM and does not need to decide the meaning of the user's natural-language request. A host can invoke client operations directly from ordinary code.
2. What is inside a client implementation?#
An MCP SDK may package client responsibilities into several layers rather than a single class.
| Logical layer | Purpose |
|---|---|
| Transport adapter | Reads and writes protocol messages using a supported transport |
| Session/lifecycle controller | Manages initialization, compatible revision and negotiated capabilities |
| Message codec | Encodes, decodes and validates supported protocol messages |
| Request manager | Allocates request identifiers and correlates responses with pending requests |
| Capability interface | Exposes convenient operations for discovery and invocation |
| Incoming message dispatcher | Handles notifications and supported server-initiated requests |
| Error and cleanup handling | Reports failures and releases resources |
These are conceptual implementation responsibilities, not a list of mandatory class names or SDK APIs. For example, a Python SDK may separate a transport context manager from a client session. A TypeScript SDK may expose related operations through a client object and a transport implementation.
The application must choose an SDK and transport compatible with the server's actual supported specification. A client SDK version number is not the protocol revision.
3. Establishing a connection#
The host supplies a trusted server configuration. The client then uses the configured transport to exchange messages.
In the historical 2025-06-18 baseline, two standard transports are stdio and Streamable HTTP.
- stdio: A client typically launches an approved server subprocess and exchanges newline-delimited protocol messages through its standard input and output. Server diagnostic logging must not corrupt the protocol output stream.
- Streamable HTTP: A client communicates with a configured HTTP MCP endpoint through the applicable transport rules. A server can use HTTP responses and supported SSE streams to deliver messages. Authentication and session behavior depend on the deployment and specification.
A successful transport connection is not the same as a ready MCP session. For example, an HTTP endpoint may be reachable but require authorization, or a subprocess may start successfully while failing during protocol initialization.
A client must not interpret network reachability as evidence that a server supports every MCP capability. The next step is to establish compatible protocol behavior.
The host chooses trusted destinations and credential policy; the transport and client components implement the relevant connection and authentication mechanisms. Server-side resource authorization remains independently necessary.
4. Initialization and capability negotiation#
Initialization allows participants to establish the protocol revision and advertise their supported features. In the historical session-oriented lifecycle, the client sends an initialize request, the server returns its selected revision and capabilities, and the client sends notifications/initialized after successful initialization.
A simplified example of an initialization request is:
JSON{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "retail-support-client", "version": "1.0" } } }
The empty client capabilities object illustrates a client that does not advertise optional features such as sampling. It does not prevent the client from consuming compatible server tools.
A corresponding illustrative server response is:
JSON{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2025-06-18", "capabilities": { "tools": { "listChanged": true } }, "serverInfo": { "name": "inventory", "version": "1.0" } } }
This server advertises tools and support for tool-list-change notifications. It does not advertise resources or prompts in this example. A client should not assume that resources/list is available merely because tools/list is available.
If a server selects a revision different from the client's proposed revision, the client must determine whether the selected revision is supported under the applicable negotiation rules. If it cannot operate compatibly, it should not continue as if initialization succeeded.
The example fixes a historical revision for teaching purposes. Real SDKs may support several revisions, and actual lifecycle behavior must be checked against the relevant specification. Detailed negotiation and initialization edge cases belong to Q36–41.
5. Walk through one ordinary client interaction#
The diagram describes a successful historical session-oriented flow, including an optional notification supported by the example server. The transport connection and any authorization steps are omitted for readability. The close operation is a host-side instruction to release resources; it is not a universal JSON-RPC shutdown method.
Notice that the host does not need to construct each low-level message itself when using a compatible SDK. It can call the client's discovery and invocation interfaces, while the client handles the protocol exchange.
6. Discovery and invocation are separate operations#
Discovery tells the application which capabilities a compatible server advertises. Invocation requests the actual operation.
| Capability | Example discovery method | Example use method |
|---|---|---|
| Tools | tools/list | tools/call |
| Resources | resources/list or resources/templates/list | resources/read |
| Prompts | prompts/list | prompts/get |
The exact available methods and their parameters depend on the negotiated revision and capability support. Not every server implements every capability.
A tool discovery result might describe a stock operation, including a name, description and input schema. The host can then decide whether to offer that operation to a user or model. A discovered tool is not automatically authorized for execution, and discovery does not execute the tool.
For an approved stock lookup, a historical tool invocation could be represented as:
JSON{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "stock", "arguments": { "sku": "A12" } } }
An illustrative successful response could be:
JSON{ "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "7 units available" } ] } }
The client delivers the relevant result to the host. It should preserve important content types, structured output where supported and error status rather than blindly converting every result into a successful text string. The host decides whether the result is safe and relevant for its workflow or model.
A discovery list may be paginated. A capable client must handle the supported continuation mechanism instead of assuming that the first returned page is the entire catalog. Detailed discovery and result-content mechanics are covered later.
7. Requests, responses and notifications#
JSON-RPC separates three useful message patterns.
| Message type | Purpose | Identifier behavior |
|---|---|---|
| Request | Ask the peer to perform a protocol operation | Carries an ID used for response correlation |
| Response | Return the result or error of a request | Carries the matching request ID |
| Notification | Inform the peer about an event without a response | Omits the ID |
A client may issue more than one outstanding request. Suppose it requests the tool catalog and a stock result. The second response may arrive first. The client should associate each response with its original request rather than assuming that all responses arrive in submission order.
A common implementation maintains a pending-request map, keyed by request ID. When a response arrives, the client identifies the corresponding pending operation and resolves it with its result or error. Unknown, duplicate or otherwise invalid responses require safe handling rather than being assigned to another operation.
The request ID is a communication identifier, not a business idempotency key, access token or proof of user consent. A production implementation must also handle timeout cleanup, ID uniqueness within the relevant scope, concurrency and the possibility of connection replacement.
Notifications can arrive independently of pending requests. For example, a server that advertises the appropriate feature may send notifications/tools/list_changed to indicate that its tool catalog needs refreshing. The client can report this event to the host, which may invalidate the previously exposed catalog and re-discover capabilities.
The client should not treat a notification as the response to whichever request happens to be pending. A notification can affect application state, but it does not complete an unrelated request.
Communication can also be bidirectional. Depending on negotiated capabilities and the specification, a server may send requests such as ping or supported sampling, roots or elicitation operations. A real client must route supported incoming requests to appropriate handlers and produce the required responses. The term client does not mean that the participant can only send requests and never receive them.
8. Error handling: preserve the failure category#
A client receives different types of failures. Reporting all of them as tool failure loses useful information; reporting all valid responses as success is worse.
| Failure | Example | Client-level responsibility |
|---|---|---|
| Transport failure | Server subprocess exits or HTTP connection fails | Report unavailable connection and clean up pending work |
| Initialization failure | Incompatible protocol revision | Prevent ordinary operations on an unready connection |
| Capability mismatch | Server does not offer tools | Avoid an unsupported feature |
| Protocol error | Response contains a JSON-RPC error | Deliver the structured error to the caller |
| Tool execution error | Tool result marks isError true | Preserve the execution-error status |
| Invalid response | Unrecognized ID or unsupported content shape | Reject or isolate invalid data according to implementation policy |
| Business rejection | Valid result reports insufficient stock | Deliver the domain outcome without claiming business success |
For example, a tool may return a normal MCP result containing isError true. That differs from receiving a JSON-RPC error object. The host can decide how to present the failure or whether to ask the model to revise a proposed call.
An interrupted write requires additional care. A timeout does not prove that the operation was never performed. The client should report the communication failure without inventing a business outcome. The host and authoritative service need an appropriate recovery and reconciliation strategy.
The detailed classification of MCP protocol errors versus tool errors appears later in the error-handling module. Here the key lesson is that the client preserves information needed for the host to make a correct decision.
9. Tested implementation: model a client's protocol state#
The following example isolates the client-side responsibilities. Unlike the earlier Q13 subprocess demonstration, this exercise does not run a server at all. It simulates decoded incoming messages and focuses on readiness, advertised feature checks, request identifiers, out-of-order responses, notifications, error classification and pending-request cleanup.
It is deliberately a small teaching state machine, not an MCP implementation. It uses only Python's standard library and handles a fixed historical revision. Initialization is supplied as a decoded result, not performed through an actual initialize exchange. The ready transition abstracts the successful initialization sequence, including the required initialized notification.
Save as mcp_q17.py:
PYTHONfrom dataclasses import dataclass, field @dataclass class Client: state: str = 'new' features: set = field(default_factory=set) pending: dict = field(default_factory=dict) next_id: int = 1 catalog_dirty: bool = True def request(self, method, params=None): needed = {'tools/list': 'tools', 'tools/call': 'tools', 'resources/list': 'resources', 'prompts/list': 'prompts'} if method not in needed or self.state != 'ready': raise RuntimeError('Method unavailable') if needed[method] not in self.features: raise RuntimeError('Capability unavailable') i = self.next_id self.next_id += 1 self.pending[i] = method return {'jsonrpc': '2.0', 'id': i, 'method': method, 'params': {} if params is None else params} def accept_initialization(self, result): if self.state != 'new' or result['protocolVersion'] != '2025-06-18': raise RuntimeError('Unsupported initialization') self.features = set(result['capabilities']) self.state = 'ready' def receive(self, message): if self.state != 'ready' or message.get('jsonrpc') != '2.0': raise ValueError('Invalid message or session state') if 'method' in message: if 'id' in message or 'result' in message or 'error' in message: raise ValueError('Unsupported incoming message') if message['method'] == 'notifications/tools/list_changed': self.catalog_dirty = True return 'notification', None i = message.get('id') if type(i) is not int or i not in self.pending: raise ValueError('Unexpected response ID') if ('result' in message) == ('error' in message): raise ValueError('Expected result or error') method = self.pending.pop(i) if 'error' in message: return 'rpc_error', message['error'] result = message['result'] if method == 'tools/call' and result.get('isError', False): return 'tool_error', result return 'result', result def close(self): abandoned = tuple(self.pending) self.pending.clear() self.features.clear() self.state = 'closed' self.catalog_dirty = True return abandoned def rejects(fn, error): try: fn() except error: return raise AssertionError('Expected rejection') if __name__ == '__main__': c = Client() rejects(lambda: c.request('tools/list'), RuntimeError) rejects(lambda: c.accept_initialization({'protocolVersion': 'other', 'capabilities': {}}), RuntimeError) c.accept_initialization({'protocolVersion': '2025-06-18', 'capabilities': {'tools': {}}}) rejects(lambda: c.request('resources/list'), RuntimeError) a = c.request('tools/list')['id'] b = c.request('tools/call', {'name': 'stock', 'arguments': {'sku': 'A12'}})['id'] assert a != b c.catalog_dirty = False assert c.receive({'jsonrpc': '2.0', 'method': 'notifications/tools/list_changed'}) == ('notification', None) and c.catalog_dirty assert c.receive({'jsonrpc': '2.0', 'id': b, 'result': {'content': []}})[0] == 'result' assert c.receive({'jsonrpc': '2.0', 'id': a, 'error': {'code': -32603, 'message': 'Internal error'}})[0] == 'rpc_error' rejects(lambda: c.receive({'jsonrpc': '2.0', 'id': b, 'result': {}}), ValueError) d = c.request('tools/call')['id'] assert c.receive({'jsonrpc': '2.0', 'id': d, 'result': {'isError': True, 'content': []}})[0] == 'tool_error' e = c.request('tools/list')['id'] rejects(lambda: c.receive({'jsonrpc': '2.0', 'id': e, 'result': {}, 'error': {}}), ValueError) assert c.close() == (e,) and not c.pending rejects(lambda: c.request('tools/list'), RuntimeError) print('12 client-state checks passed')
Run with Python 3.10 or later:
BASHpython -m py_compile mcp_q17.py python mcp_q17.py
Actual local output using Python 3.13.5:
12 client-state checks passedThe 12 explicit checks verify rejection before initialization, incompatible revision rejection, unsupported resource capability, unique IDs, notification-driven invalidation, out-of-order result handling, RPC error classification, duplicate response rejection, tool error classification, rejection of a response containing both result and error, pending-request cleanup and denial after closure.
The pending map associates each request with its originating method. When the later stock response arrives first, the client correctly recognizes it as a tools/call result rather than treating it as the response to tools/list. The notification marks the catalog dirty without removing a pending request.
Deliberate limitations: The fixture uses numeric IDs only, does not implement actual transports, authorization, schema validation, version negotiation or the full JSON-RPC grammar, and has no thread-safety or asynchronous task management. It rejects server-initiated requests rather than handling them. The notification fixture deliberately tests the dispatch branch without checking the negotiated listChanged flag; a real client should respect feature-specific capability rules and treat unexpected messages according to its protocol policy. The later tools/call with empty parameters is also a synthetic error-classification fixture, not a valid real tool invocation. Responses are assumed to have the expected decoded types; malformed nested content can still raise errors. Production clients should validate complete message schemas before resolving requests, use bounded waits and complete pending callers with explicit failure on shutdown. The tests prove only the listed local behaviors, not real MCP conformance.
10. Connection lifetime and shutdown#
A client is usable only while its transport and protocol state support the requested operation. A host may choose task-scoped connections, longer-lived sessions or an SDK-supported reuse strategy. A client should track readiness and release resources when no longer needed.
An application shutting down a local stdio client should follow the SDK's documented cleanup procedure, close streams and terminate or reap its subprocess when appropriate. For remote Streamable HTTP deployments, follow the supported transport and session termination rules, including optional session termination behavior when applicable.
There is no universal guarantee that an interrupted connection can resume every previous operation. A new connection may require initialization and rediscovery. The client should clear or invalidate stale negotiated state and pending work as appropriate, rather than accidentally associating a previous response with a new connection.
A robust implementation communicates pending-request failures back to the host, allowing the application to distinguish unavailable data from an uncertain business operation. It must not silently drop a completed write or claim that closing the transport reversed it.
The local example models cleanup by returning abandoned IDs and clearing its map. A production SDK would usually resolve or fail associated futures/tasks and release the transport itself. Dedicated lifecycle and asynchronous client lessons cover those details.
11. Practical troubleshooting by layer#
Suppose the host cannot obtain stock for A12. Start by identifying the failing boundary.
| Observation | First investigation |
|---|---|
| Client cannot connect | Configured transport, process startup, endpoint or authentication |
| Initialization rejected | Supported revisions, message validity and capabilities |
| No tools discovered | Server tool capability, pagination, permissions and catalog filtering |
| Tool invocation rejected | Tool identity, input schema, access policy and business arguments |
| Unexpected response | Protocol correlation, message decoding or content validation |
| Valid result but wrong answer | Host result interpretation, freshness, model behavior or business data |
| Connection fails after a write | Authoritative operation status and safe reconciliation |
Do not start by changing the model prompt when the client is failing initialization. Conversely, a valid stock result delivered to the host does not prove that the model used it correctly.
Good tests isolate these layers. Test message processing with controlled fixtures, then exercise an actual compatible client and server in staging, then evaluate the host workflow and optional model. Record client version, negotiated revision, server identity and failure categories without logging credentials or sensitive business data.
12. Common misconceptions#
Is the MCP client the whole AI application? No. It is the protocol-facing component within or used by the host. A standalone CLI may implement both roles in one program.
Does every client support every server? No. Transport, revision, features, schemas and authorization must be compatible.
Does a client need a model API key? Not for ordinary model-free operations. Some server capabilities or client-supported features may require inference.
Does discovering a tool execute it? No. Discovery describes capabilities; invocation is a separate operation.
Does a successful response mean the business task completed? Not necessarily. Inspect protocol status, tool execution status and authoritative business results.
Does a notification always require a response? No. A JSON-RPC notification omits the request ID and does not receive a JSON-RPC response.
Interview-ready answer#
An MCP client is the protocol component a host uses to communicate with an MCP server. It establishes a supported transport, performs the applicable initialization and capability negotiation, discovers available tools, resources and prompts, sends approved requests, correlates responses by ID, handles supported notifications and server-initiated requests, preserves error information and manages the connection lifecycle. The host owns user interaction, consent, model integration and orchestration; the server owns capability execution and authoritative access controls. A client can operate without an LLM, and protocol compatibility must be established rather than assumed.
Next lesson: Q18 examines the MCP server: how it exposes capabilities, executes operations and connects the protocol boundary to underlying business services.
References
- 1.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 2.MCP architecturemodelcontextprotocol.io
- 3.MCP lifecyclemodelcontextprotocol.io
- 4.MCP transportsmodelcontextprotocol.io
- 5.MCP toolsmodelcontextprotocol.io
- 6.JSON-RPC 2.0jsonrpc.org
- 7.Official MCP Python SDKgithub.com
- 8.Official MCP TypeScript SDKgithub.com
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation