MCP: Model Context ProtocolBeginnerModule 03 — MCP messages and JSON-RPC

How does MCP correlate concurrent requests with their responses?

Question 28 of 43 · Updated

On this page

Direct answer#

MCP correlates concurrent requests and responses using JSON-RPC request IDs and trusted session context. When a participant issues a request, its implementation registers the identifier together with the expected operation and a pending completion object, such as a future or promise. When a response arrives, the receiver identifies the correct session and direction, validates the response and resolves the corresponding pending operation. Responses need not arrive in request order.

In the historical MCP 2025-06-18 specification, a request ID is a string or integer and must not be reused by the same requestor within the same session. A valid response to an identifiable request carries the matching ID. The protocol specifies these communication semantics; the pending registry, asynchronous scheduling and synchronization primitives are implementation choices.

The crucial invariant is that each pending request has at most one terminal local outcome. A successful response, error response, timeout, cancellation or connection failure may win that transition. A late or duplicate response must never resolve a different request.

Learning continuity: Q29 established identifier types, scope and allocation; Q33 established inbound validation. Q34 completes Module 03 by putting those rules into an asynchronous request manager. It focuses on the lifetime of an in-flight exchange, not the scheduling of independent business tools (Q112, Q132), session lifecycle (Q36–44), detailed cancellation (Q161–162), end-to-end deadlines (Q170) or business reconciliation (Q231).

Verification scope: Prepared under the authorized offline research and changelog exceptions. The historical MCP 2025-06-18 specification is the baseline, not a claim about the latest revision. Official references were not checked live. The Python 3.13.5 standard-library example was compiled and actually executed with asyncio debug mode enabled and warnings treated as errors. All 25 asynchronous correlation checks passed. It uses real tasks, futures and queues in one event loop, with simulated message delivery rather than a live MCP connection. The MCP Python SDK and Mermaid CLI were unavailable locally; actual SDK interoperability, network behavior, Mermaid parsing and page rendering remain unverified.

1. Why arrival order cannot be the correlation mechanism#

Imagine a retail support host submitting two independent inventory lookups. Request 1 concerns SKU A12, and request 2 concerns B34. The latter may finish first because its data is cached.

Loading diagram…

This is a conceptual exchange after the required initialization, assuming the applicable implementation can perform independent operations concurrently. The method names and business data are abstracted.

If a receiver simply assigns each arriving response to the earliest pending request, it may tell the user that A12 has B34's quantity. Correlation is about matching the correct operation, not predicting which operation finishes first.

An ordered transport such as a byte stream does not imply that application-level work completes in submission order. The transport may reliably deliver the bytes of response 2 before the bytes of response 1 because the server completed operation 2 first.

2. The pending-request registry#

A typical asynchronous implementation maintains a registry of locally originated requests awaiting terminal outcomes. Each entry contains enough trusted context to validate and complete that request.

Pending entry fieldPurpose
Request ID and typeIdentify the exact exchange
Connection/session ownershipPrevent cross-connection correlation
Original method and expected result contractValidate the corresponding response
Future, promise or completion callbackDeliver the outcome to the waiting caller
Deadline and local stateSupport timeout and cleanup
Optional progress associationLink progress events without resolving the request

Not every library exposes these fields to the application. An SDK may maintain them internally and return an awaitable result to the caller.

The conceptual lookup key is the trusted requestor/session scope plus the original typed ID. A registry dedicated to one outbound direction of one logical session can use the ID alone as its internal key because the surrounding object supplies the scope.

A global registry indexed only by integer ID is dangerous. Two separate clients may legitimately issue ID 1 to different servers, and the opposite direction of a bidirectional relationship can have an independent ID 1.

A pending registry is not an application transaction ledger. It is temporary communication state. It should not be relied on to recover the authoritative outcome of a committed order after a process crash.

3. Register before sending#

The normal lifecycle of a locally issued request is:

  1. Check the applicable lifecycle, negotiated capability and local concurrency budget.
  2. Allocate a previously unused ID for the relevant requestor/session.
  3. Create a completion object and retain the expected method contract.
  4. Register the pending entry before making the request visible to the peer.
  5. Send the message using the supported transport.
  6. Await the completion object within the applicable deadline.
  7. Release the pending entry and associated resources on every terminal path.

Registering after sending creates a subtle race. A local server might respond immediately while the sending coroutine yields control. The response reader would look up the ID before the pending entry exists and wrongly treat a valid response as unexpected.

If registration succeeds but sending fails, the request manager must also clean up. It should not leave an orphaned future waiting indefinitely. A failure during transmission may leave the actual remote outcome uncertain; a local exception alone does not prove that no request bytes reached the peer.

The request ID must not become reusable merely because the pending entry has been removed. As Q29 explains, historical MCP prohibits reuse within the same requestor/session. A monotonic allocator without wraparound or premature reset can satisfy this locally without retaining every completed future forever.

4. Futures and asynchronous scheduling#

An asyncio Future represents a completion that may not yet be available. One task can await the future while another task receives and processes messages. Resolving that future schedules the waiting task to resume.

A conceptual request manager therefore has two cooperating paths:

Sending pathReceiving path
Allocate IDRead bounded transport messages
Register pending futureParse and classify messages
Send requestIdentify response ID and expected contract
Await futureResolve matching pending future
Clean up in finallyReject unmatched or already completed messages

Do not make every caller independently consume the same underlying stream and assume it will receive its own response. A central reader or an equivalent transport-specific demultiplexer should route each validated message. Multiple readers of a single undemultiplexed stream can consume one another's responses.

Asyncio futures are not thread-safe. When all registry mutations run on one event loop, short synchronous sections without await can act as non-interleaving state transitions relative to other tasks on that loop. If transport callbacks arrive from another thread, marshal them into the owning loop using a supported thread-safe scheduling mechanism. For multi-threaded or distributed registries, use appropriate synchronization and ownership rather than assuming a Python dictionary alone supplies the required atomicity.

A future's completion is a local software event. It does not guarantee that the remote operation was executed successfully, that all returned data is authorized or that a business transaction committed. Q27 and Q32 explain the separate outcome and payload contracts.

5. Bidirectional requests on the same relationship#

Suppose an MCP client has an outstanding request with ID 1. A server-initiated ping with ID 1 may arrive while that request is pending.

JSON
{"jsonrpc":"2.0","id":1,"method":"ping"}

This is an incoming request, not the response to the client's outstanding request. It has a method and ID. The request dispatcher should process it according to the supported method and lifecycle rules, returning its own correlated reply.

A response to the client's original request might separately arrive as:

JSON
{"jsonrpc":"2.0","id":1,"result":{}}

The relevant original request context determines whether an empty result is valid. The ID alone does not establish the message category.

The implementation must classify the message before looking up the outbound pending registry. Supported notifications have no top-level ID, and their event-handling path should not resolve an unrelated future.

A related failure mode is reader deadlock: an incoming handler waits for a nested supported request to complete, but the only reader is blocked waiting for that handler to finish. If the reader cannot process the nested response, neither side can make progress. A production architecture must allow appropriate inbound request handling without blocking delivery of unrelated responses. Bound handler concurrency and follow applicable capability and lifecycle restrictions rather than assuming arbitrary nested requests are always allowed.

6. Terminal state transitions and races#

Loading diagram…

This is a conceptual local request-state model. These are not standardized MCP wire-level state names. A real implementation may use a future's completion state and additional local metadata rather than an explicit state enum.

For a successful result or error, validation and the final decision to complete a pending future must not be separated by an unprotected await that lets another path complete it. A timeout, cancellation or connection-close callback can otherwise race with the response handler.

RaceRequired local invariant
Two responses for the same requestOnly one may complete it
Timeout and response arrive togetherOnly one local terminal outcome is accepted
Response and connection closeClosure must not overwrite an already accepted completion
Cancellation and responseNo second completion; cleanup still occurs
Old reader callback after session replacementMust not resolve work in the new session

Exact precedence at a boundary depends on scheduling, timeout semantics and the implementation's defined policy. A response can win the registry's completion transition while its waiting caller is independently cancelled before consuming it. Do not promise that every caller observes the winning response in all scheduling situations.

When using asyncio, checking future.done() and calling set_result() in one synchronous event-loop-owned function prevents another asyncio task from interleaving between those operations. That is a property of the specific ownership model, not a general distributed atomicity guarantee.

7. Unknown, duplicate and late responses#

An unknown response ID may result from a peer defect, an invalid message, a stale callback or an operation that already terminated locally. The response manager should not guess which other request it was intended for.

A duplicate response may arrive before the completed entry is removed, so the registry must recognize that a future is already done. It may also arrive after cleanup, in which case the identifier is absent from the active registry.

Both situations should prevent a second completion.

A late response after a timeout is not necessarily malicious. The server may have finished its work after the local deadline. The receiver can record an appropriate sanitized diagnostic and follow the application contract, but it must not deliver the response to a new request.

If operations need a detailed distinction between unknown, duplicate and late IDs, a bounded diagnostic tombstone cache may help. Tombstones are not a substitute for non-reuse of IDs. Unbounded retention of every historical response is not necessary for basic safety and can create a memory problem.

8. Timeouts, cancellation and the meaning of uncertainty#

A timeout establishes that the local caller did not obtain a usable outcome within its configured waiting policy. It does not prove that the server failed to execute the operation.

Local cancellation, such as cancelling an asyncio Task, ends that local waiting relationship and should release resources. Actual MCP request cancellation is a separate protocol action. In the historical baseline, the notification method notifications/cancelled can reference an applicable earlier request through params.requestId. The sender must follow the applicable lifecycle and cancellation rules. Sending the notification does not guarantee that remote work has stopped, and it cannot roll back a committed transaction by itself.

For example, if a stock reservation request times out, a host cannot safely assume that the inventory is unchanged. It may need to query authoritative status or use an explicitly supported idempotency contract. A newly issued request needs a fresh protocol ID within the existing sender/session scope, even if the same business idempotency key is legitimately reused.

End-to-end deadline allocation, sending cancellation notifications, retry classification and uncertain business outcomes are developed in later dedicated lessons. Here the important point is that local registry cleanup and remote execution control are separate responsibilities.

9. Connection cleanup and session replacement#

When a connection fails or a logical session is terminated, its pending operations must not remain unresolved indefinitely. Stop admitting new requests, notify or cancel affected waiters using controlled local failure semantics, clean up the transport and prevent stale callbacks from reaching replacement state.

A physical connection change is not automatically a new logical MCP session. Follow the applicable transport and lifecycle semantics. If the implementation genuinely replaces a session, its reader and registry should be bound to the new session identity, and old callbacks must remain scoped to the old one.

In a host with independent inventory and policy connections, closing the inventory session should not fail policy futures unless both depend on a shared failure domain. Failure scope is an architectural property, not a guarantee that every separate connection is physically isolated.

Cleanup also includes tasks that own streams or run inbound handlers. Do not simply drop references to active futures while leaving their waiting tasks and transport resources alive. Define ownership, shutdown ordering and exception propagation explicitly.

10. Bounded concurrency and backpressure#

Asynchronous code allows many operations to wait concurrently, but unlimited outstanding requests consume memory and potentially overload the peer.

For example, with a local pending limit of 32, a request manager can reject or queue further work after the limit is reached. If queuing is chosen, the queue itself must be bounded and its waiting time must be included in the applicable deadline policy.

PolicyBenefitTrade-off
Reject when fullPredictable admission and bounded pending stateCaller must handle overload
Bounded wait queueAbsorb short burstsQueue delay and fairness must be managed
SemaphoreSimple bound on admitted operationsWaiting tasks can still grow without separate admission limits
Adaptive limitsMay respond to measured dependency healthMore complexity and tuning

A pending limit bounds one dimension of work, not the entire application. Bound response sizes, outbound buffers, notification work, inbound requests, downstream calls and model usage as appropriate.

Average pending registry lookup is typically constant time with a hash map; memory grows with the number and size of admitted entries. Actual throughput depends on the transport, server handlers, downstream services and workload. Concurrency cannot make an inherently dependent workflow independent.

11. Tested Python example: correlate real asynchronous tasks#

The following Python 3.10+ standard-library example uses real asyncio tasks, futures and queues. Peer is a deliberately restricted request manager for one logical outgoing sender scope. A queue stands in for an outbound transport, and the test manually delivers already decoded response fixtures.

The fictitious demo methods and string-valued result fixtures illustrate internal correlation mechanics; they are not standardized MCP methods or conformant MCP result objects. The receive function assumes that a trusted reader has already validated the actual session, version and method-specific response schema. It makes only the minimal additional classification and matching checks needed for this exercise.

Save as mcp_q34.py:

PYTHON
import asyncio class Busy(Exception): pass class RpcError(Exception): pass class Peer: def __init__(self, limit=2): self.limit = limit self.pending = {} self.next_id = 0 self.closed = False self.sent = asyncio.Queue() async def call(self, method, timeout=1): if self.closed: raise ConnectionError('Closed') if len(self.pending) >= self.limit: raise Busy('Pending limit') self.next_id += 1 rid = self.next_id fut = asyncio.get_running_loop().create_future() self.pending[rid] = fut try: self.sent.put_nowait({'jsonrpc': '2.0', 'id': rid, 'method': method}) status, value = await asyncio.wait_for(fut, timeout) if status == 'closed': raise ConnectionError('Closed') if status == 'error': raise RpcError(value['code']) return value finally: self.pending.pop(rid, None) if not fut.done(): fut.cancel() def receive(self, msg): # Called by the trusted, validated reader for this session. if self.closed or 'method' in msg or type(msg.get('id')) is not int: return False if ('result' in msg) == ('error' in msg): return False fut = self.pending.get(msg['id']) if fut is None or fut.done(): return False branch = 'result' if 'result' in msg else 'error' fut.set_result((branch, msg[branch])) return True def close(self): self.closed = True for fut in self.pending.values(): if not fut.done(): fut.set_result(('closed', None)) def result(rid, value): return {'jsonrpc': '2.0', 'id': rid, 'result': value} async def fails(task, expected): try: await task except expected: return raise AssertionError('Expected failure') async def main(): a, b = Peer(), Peer() t1 = asyncio.create_task(a.call('demo/first')) r1 = (await a.sent.get())['id'] t2 = asyncio.create_task(a.call('demo/second')) r2 = (await a.sent.get())['id'] t3 = asyncio.create_task(b.call('demo/other')) r3 = (await b.sent.get())['id'] assert r1 == r3 and r1 != r2 await fails(a.call('demo/excess'), Busy) assert not a.receive({'jsonrpc': '2.0', 'id': r1, 'method': 'ping'}) assert not a.receive(result(str(r1), 'wrong type')) assert not a.receive(result(999, 'unknown')) assert not a.receive({**result(r1, "ambiguous"), "error": {}}) assert a.receive(result(r2, 'second')) assert not a.receive(result(r2, 'duplicate')) assert await t2 == 'second' and not t1.done() and not t3.done() assert b.receive(result(r3, 'other')) and await t3 == 'other' assert a.receive(result(r1, 'first')) and await t1 == 'first' assert not a.pending and not b.pending t4 = asyncio.create_task(a.call('demo/error')) r4 = (await a.sent.get())['id'] assert a.receive({'jsonrpc': '2.0', 'id': r4, 'error': {'code': -32603, 'message': 'Internal error'}}) await fails(t4, RpcError) t5 = asyncio.create_task(a.call('demo/timeout', timeout=0.01)) r5 = (await a.sent.get())['id'] await fails(t5, TimeoutError) assert not a.pending and not a.receive(result(r5, 'late')) t6 = asyncio.create_task(a.call('demo/cancel')) r6 = (await a.sent.get())['id'] t6.cancel() await fails(t6, asyncio.CancelledError) assert not a.pending and not a.receive(result(r6, 'late')) t7 = asyncio.create_task(a.call('demo/response-wins')) r7 = (await a.sent.get())['id'] assert a.receive(result(r7, 'accepted')) a.close() assert await t7 == 'accepted' and not a.pending await fails(a.call('demo/closed'), ConnectionError) t8 = asyncio.create_task(b.call('demo/close-wins')) r8 = (await b.sent.get())['id'] t9 = asyncio.create_task(b.call('demo/also-close')) r9 = (await b.sent.get())['id'] b.close() assert not b.receive(result(r8, 'late')) and not b.receive(result(r9, 'late')) await fails(t8, ConnectionError) await fails(t9, ConnectionError) assert not b.pending print('25 asynchronous correlation checks passed') if __name__ == '__main__': asyncio.run(main())

Run without Python's optimization flag so that assertions remain enabled:

BASH
python -m py_compile mcp_q34.py PYTHONASYNCIODEBUG=1 python -W error mcp_q34.py

Actual local output on Python 3.13.5:

25 asynchronous correlation checks passed

What the tests establish#

The first twelve check statements cover independent ID scopes, admission limits, rejecting an inbound request as a response, type-sensitive ID matching, unknown IDs, ambiguous outcome branches, out-of-order completion, duplicate rejection, isolation of waiting tasks, correct independent-session completion and successful cleanup.

The next six checks cover the correlated RPC error, actual timeout and task cancellation, including late-response rejection and empty pending registries. The final seven checks cover response-first closure, rejection of a new request after closure, close-first failure for two outstanding tasks, rejection of their late responses, and cleanup.

The tests use queue reads to wait until each request is registered and sent to the simulated transport. This is more deterministic than guessing a sleep duration to assume that an operation is ready. The timeout case actually waits for asyncio.wait_for to time out. The cancellation case invokes Task.cancel() and awaits the resulting CancelledError. The two close-order cases explicitly exercise both sequences of local state transitions; they are not exhaustive race-condition stress tests.

The receive and close methods contain no await, so their future-completion checks and transitions do not interleave with another task on the same owning loop. The pending entry remains present until the caller's finally block runs, and the done guard prevents duplicate resolution during that interval. The finally block releases the entry on all demonstrated exits.

Using a tagged completion tuple allows close to wake waiting tasks without setting an unobserved exception directly on a future. The caller interprets the tagged outcome and raises an appropriate local exception. A real SDK may use different mechanisms.

Deliberate limitations#

This is an in-memory teaching fixture, not a complete MCP client, server or transport. The queue is unbounded and the pending limit bounds admitted request entries only. A production implementation must bound outbound buffering independently and define transport send failure handling. The example does not run a background transport reader or send cancellation notifications, parse raw JSON, authenticate the sender, enforce negotiated capabilities, validate complete result schemas, handle notifications or implement actual inbound ping processing. The ping check merely verifies that method-bearing messages are not treated as responses.

The fixture uses integer IDs generated by a monotonically increasing counter and assumes small safe values. Real interoperability requires suitable numeric limits or strings. It does not test thread safety, shared-process ownership, arbitrary task scheduling races, network fragmentation, reconnect behavior, actual remote cancellation, send failure or business idempotency. It models independent sessions using separate Peer objects and assumes trusted routing to the correct one.

The tests run genuine asynchronous Python tasks, not a live SDK integration. Production code should use a compatible official MCP SDK and exercise its actual concurrency, timeout and connection semantics with the chosen transport.

12. Production checklist and common mistakes#

MistakeCorrective principle
Match by response arrival orderMatch typed ID in the correct trusted scope
Register only after sendRegister before the peer can respond
Treat any matching ID as a responseClassify requests, notifications and responses first
Resolve a future twicePerform a guarded terminal transition
Reset counters on a transient reconnectPreserve non-reuse until a genuinely new session is established
Remove registry entries only on successClean up on every terminal exit
Treat timeout as proof of rollbackReconcile authoritative business state when necessary
Let a reader wait indefinitely on nested handlersPreserve progress of response dispatch with bounded handler execution
Bound pending futures but not queued workBound all admission and buffer dimensions

In production, measure in-flight count, admission rejections, response latency, local timeout rate, cancellation rate, unexpected response rate and close-induced failures. Keep protocol failures separate from domain rejection and tool execution failures. Avoid logging private arguments or credentials merely to investigate request correlation.

For integration tests, exercise the actual selected SDK and transport with out-of-order completions, interleaved incoming requests and notifications, duplicate and malformed messages, cancellation, deadlines, resource limits and connection replacement. Validate real cleanup and ensure that stale work cannot cross a session or authorization boundary.

Interview-ready answer#

MCP uses JSON-RPC request IDs to correlate responses with their original requests, independently of arrival order. An asynchronous implementation typically registers a pending future and expected method contract before sending each request. The response reader classifies the message, checks the trusted session and direction, matches the typed ID, validates the result or error and resolves only the corresponding future. Timeout, cancellation, response and close paths must coordinate so that a pending operation has at most one terminal local outcome. Late and duplicate responses cannot complete another request; IDs are not reused in the same historical MCP requestor/session scope. Bounded concurrency and cleanup prevent resource leaks. The mechanism correlates communication, not business transactions or exactly-once execution.

Module 03 transition: This completes the eligible message and JSON-RPC lessons, from why JSON-RPC is used through envelope contracts, notifications, IDs, dispatch, errors, payload boundaries, validation and concurrent correlation. Q36 starts Module 04 by examining the initialize exchange in session-oriented MCP revisions.

References

  1. 1.
  2. 2.
  3. 3.
    MCP base protocolmodelcontextprotocol.io
  4. 4.
    MCP lifecyclemodelcontextprotocol.io
  5. 5.
    MCP transportsmodelcontextprotocol.io
  6. 6.
    MCP cancellationmodelcontextprotocol.io
  7. 7.
  8. 8.
    Python asyncio tasksdocs.python.org
  9. 9.
    Python asyncio futuresdocs.python.org
  10. 10.
    Python asyncio queuesdocs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation