MCP: Model Context ProtocolBeginnerModule 02 — MCP architecture and components
How does an MCP host isolate client connections and capabilities across servers?
Question 16 of 43 · Updated
On this page
- Direct answer
- 1. Why multi-server isolation matters
- 2. Dedicated logical client connections
- 3. What information belongs to a connection scope?
- 4. Session isolation and request correlation
- 5. Capability boundaries and server-specific routing
- 6. Credential isolation
- 7. Context separation and controlled information flow
- 8. Failure containment and lifecycle isolation
- 9. Tested Python example: isolate connection state and disclosure
- 10. How to apply this design with an MCP SDK
- 11. Common mistakes and practical tests
- Interview-ready answer
Direct answer#
An MCP host isolates its integrations by maintaining a separate logical client connection for each server relationship and keeping the connection's negotiated capabilities, pending requests, authorization context and lifecycle state associated with that relationship. When the host exposes a capability to a model or workflow, it preserves the trusted identity of the server that owns it. A request intended for one server must not accidentally execute on another server, use another server's credentials or receive a response from a different connection.
The historical session-oriented MCP architecture describes a host managing multiple clients, with each client maintaining a dedicated connection to a server. This provides a useful architectural boundary, but a connection alone is not a complete security sandbox. The host must enforce identity-scoped routing, permissions, context disclosure and failure containment. The server and downstream services must independently authorize their actual resources and operations.
Learning continuity: Q16, Q17 and Q18 introduced the host, client and server respectively. This lesson examines what must stay separate when a single host connects to several servers. It does not repeat the general LangChain integration setup or implement the advanced alias-generation and immutable registry designs reserved for Q127–128. Q22 will examine the division of consent, context and execution decisions between the host and servers.
Verification scope: Prepared under the authorized offline research and changelog exceptions, using MCP 2025-06-18 as a historical specification baseline, not a claim about the latest revision. Official links were not opened live. The standard-library Python example was syntax-compiled and executed locally using Python 3.13.5; all 14 checks passed. It models logical isolation with trusted in-memory objects, not a complete MCP client or real security boundary. The local MCP SDK and Mermaid CLI were unavailable; SDK interoperability, network and process isolation, and Mermaid parser/frontend rendering were not verified.
1. Why multi-server isolation matters#
Imagine that the retailer's support host connects to three independent integrations:
| Server | Capability | Intended information |
|---|---|---|
| Inventory | stock | Product availability |
| Policy | search | Approved retail policy documents |
| Customer accounts | lookup | Authorized customer records |
The host can combine these capabilities to answer a support question. However, permission to check stock does not grant permission to read a customer record. Nor does reading a private customer record authorize forwarding it to the policy-search server.
If the host puts every connection, credential and result into one undifferentiated global object, several problems become possible:
- A tool intended for one server is routed to a similarly named tool on another server.
- A response from one connection is mistaken for a response from another.
- Credentials intended for one service are sent to the wrong destination.
- A cached resource or tool catalog is reused under a different user's identity.
- Private information retrieved from one server is disclosed to an unrelated integration.
- Failure of a nonessential server unnecessarily stops every other connection.
Isolation is therefore both a correctness requirement and a security design requirement. The aim is not to forbid all cross-server workflows. It is to ensure that any coordination is deliberate, authorized and traceable.
2. Dedicated logical client connections#
Each client-server relationship has its own relevant protocol state. The host acts as the coordinator. Servers do not automatically obtain access to the other servers, their credentials or the host's entire conversation.
The boxes represent logical scopes. They do not imply that every client must run in a separate process or use a dedicated physical TCP socket. HTTP connection pooling, session behavior and local subprocess lifetimes depend on the transport, SDK and specification revision. A server deployment may serve multiple compatible clients.
In the historical 2025-06-18 architecture, a host creates and manages multiple clients, and each client maintains a dedicated connection to one server. Later protocol and SDK designs may represent lifecycle differently; the application should preserve equivalent isolation appropriate to its actual supported implementation.
Separate logical clients are necessary for correct message association in this architecture, but they are insufficient to contain malicious code running with broad operating-system permissions.
3. What information belongs to a connection scope?#
A useful beginner model is to associate state with the server's trusted configuration identity, the authenticated authorization context and the current connection instance.
| State | Why keep it scoped? |
|---|---|
| Transport and session handle | Prevent messages from being sent through an unrelated connection |
| Negotiated protocol revision | Use the rules appropriate to that server relationship |
| Advertised features | Do not assume that features available on one server exist on another |
| Discovered tool, resource and prompt metadata | Preserve the source and current capability contract |
| Outstanding requests | Correlate responses with the correct operation |
| Credentials or protected credential references | Prevent use at an unintended audience or destination |
| Cache entries | Avoid stale or cross-user discovery and result reuse |
| Timeout and health state | Recover or disable the affected connection independently |
A connection scope is an application design concept, not a standardized MCP field. A host might use an internal key consisting of integration ID, authenticated principal, tenant or authorization context, and a locally generated connection generation.
Use a stable trusted integration identifier rather than a display name supplied by a server. If a connection is replaced, allocate a new local generation or equivalent identity. Do not rely on a server's name, a URL alone or a bare JSON-RPC ID as proof that two relationships are identical.
A generation is especially useful when old callbacks, pending tasks or cached data may survive reconnection. It is not the same as a protocol session identifier. A host must handle applicable protocol identifiers using the rules of the selected transport and revision.
4. Session isolation and request correlation#
In Q17, we saw why a client maintains a pending-request map. When multiple clients exist, the maps must not be merged under request ID alone.
For example, both the inventory client and the policy client may send a request with numeric ID 1 in their respective independent sessions. This is not inherently a conflict. The responses are associated with different client-server relationships.
The diagram illustrates separate historical sessions, not two requests reusing an ID within a single session. IDs need to satisfy the applicable specification's uniqueness and correlation requirements within their scope.
The two responses can arrive in either order. The inventory response must resolve the inventory client's pending operation, and the policy response must resolve the policy client's operation. A response from a retired connection instance must not accidentally complete a new operation that happens to reuse a numeric ID.
The client should obtain message origin from the actual trusted transport or session association. A field inside an untrusted response claiming to be from a particular server is not evidence of its origin.
If an SDK already maintains an independent request manager for each client, use that abstraction rather than creating another global ID map that removes the separation.
5. Capability boundaries and server-specific routing#
A host may aggregate capabilities for a model-facing interface, but aggregation must preserve ownership. For example, two servers could both expose a tool named search, one searching public policy documents and another searching confidential customer records.
The bare name search is not a globally unique business operation. The host needs to associate each model-facing capability with the correct configured server, actual operation name and supported schema. It can use distinct model-facing names or application-issued identifiers, but the mapping must come from trusted configuration and approved discovery, not from arbitrary model-generated server URLs or credentials.
A simple conceptual binding is:
- Integration: approved policy server.
- Server operation: search.
- Expected input: query text.
- Authorized actor: current support user.
- Current connection: policy client for this authorization context.
The host validates an invocation against this binding, while the server independently validates the operation and resource. An operation should become unavailable when its required connection is closed, its permission is revoked or its advertised contract is no longer supported.
This is distinct from the advanced registry design in later lessons. Here the key invariant is that the host must not lose the capability's server and identity association when it presents tools to a shared model.
Consider the following examples:
| Situation | Correct behavior |
|---|---|
| Inventory server supports stock but not search | Do not dispatch search to that connection |
| Two servers advertise search | Preserve separate bindings even if their descriptions are similar |
| Resource URI appears on different servers | Preserve server identity and URI together |
| Server advertises new operations | Reevaluate eligibility before exposing them |
| Tool removed or server disabled | Remove or invalidate the affected model-facing binding |
Discovery and authorization remain separate. A server may advertise a capability that the current user cannot execute.
6. Credential isolation#
Credentials are not part of a shared model context. A host should resolve them through trusted application code and configure them only for their intended server relationship.
For remote HTTP deployments using the applicable historical OAuth authorization framework, access tokens must be suitable for the intended protected resource. Validate the server identity and transport security, follow the applicable resource and authorization metadata mechanisms, and avoid sending a token intended for server A to server B.
Different integrations may use different authentication mechanisms. Even when a shared identity provider is used, the token audience, scopes and actual resource authorization must be appropriate. A token being valid for one resource does not make it valid everywhere.
For local stdio integrations, avoid passing the entire host environment to every process when only a small set of values is needed. Use an approved executable and constrained environment, filesystem and network permissions. A local server can potentially access anything permitted by its operating-system identity; separate client objects do not sandbox a malicious process.
Credential references are useful because routing metadata can identify which protected credential should be resolved without embedding the actual secret in model-visible descriptions or results. A production credential manager must enforce access to those references.
For shared multi-user hosts, distinguish an application workload identity from user-delegated authorization. Reusing an underlying connection or client session across users is appropriate only if its identity and state semantics safely support that design. A pool must not hand one user's authenticated state to another user.
Q4 covered authentication and credential policy in detail. The specific point here is that every client must retain its intended credential and authorization association throughout the connection lifecycle.
7. Context separation and controlled information flow#
Servers do not automatically receive the entire model context merely because the host connects to them. An ordinary tool invocation carries the operation's relevant parameters and applicable protocol information. The host decides which data is supplied.
Suppose the customer accounts integration returns a private address, and the inventory integration needs only a product SKU. The host should not include the customer's address in the stock lookup merely because it is available in the conversation.
Likewise, a document returned by the policy server may contain instructions telling the assistant to retrieve and transmit customer data. Such text is untrusted content. It cannot authorize a call to the customer accounts server or change the destination's disclosure policy.
A practical host tracks:
- Which integration produced the information.
- Which authenticated user or tenant the information belongs to.
- What classification or disclosure policy applies.
- Which destination and task are allowed to receive it.
- Whether the information remains relevant, fresh and authorized.
The same considerations apply to a model provider as a destination. Authorization to retrieve a record is not necessarily authorization to disclose it to that provider.
When using supported sampling or other server-initiated requests, apply the applicable negotiated capability rules and explicit host policy. Do not infer that one server can see another server's results or the entire conversation simply because it requested model generation.
Context separation does not require forbidding legitimate cross-server workflows. For instance, a host can retrieve an approved product identifier from an order and pass that identifier to an inventory service if the transfer is authorized and necessary. The host mediates the transfer and shares only what is needed.
8. Failure containment and lifecycle isolation#
Suppose the inventory server becomes unavailable while the policy server is healthy. The host should associate the failure with the affected connection rather than automatically destroying the entire application's ability to communicate with every other service.
| Failure event | Scoped response |
|---|---|
| One subprocess exits | Mark that integration unavailable and clean up its pending requests |
| One remote session expires | Follow the supported reconnection or reinitialization procedure |
| One capability changes | Refresh or invalidate that integration's catalog |
| One credential expires | Refresh or reauthorize the affected relationship where supported |
| A user signs out or loses permissions | Invalidate affected authorization state and prevent further access |
| A server returns invalid or oversized content | Reject or contain the affected operation and report the problem |
Partial availability is not always enough to finish a task. If a user asks whether a product is available and returnable, the host may still explain the verified return policy while noting that current stock could not be checked. If both pieces of evidence are required for a purchase, the host should not claim that the whole purchase is possible.
When an interrupted operation has side effects, a timeout is not evidence that the write never happened. The host should report uncertainty and use an authoritative status or reconciliation mechanism, not automatically retry an uncertain write.
Resource isolation matters as well. Per-integration timeouts, bounded concurrency, queue limits and separate health state can reduce the chance that a slow dependency exhausts all host resources. Shared infrastructure and dependencies can still create common failure domains. Logical client separation is not a guarantee of high availability.
9. Tested Python example: isolate connection state and disclosure#
The following standard-library exercise focuses on three architectural invariants:
- Pending requests belong to a particular connection instance.
- Closing one client does not close another client or expose its capabilities.
- Information may cross a destination boundary only when the application has granted that disclosure.
It is not an MCP SDK implementation, a network connection pool or a production authorization system. The Scope object models trusted application metadata for the demonstration. The actor field is a fictional authenticated identity, and the generation is a host-local connection identity, not an MCP session ID. Credential references are invented labels, not real secrets. The receive method assumes that origin is supplied by trusted transport association, never by arbitrary response data.
Save as mcp_q21.py:
PYTHONfrom dataclasses import dataclass, field @dataclass(frozen=True) class Scope: server: str actor: str generation: int @dataclass class Connection: scope: Scope capabilities: frozenset[str] credential_ref: str pending: dict[int, str] = field(default_factory=dict) next_id: int = 1 ready: bool = True def start(self, tool): if not self.ready or tool not in self.capabilities: raise PermissionError('Unavailable capability') request_id = self.next_id self.next_id += 1 self.pending[request_id] = tool return request_id def receive(self, origin, request_id): if not self.ready or origin != self.scope or request_id not in self.pending: raise ValueError('Unexpected response') return self.pending.pop(request_id) def disconnect(self): self.ready = False abandoned = tuple(self.pending) self.pending.clear() return abandoned @dataclass(frozen=True) class Evidence: origin: Scope value: str def disclose(evidence, destination, grants): if (evidence.origin, destination) not in grants: raise PermissionError('Disclosure not allowed') return evidence.value def rejects(fn, error): try: fn() except error: return raise AssertionError('Expected rejection') if __name__ == '__main__': inv = Scope('inventory', 'user-A', 1) policy = Scope('policy', 'user-A', 1) a = Connection(inv, frozenset({'stock'}), 'inventory-key-ref') b = Connection(policy, frozenset({'search'}), 'policy-key-ref') i, j = a.start('stock'), b.start('search') assert i == j == 1 assert a.pending is not b.pending assert a.credential_ref != b.credential_ref rejects(lambda: a.start('search'), PermissionError) rejects(lambda: a.receive(policy, i), ValueError) assert a.receive(inv, i) == 'stock' and j in b.pending rejects(lambda: a.receive(inv, i), ValueError) k = a.start('stock') assert a.disconnect() == (k,) and not a.pending assert b.ready and b.receive(policy, j) == 'search' rejects(lambda: a.start('stock'), PermissionError) renewed = Connection(Scope('inventory', 'user-A', 2), a.capabilities, a.credential_ref) n = renewed.start('stock') rejects(lambda: renewed.receive(inv, n), ValueError) rejects(lambda: renewed.receive(Scope('inventory', 'user-B', 2), n), ValueError) fact = Evidence(inv, '7 units') grants = {(inv, 'model-approved')} assert disclose(fact, 'model-approved', grants) == '7 units' rejects(lambda: disclose(fact, 'policy-server', grants), PermissionError) print('14 isolation checks passed')
Run with Python 3.10 or later:
BASHpython -m py_compile mcp_q21.py python mcp_q21.py
Actual local output on Python 3.13.5:
14 isolation checks passedThe tests cover overlapping numeric request IDs, independent pending maps, distinct credential-reference labels, capability rejection, wrong-server response rejection, correct response association, duplicate rejection, disconnect cleanup, continued operation of the other connection, refusal after closure, stale-generation response rejection, wrong-actor response rejection, permitted disclosure and denied disclosure.
The example does not prove that two real credentials are securely isolated. The test checks only that the fixture labels differ. Similarly, the scope comparison tests logical response association; it does not authenticate a network peer or validate actual JSON-RPC response messages.
The disclosure grant is intentionally simple. It permits a previously retrieved fact to be shared with an explicitly approved destination in this fixture even after the source connection closes. In a real system, disclosure must also consider current identity and permission, freshness, revocation, data classification, destination trust and task scope. Connection closure does not necessarily invalidate every previously retrieved fact, but neither does a previous grant justify unlimited later use.
Production limitations: The sample objects are mutable except for Scope and Evidence. It assumes trusted callers, unique generation assignment and valid request-ID types. It has no concurrency control, secure credential storage, actual transport, token validation, capability schema validation, dynamic catalog handling, timeouts, resource sandbox, or server-side authorization. It returns abandoned IDs instead of failing real pending asynchronous callers. Do not deploy it as a security boundary. A real application should use compatible SDK-managed client sessions and independently enforce the relevant application controls.
10. How to apply this design with an MCP SDK#
When using an actual MCP SDK, retain a client or session handle per approved integration and authorization context as appropriate. Let the SDK handle its supported initialization, message routing and transport mechanics. Do not merge those session objects into a single unscoped protocol state.
The host typically keeps trusted connection configuration separate from model-facing capability descriptions. It obtains metadata through the appropriate session, constructs approved bindings and calls the correct session's invocation method. For supported catalog-change events, it invalidates the affected bindings rather than blindly refreshing unrelated integrations.
When a session closes, remove or disable the routes tied to it and release its resources. If it reconnects, establish the applicable lifecycle state, verify the identity and permissions, and rebuild or validate the affected metadata. Avoid carrying over an old pending-request map.
The exact session APIs differ between SDKs and versions. This lesson intentionally does not provide an unverified SDK API signature; Q105–113 address concrete client construction and lifecycle management. Use the official Python or TypeScript SDK for the selected revision and test the actual combination of host, SDK, transport and server.
11. Common mistakes and practical tests#
| Mistake | Why it is dangerous | Better design |
|---|---|---|
| One pending-request dictionary keyed only by ID | Independent sessions can reuse IDs | Keep correlation state per client instance |
| One global tool dictionary keyed only by tool name | Names may collide across integrations | Preserve trusted server ownership |
| Forwarding a shared access token to every server | Wrong audience or excessive privileges | Resolve appropriate credentials per relationship |
| Sharing a cache across users without identity scope | May disclose private catalogs or results | Scope cache and invalidation to authorization context |
| Treating every server result as an instruction | External content can manipulate later actions | Treat it as data; enforce policy outside the model |
| Assuming local subprocesses are automatically sandboxed | They may inherit broad OS access | Apply process and environment isolation |
| Reusing connection state after a disconnect | Old responses or metadata may become invalid | Reinitialize and invalidate affected state |
| Stopping all integrations after one optional service fails | Creates unnecessary loss of availability | Contain failures and evaluate task dependencies |
For a production test plan, simulate simultaneous calls across two real supported sessions, overlapping IDs, changed capabilities, permission revocation, connection replacement and one-server failure. Test unauthorized disclosures and cross-user access independently, including the authoritative server-side checks. Add integration tests for actual authentication and the selected transport.
Observe sanitized server identity, connection instance, error category and operation correlation in diagnostics. Never log raw credentials or unrestricted private result payloads just to make debugging easier.
Interview-ready answer#
An MCP host manages separate logical client relationships with its configured servers. Each relationship retains its own negotiated features, pending requests, authorization context, capability catalog and lifecycle state. The host exposes capabilities through trusted server-specific bindings, keeps credentials scoped to their intended resources, mediates cross-server and model-facing data disclosure, and contains connection failures where possible. It must invalidate stale connection state and avoid cross-user session or cache reuse. These architectural boundaries reduce accidental mixing, but do not automatically provide OS sandboxing, tenant authorization or network security. Those controls must be implemented and tested at the host, server and downstream service boundaries.
Next lesson: Q22 examines how to divide consent, context and execution responsibilities between hosts and servers, including why neither side can rely on the model as an authorization authority.
References
- 1.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 2.MCP architecturemodelcontextprotocol.io
- 3.MCP lifecyclemodelcontextprotocol.io
- 4.MCP transportsmodelcontextprotocol.io
- 5.MCP authorizationmodelcontextprotocol.io
- 6.MCP security best practicesmodelcontextprotocol.io
- 7.MCP toolsmodelcontextprotocol.io
- 8.JSON-RPC 2.0jsonrpc.org
- 9.Official MCP Python SDKgithub.com
- 10.Official MCP TypeScript SDKgithub.com
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation