MCP: Model Context ProtocolBeginnerModule 04 — MCP protocol lifecycle
How should clients gate individual MCP methods on negotiated server capabilities?
Question 34 of 43 · Updated
On this page
- Direct answer
- 1. Map the exact method, not the namespace prefix
- 2. Optional flags change individual interactions
- 3. Gate on the accepted revision and ready relationship
- 4. The outbound enforcement boundary
- 5. Store immutable capability evidence per session
- Avoid a check-to-send race
- 6. Worked scenario: subscription versus fresh read
- 7. Treat local rejection differently from remote failure
- 8. Tested Python implementation: session-scoped outgoing method gate
- Test coverage
- Limitations and production adaptation
- 9. Practical engineering checks
- Interview-ready answer
Direct answer#
An MCP client should gate each outgoing operation against an explicit method-to-capability contract for the accepted protocol revision and the particular server relationship. Before dispatching, it checks the method's direction, lifecycle readiness, required capability family, any required optional flag, current trusted route, method-specific parameters and independent application authorization.
For example, in historical MCP 2025-06-18, resources/read requires the server's resources capability, whereas resources/subscribe additionally requires resources.subscribe support. A resources object with listChanged true does not establish subscription support. Conversely, tools/list does not require tools.listChanged: a server advertising {"tools":{}} supports the base tools family without claiming catalog change notifications.
The client should reject unsupported operations locally rather than probe arbitrary methods, fabricate support or rely on a server error as ordinary feature detection. The server still independently validates and authorizes every actual request.
Learning continuity: Q39 interprets the declarations; Q40 establishes lifecycle readiness. This lesson converts the accepted server declaration into a method-level outbound admission decision, distinct from Q30's receiver-side dispatch and Q33's general message validation. Q107 will implement the equivalent checks with a compatible real SDK; Q199 tests negotiation, Q279 develops degradation strategies, and Q128 covers trusted multi-server tool routing.
Verification scope: Authorized offline research and changelog exceptions apply. The reference baseline is historical MCP 2025-06-18, not the latest specification. Official links and later revision behavior were not verified live. Python 3.13.5 syntax compilation and unittest execution with warnings treated as errors passed all 16 tests. The code is an in-memory outbound admission fixture, not an MCP SDK or transport. Neither the MCP SDK nor Mermaid CLI was available locally; actual interoperability and diagram/frontend rendering are unverified.
1. Map the exact method, not the namespace prefix#
Build a reviewed rule registry for the revision the client implements. The following matrix covers selected client-to-server request methods in the historical baseline.
| Method | Required server family | Additional capability flag |
|---|---|---|
| tools/list, tools/call | tools | None |
| resources/list, resources/templates/list, resources/read | resources | None |
| resources/subscribe, resources/unsubscribe | resources | subscribe = true |
| prompts/list, prompts/get | prompts | None |
| logging/setLevel | logging | None |
| completion/complete | completions | None |
| ping | No optional server family | None |
This is a selected request-method matrix, not a complete grammar of every valid protocol message. For completion/complete the referenced prompt or resource template and argument must also be valid and accessible under the applicable contract. A resource unsubscribe additionally needs the correct subscription context. The matrix is not a substitute for checking parameters, catalog entries or active subscriptions.
Initialization, notifications, responses and cancellation have their own lifecycle and association rules. They are not ordinary capability calls. Do not add initialize to the ready-only dispatcher and require an already initialized session in order to initialize it.
Historical server-to-client sampling/createMessage, roots/list and elicitation/create depend on the relevant client features. They are not requests that this client-to-server table should authorize. Direction is a separate rule.
A registry keyed by exact strings prevents accidental support for an invented method such as tools/delete. Having tools support does not mean every method beginning with tools/ is available.
2. Optional flags change individual interactions#
Suppose the negotiated server capabilities are:
JSON{ "tools": {}, "resources": { "subscribe": false, "listChanged": true } }
Assuming a ready session and independently valid, authorized inputs:
| Candidate interaction | Decision |
|---|---|
| tools/list | Base family available |
| tools/call | Base family available; resolve actual tool and validate arguments |
| resources/read | Base family available |
| resources/subscribe | Unsupported: subscribe is false |
| prompts/get | Unsupported: prompts absent |
| logging/setLevel | Unsupported: logging absent |
A missing optional boolean flag does not enable the optional feature. A true listChanged flag allows the applicable list-change notification mechanism; it does not authorize the client to send notifications/tools/list_changed to the server or imply subscribe support. The host should instead be prepared to handle the applicable server-originated notifications.
The presence of an empty family object is valid support for that family. In Python, checking bool(caps.get("tools")) would incorrectly block tools/list for the example. Check family presence after schema validation, and test required feature flags against the actual boolean true.
Do not mistake optional flags for tool-specific permission. A tool may have a read-only annotation or a description claiming it is safe; neither is trusted authorization to execute it.
3. Gate on the accepted revision and ready relationship#
Method availability is revision-dependent. A method or flag introduced in a newer revision is not automatically available under an older accepted revision, even if a peer happens to return similarly named metadata. Use the selected revision's supported method registry, parameter schemas and lifecycle behavior.
Before ordinary work, require the successful lifecycle procedure appropriate to that revision. In the historical 2025-06-18 session-oriented design this includes the initialize exchange and the client's initialized notification. A server may have returned capabilities before the client is admitted to ordinary operation.
Ping has no optional capability family and has historical pre-initialization allowances. Therefore a generic statement that every method requires ready state is incorrect. The example below deliberately implements only a ready-session dispatcher, even for ping; initialization and allowed early utility messages belong to a separate lifecycle path in a real implementation.
A client should use a supported SDK rather than reconstructing the entire protocol merely to enforce these application-level admission rules. The SDK's own capability checks are valuable, but the host must still ensure that the model cannot bypass its own routing or authorization policy by calling another interface.
4. The outbound enforcement boundary#
The order is illustrative; cheap checks, authorization or target resolution may be combined or performed earlier. The important property is that a rejected candidate does not reach the transport. Invalid requests should not consume request IDs, network calls or server execution resources unnecessarily. If a request ID was already allocated, preserve historical non-reuse rules rather than recycling it.
For tools/call the target is not the method name. Resolve the actual tool from the trusted discovered catalog and use its input contract. For resources/read the target is a resource URI, which must be permitted for the actor. For resources/unsubscribe the target should correspond to a valid subscription under the applicable state. For completion/complete validate its reference and argument, not merely the completions flag.
A protocol method gate cannot enforce these target-specific constraints by itself. It should be composed with the actual schema validator and authorization system.
5. Store immutable capability evidence per session#
Consider a host with two independent server relationships:
- Inventory: tools supported, resources absent.
- Policy: resources supported, tools absent.
A global union of both declarations would misleadingly suggest that both servers support both method families. Instead, maintain trusted state scoped to the actual relationship, including the accepted revision, readiness, server identity, credential/tenant scope where applicable and a session generation or equivalent lifetime identifier.
The local generation is not a standardized MCP wire field. It helps reject work planned against an obsolete local session when the connection has genuinely been replaced.
When the connection changes, invalidate work tied to the previous relationship. Do not automatically replay a previously approved action on a replacement server. Re-resolve the target and verify any approval binding and current authority.
The snapshot should be copied from validated initialization evidence, not from arbitrary model-controlled parameters. Immutable or controlled ownership avoids accidental modifications to the declaration after acceptance. A catalog invalidation event is different from a change of protocol capability declaration. Refresh the appropriate catalog without treating listChanged as a new capability negotiation.
Avoid a check-to-send race#
If an async task checks a snapshot, awaits unrelated work and then sends through a mutable global client pointer, the session or policy may change during that gap. Rechecking at the final dispatch boundary helps but does not itself provide atomicity across an arbitrary await. Use a session-owned send operation or suitable synchronization/lease that ties the check to the actual selected transport and generation. Revalidate permissions at the appropriate boundary and let the server enforce authorization at execution.
This pattern prevents accidental cross-session sends; it cannot recall bytes already handed to a transport. The concurrency and cleanup mechanics belong to later lessons.
6. Worked scenario: subscription versus fresh read#
A policy integration advertises:
JSON{"resources":{"listChanged":true}}
The user wants the current returns policy and asks the assistant to stay updated when it changes.
The gate allows consideration of resources/read after validating the actual URI and authority. It does not allow resources/subscribe because subscribe is absent. A catalog list-change event is not a resource-content update and should not be substituted as proof that an existing document changed or remained unchanged.
If the task merely needs a fresh policy at decision time, an authorized read may be an acceptable alternative. If it requires continuous update delivery, report that the subscription feature is unavailable unless an independently supported alternative satisfies the same requirements. Do not promise live updates from unsupported features.
For tools without listChanged support, an on-demand tools/list refresh can be appropriate. It must honor the correct session and actor scope, pagination and freshness requirements. Avoid excessive polling. A missing tools family cannot be fixed by calling tools/list anyway.
7. Treat local rejection differently from remote failure#
| Observed condition | Appropriate action |
|---|---|
| Family absent in valid snapshot | Report unsupported feature locally; no send |
| Required optional flag false or absent | Reject that specific optional method; consider safe fallback |
| Unready or stale session | Block dispatch and use the lifecycle or replanning path |
| Unknown method for the selected registry | Reject unsupported method |
| Target absent or invalid | Refresh or reject according to the actual catalog/schema contract |
| Authorization denied | Do not bypass by switching transport or peer |
| Advertised method returns Method not found | Investigate peer compatibility or implementation inconsistency |
| Valid tool result reports isError | Interpret the tool failure; not necessarily a capability mismatch |
| Timeout after send | Apply the actual deadline and outcome-reconciliation policy |
Local errors are application classifications, not wire-level JSON-RPC error responses. In particular, the client has not sent a request when it locally blocks an operation. It should not present an invented -32601 as though the server returned it.
A server that advertises support but returns an unsupported-method error might have a bug, a stale relationship, incompatible deployment or method-specific restriction. Capture safe evidence, invalidate inappropriate routes where necessary and investigate rather than silently changing negotiated state or retrying indefinitely. Do not automatically conclude that a failed business tool proves the entire tools family is unavailable.
8. Tested Python implementation: session-scoped outgoing method gate#
The following dependency-free example deliberately uses a reviewed subset of the historical client-to-server method registry. It constructs immutable family/flag snapshots from decoded declarations and checks the current route, generation, revision, readiness, family, optional flag and an independently supplied authorization decision. The Dispatcher records accepted sends in a list. This makes negative assertions observable: rejected operations cannot append to the outbound record.
Save as mcp_q41.py:
PYTHONfrom dataclasses import dataclass import unittest REV = '2025-06-18' RULES = { 'ping': (None, None), 'tools/list': ('tools', None), 'tools/call': ('tools', None), 'resources/list': ('resources', None), 'resources/read': ('resources', None), 'resources/templates/list': ('resources', None), 'resources/subscribe': ('resources', 'subscribe'), 'resources/unsubscribe': ('resources', 'subscribe'), 'prompts/list': ('prompts', None), 'prompts/get': ('prompts', None), 'logging/setLevel': ('logging', None), 'completion/complete': ('completions', None), } @dataclass(frozen=True) class Session: route: str generation: int revision: str ready: bool families: frozenset flags: frozenset @classmethod def build(cls, route, generation, revision, ready, caps): if revision != REV or type(caps) is not dict: raise ValueError('unsupported_schema') families, flags = set(), set() for family in ('tools', 'resources', 'prompts', 'logging', 'completions'): if family not in caps: continue obj = caps[family] if type(obj) is not dict: raise ValueError('invalid_family') families.add(family) known = {'tools': ('listChanged',), 'resources': ('listChanged', 'subscribe'), 'prompts': ('listChanged',)}.get(family, ()) for flag in known: if flag in obj and type(obj[flag]) is not bool: raise ValueError('invalid_flag') if obj.get(flag) is True: flags.add((family, flag)) return cls(route, generation, revision, ready, frozenset(families), frozenset(flags)) def gate(session, route, generation, method, authorized): if (session.route, session.generation) != (route, generation): raise ValueError('stale_route') if session.revision != REV or method not in RULES: raise ValueError('unsupported_method') if not session.ready: raise ValueError('not_ready') family, flag = RULES[method] if family is not None and family not in session.families: raise ValueError('missing_family') if flag is not None and (family, flag) not in session.flags: raise ValueError('missing_flag') if authorized is not True: raise ValueError('denied') class Dispatcher: def __init__(self): self.active = {} self.sent = [] def send(self, route, generation, method, authorized): session = self.active.get(route) if session is None: raise ValueError('not_ready') gate(session, route, generation, method, authorized) self.sent.append((route, generation, method)) class Tests(unittest.TestCase): def setUp(self): self.d = Dispatcher() def install(self, caps, ready=True, generation=1, route='inventory'): self.d.active[route] = Session.build(route, generation, REV, ready, caps) def send(self, method, authorized=True, generation=1, route='inventory'): self.d.send(route, generation, method, authorized) def blocked(self, method, category, **kwargs): before = list(self.d.sent) with self.assertRaisesRegex(ValueError, '^' + category + '$'): self.send(method, **kwargs) self.assertEqual(self.d.sent, before) def test_empty_family(self): self.install({'tools': {}}) self.send('tools/list') self.send('tools/call') self.assertEqual(len(self.d.sent), 2) def test_missing_family(self): self.install({}) self.blocked('tools/list', 'missing_family') def test_read_without_subscribe(self): self.install({'resources': {}}) self.send('resources/read') self.blocked('resources/subscribe', 'missing_flag') def test_list_changed_is_not_subscribe(self): self.install({'resources': {'listChanged': True}}) self.blocked('resources/subscribe', 'missing_flag') def test_false_flag(self): self.install({'resources': {'subscribe': False}}) self.blocked('resources/unsubscribe', 'missing_flag') def test_subscription(self): self.install({'resources': {'subscribe': True}}) self.send('resources/subscribe') self.send('resources/unsubscribe') self.assertEqual(len(self.d.sent), 2) def test_completion(self): self.install({'prompts': {}}) self.blocked('completion/complete', 'missing_family') self.install({'prompts': {}, 'completions': {}}) self.send('completion/complete') def test_ping_no_family(self): self.install({}) self.send('ping') def test_unready(self): self.install({'tools': {}}, ready=False) self.blocked('tools/list', 'not_ready') def test_unknown_and_wrong_direction(self): self.install({'tools': {}, 'sampling': {}}) self.blocked('tools/delete', 'unsupported_method') self.blocked('sampling/createMessage', 'unsupported_method') self.blocked('notifications/tools/list_changed', 'unsupported_method') def test_policy(self): self.install({'tools': {}}) self.blocked('tools/call', 'denied', authorized=False) def test_stale_generation(self): self.install({'tools': {}}, generation=2) self.blocked('tools/call', 'stale_route') self.send('tools/call', generation=2) def test_scope(self): self.install({'tools': {}}) self.install({'resources': {}}, route='policy') self.blocked('tools/list', 'missing_family', route='policy') self.send('resources/read', route='policy') def test_snapshot(self): caps = {'resources': {'subscribe': True}} self.install(caps) caps['resources']['subscribe'] = False self.send('resources/subscribe') def test_bad_declaration(self): for caps in ({'tools': None}, {'resources': {'subscribe': 1}}): with self.assertRaises(ValueError): self.install(caps) with self.assertRaises(ValueError): Session.build('inventory', 1, 'unknown', True, {}) def test_removed_route(self): self.install({'tools': {}}) del self.d.active['inventory'] self.blocked('tools/call', 'not_ready') if __name__ == '__main__': unittest.main(verbosity=2)
Run:
BASHpython -m py_compile mcp_q41.py python -W error mcp_q41.py
Actual local output summary:
Ran 16 tests in 0.002s
OKThe frozen dataclass and frozensets preserve the recognized snapshot independently of the source dictionary. RULES maps exact method names to required family and optional flag. The dispatcher obtains the current session rather than accepting capabilities from the caller. Its blocked helper checks both the failure category and that the outbound record is unchanged.
Test coverage#
| Group | Named tests |
|---|---|
| Empty family, missing family, read without subscription, independent list-change flag, false flag and subscription support | 6 |
| Completion capability and ready-session ping without optional family | 2 |
| Not ready, unknown/wrong-direction methods, denied policy | 3 |
| Stale generation, route isolation, immutable snapshot, invalid declarations and removed route | 5 |
The 16 tests were actually executed with unittest. In test_stale_generation the old plan is rejected while a matching generation succeeds. In test_scope one route cannot borrow another route's family support. test_snapshot confirms mutation of the source declaration cannot alter the installed snapshot.
Limitations and production adaptation#
This is a sequential fixture with no real transport, MCP SDK, network or concurrency. It handles only the listed outgoing request methods and only one historical revision. The strict ready-only ping rule is a local policy, not the full historical lifecycle. Unknown and wrong-role declaration members are ignored in a narrow projection; the code does not validate the complete capability schema, experimental extensions or actual initialize exchange. It assumes trusted route/generation/ready inputs, a known method string and prior validated session association. It does not allocate request IDs or validate real message envelopes.
The authorized argument represents a trusted independent decision, not a user-provided credential or proof of permission. The gate does not resolve actual tool names, URIs, completion references, input schemas or subscription state. Accepted entries record only method markers, not actual calls. No business operation is executed. The synchronous check and append are not a proof of async or thread-safe transport dispatch, and no real stale-callback or policy-revocation race was tested.
A production application must compose this admission logic with the compatible SDK, real schema and target checks, owned session synchronization and independently enforced permissions. Q107 is reserved for real SDK implementation; local tests are not evidence of SDK conformance.
9. Practical engineering checks#
The method gate is an appropriate shared application boundary for UI actions, deterministic workflows and model tool calls. Apply it both when exposing available operations and immediately before actual execution. Hiding a button or removing a tool from model context helps usability but is not enforcement: a stale plan or direct API invocation can bypass the presentation layer.
Test actual SDK pairs for each supported revision and transport. Include feature-limited servers, false and missing flags, supported empty objects, invalid declarations, wrong direction, lifecycle exceptions, removed routes, capability changes after genuine session replacement, and negative assertions that unsupported operations never reach the transport.
Record controlled failure categories, trusted route and revision, method and capability requirement. Do not dump private arguments or credentials. Distinguish local blocks from remote failures when measuring error rates. A gate implemented as a small exact-method lookup and set membership checks is inexpensive relative to network calls, but no latency benchmark was conducted. Keep snapshots and queued work bounded.
Interview-ready answer#
A client should use a revision-specific method registry to check the current trusted session, correct direction, lifecycle, required server capability family and any additional optional flag before dispatch. Base tools support permits consideration of tools/list and tools/call; resource subscriptions additionally require resources.subscribe true. A listChanged flag is a notification feature, not a subscription or authorization grant. An empty capability-family object can advertise base support. After the protocol feature gate, resolve the actual target, validate its schema and state, enforce independent user/resource permissions, and send only through the owned current session. Reject unsupported methods locally and use only semantically safe, supported alternatives. Server-side validation remains mandatory independently of the client's gate.
Next lesson: Q42 covers connection termination and cleanup, including releasing the owned transport, invalidating routes and resolving outstanding work.
References
- 1.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 2.MCP lifecyclemodelcontextprotocol.io
- 3.MCP toolsmodelcontextprotocol.io
- 4.MCP resourcesmodelcontextprotocol.io
- 5.MCP promptsmodelcontextprotocol.io
- 6.MCP loggingmodelcontextprotocol.io
- 7.MCP completionmodelcontextprotocol.io
- 8.MCP pingmodelcontextprotocol.io
- 9.Official MCP Python SDKgithub.com
- 10.Python unittestdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation