|
1 | 1 | # MCP Routing Semantics |
2 | 2 |
|
3 | | -> This page describes the **current transitional routing behavior**. Its live |
4 | | -> upstream fan-out and durable-session assumptions are not the Phase 3 target. |
5 | | -> See [ContextForge 2.0 Target Architecture and Roadmap](mcp-capability-allocation.md) |
6 | | -> for the proposed ownership boundary and migration. |
| 3 | +The external dataplane is a **pure stateless router**. No session state, no `BackendTransports`, no sticky-routing requirement. |
7 | 4 |
|
8 | | -## Backend Prefix Contract |
| 5 | +## How a request is routed |
9 | 6 |
|
10 | | -Backend map keys become public identifiers only for **multi-backend virtual hosts without an explicit tool alias**: |
| 7 | +1. `validate_stateless` extracts `VirtualHost` from request extensions (set by `virtual_host_config` layer from the JWT virtual-host ID). |
| 8 | +2. Downstream name is looked up in `VirtualHost::tools`, `::resources`, or `::prompts` — an O(1) table lookup. |
| 9 | +3. `connect_backend_for_request` opens a fresh `StreamableHttpClientTransport`, runs the call, closes the connection. |
11 | 10 |
|
12 | | -```text |
13 | | -backend tool "increment" on backend "gateway-one" → "gateway-one-increment" |
14 | | -backend resource "counter" on backend "gateway-one" → "gateway-one-counter" |
15 | | -``` |
16 | | - |
17 | | -Single-backend virtual hosts: identifiers pass through **unchanged**. |
18 | | - |
19 | | -> **Breaking change rule:** changing a backend map key changes downstream identifiers for multi-backend virtual hosts. Do not rename without updating merge logic, split logic, and tests. |
20 | | -
|
21 | | -## Tool Aliases |
22 | | - |
23 | | -`BackendMCPGateway.tool_name_aliases` maps `{downstream_alias: upstream_original}`. Aliases take precedence over prefix fallback. They are advertised and routed exactly as published (case, dots, underscores preserved). |
24 | | - |
25 | | -## List Operations (fan-out) |
26 | | - |
27 | | -All four list methods fan out to all connected backends concurrently and merge results: |
28 | | - |
29 | | -```text |
30 | | -list_tools / list_resources / list_prompts / list_resource_templates |
31 | | - → all connected backends → merged sorted output |
32 | | -``` |
| 11 | +The control plane builds and publishes the routing tables to Redis; the dataplane never derives names at call time. |
33 | 12 |
|
34 | | -Failed/unavailable backends are logged and skipped. Single-backend: identifiers unchanged. Multi-backend: prefixed with backend map key. |
| 13 | +## Routing table shape |
35 | 14 |
|
36 | | -## Routed Operations (single backend) |
| 15 | +```rust |
| 16 | +VirtualHost { backends: HashMap<String, BackendMCPGateway>, |
| 17 | + tools: HashMap<String, ServiceRoute>, |
| 18 | + resources: HashMap<String, ServiceRoute>, |
| 19 | + resource_templates: HashMap<String, ServiceRoute>, |
| 20 | + prompts: HashMap<String, ServiceRoute> } |
37 | 21 |
|
38 | | -Calls targeting one object use the inverse rule. The name splitter walks configured backend names and requires a `-` immediately after the backend name: |
39 | | - |
40 | | -```text |
41 | | -gateway-one-increment → backend: gateway-one, tool: increment |
42 | | -gateway-oneincrement → rejected (no - separator) |
| 22 | +ServiceRoute { backend_name: String, // key into VirtualHost::backends |
| 23 | + upstream_name: String } // name/URI forwarded to the backend |
43 | 24 | ``` |
44 | 25 |
|
45 | | -`call_tool` resolves explicit alias first, then falls back to single/multi-backend logic. |
46 | | - |
47 | | -Methods using the same conditional routing: `read_resource`, `subscribe`, `unsubscribe`, `get_prompt`, `complete`. |
| 26 | +Source: [`user_store.rs`](../../crates/contextforge-data-plane-apis/src/user_store.rs) |
48 | 27 |
|
49 | | -## Federated Pagination |
| 28 | +## Method quick reference |
50 | 29 |
|
51 | | -The gateway wraps per-backend cursors inside its own opaque token (JSON, treated as opaque by MCP clients). First request: all backends queried. Resume: cursor decoded, exhausted backends skipped. New cursor emitted when any backend has more pages. |
| 30 | +| Method | Behavior | |
| 31 | +| --- | --- | |
| 32 | +| `initialize` (`2026-07-28`) | `INVALID_REQUEST` — not supported by this dataplane. | |
| 33 | +| `initialize` (legacy) | Stub `InitializeResult`; no backend fanout. Supports older clients during migration. | |
| 34 | +| `list_tools`, `list_resources`, `list_resource_templates`, `list_prompts` | `INVALID_REQUEST` — delegated to control plane. | |
| 35 | +| `call_tool` | Lookup in `tools` map → pre-hook → fresh connection → call → post-hook → close. Forwards cancellation; tracks progress tokens. | |
| 36 | +| `read_resource` | Lookup in `resources` map → fresh connection → call with upstream URI → close. | |
| 37 | +| `get_prompt` | Lookup in `prompts` map → pre-hook → fresh connection → call → post-hook → close. | |
| 38 | +| `subscribe`, `unsubscribe`, `complete` | `INVALID_REQUEST` — delegated to control plane. | |
| 39 | +| `ping` | Local success; no backend fanout. | |
| 40 | +| `DELETE` | RMCP handles; `session_id_layer` removes the `LocalUserSessionStore` entry. No backend state to clean up. | |
52 | 41 |
|
53 | | -**Known limitation:** if backend set changes between pages, removed backend's cursor is silently dropped. |
| 42 | +## Header forwarding |
54 | 43 |
|
55 | | -## Session State (local process) |
| 44 | +Applied in order per upstream call: Host (from backend URL, HTTPS only) → passthrough (`BackendMCPGateway::passthrough_headers`) → `Mcp-Param-*` auto-forward → trace context → add (`add_headers`, overrides passthrough) → remove (`remove_headers`, applied last). |
56 | 45 |
|
57 | | -Backend RMCP services are stored in `BackendTransports` keyed by: |
58 | | -```text |
59 | | -principal (claims.sub) + backend_name (map key) + downstream_session_id |
60 | | -``` |
61 | | - |
62 | | -This is **local process state only**. Implications: |
63 | | -- After `initialize`, later requests must reach the same process. |
64 | | -- Sticky routing required for load-balanced deployments. |
65 | | -- Gateway restart → all sessions lost → clients must re-run `initialize`. |
66 | | -- Multi-runtime mode (`--single-runtime false`): each runtime thread has its own `BackendTransports` with no cross-thread affinity. |
67 | | - |
68 | | -**Exception: `call_tool` uses per-request backend lifecycle.** Each tool call creates a fresh backend connection, executes the call with plugin hooks, then closes the connection. This bypasses `BackendTransports` entirely and does not require session affinity for tool calls specifically (though other MCP methods still do). |
69 | | - |
70 | | - |
71 | | -```mermaid |
72 | | -sequenceDiagram |
73 | | - participant C as MCP Client |
74 | | - participant GW as Gateway (RMCP) |
75 | | - participant BT as BackendTransports<br/>(local process state) |
76 | | - participant LU as LocalUserSessionStore<br/>(LRU 50k / 1h) |
77 | | - participant BA as Backend A |
78 | | - participant BB as Backend B |
79 | | -
|
80 | | - C->>GW: POST initialize (Mcp-Session-Id: S) |
81 | | - GW->>BA: initialize (concurrent) |
82 | | - GW->>BB: initialize (concurrent) |
83 | | - BA-->>GW: InitializeResult |
84 | | - BB-->>GW: InitializeResult |
85 | | - GW->>BT: store RunningService keyed by sub+backend+S |
86 | | - GW->>LU: store session entry for sub+S |
87 | | - GW-->>C: merged InitializeResult |
88 | | -
|
89 | | - C->>GW: POST call_tool (Mcp-Session-Id: S) |
90 | | - GW->>BT: lookup sub+backend+S → Arc<RunningService> |
91 | | - BT-->>GW: RunningService handle |
92 | | - GW->>BA: call_tool (routed by name prefix) |
93 | | - BA-->>GW: ToolResult |
94 | | - GW-->>C: ToolResult |
95 | | -
|
96 | | - C->>GW: DELETE (Mcp-Session-Id: S) |
97 | | - GW->>GW: RMCP handles DELETE |
98 | | - GW->>LU: remove sub+S entry |
99 | | - GW->>BT: remove all sub+*+S entries |
100 | | - GW-->>C: 200 OK |
101 | | -``` |
| 46 | +Protected headers that config can never touch: `Host`, `Content-Length`, `Content-Type`, all RFC 7230 hop-by-hop headers, `Mcp-Session-Id`, `Accept`, `Last-Event-Id`, and all computed MCP standard headers (`Mcp-Method`, `Mcp-Name`, `Mcp-Protocol-Version`, `Mcp-Param-*`). |
102 | 47 |
|
103 | | -## Capability Merge |
| 48 | +For clients on `≥ 2026-07-28`, `call_tool` validates `Mcp-Param-*` headers against `BackendMCPGateway::tool_schemas` before contacting the backend. |
104 | 49 |
|
105 | | -On `initialize`, the gateway builds one downstream `InitializeResult` — not a passthrough of any one backend. The source of truth is each backend's `InitializeResult`; the gateway reads `peer_info().capabilities` from each running service and stores them with the backend transport state. |
| 50 | +## Plugin hooks |
106 | 51 |
|
107 | | -The merge rule (gateway-aware, not a raw union): |
108 | | -- Enable a top-level capability when ≥1 backend supports it **and** the gateway has a routing story for it. |
109 | | -- `resources.subscribe` preserved if any backend advertises it (the gateway routes subscribe/unsubscribe and forwards resource-update notifications). |
110 | | -- `listChanged` not yet advertised (gateway doesn't emit downstream list-changed notifications when upstream lists change). |
111 | | -- Single-backend passthrough is not a stable contract (`HashMap` iteration order). |
112 | | -- If no backend reports supported capabilities, returns `ServerCapabilities::default()`. |
113 | | - |
114 | | -**Do not** initialize the downstream capability from just one backend entry — the gateway fronts multiple backends, `HashMap` iteration is non-deterministic, and list methods already merge across all backends. |
115 | | - |
116 | | -## Cleanup |
117 | | - |
118 | | -`DELETE` with `Mcp-session-id`: |
119 | | -```text |
120 | | -→ RMCP handles request |
121 | | -→ on success: remove LocalUserSessionStore entry + BackendTransports entries for principal+session |
122 | | -``` |
123 | | -If RMCP rejects the delete, local state is untouched. |
124 | | - |
125 | | - |
126 | | -## MCP Method Quick Reference |
127 | | - |
128 | | -| Method | Group | Behavior | |
129 | | -| --- | --- | --- | |
130 | | -| `initialize` | Session | Concurrent fanout to all backends; failure of one backend is non-fatal (stored with no service). Returns merged capability set. Requires `DownstreamSessionId`, `UserConfig`, `VirtualHostId`, `ContextForgeClaims`. | |
131 | | -| `list_tools` | List | Fan-out all connected backends → merged sorted result. Cursor-based pagination across backends. | |
132 | | -| `list_resources` | List | Same as list_tools. | |
133 | | -| `list_prompts` | List | Same as list_tools. | |
134 | | -| `list_resource_templates` | List | Same — both name and URI template get prefixed for multi-backend. | |
135 | | -| `call_tool` | Targeted | **Per-request backend lifecycle:** creates fresh connection via `connect_backend_for_request`, runs pre-hook, executes call, runs post-hook, closes connection. Resolves alias → single/multi-backend fallback. Forwards downstream cancellation to backend. Tracks backend progress tokens: RMCP assigns a new token per backend request; the gateway maps each backend token to the downstream token. Request enqueue and mapping publication are serialized against progress lookup so an immediate backend notification cannot overtake registration. When the notification matches an in-flight token, the gateway restores the downstream token and forwards it to the client. Does not use session-backed `BackendTransports`. | |
136 | | -| `read_resource` | Targeted | Single-backend: URI unchanged. Multi-backend: strips prefix. | |
137 | | -| `subscribe` / `unsubscribe` | Targeted | Same resource-URI routing; forwards/stops resource-update notifications. | |
138 | | -| `get_prompt` | Targeted | Single-backend: name unchanged. Multi-backend: strips prefix. Runs pre/post prompt hooks around the backend call: the pre hook may rewrite arguments or deny, the post hook may rewrite or reject the rendered messages. | |
139 | | -| `complete` | Targeted | Routes on prompt name or resource URI inside `ref`. | |
140 | | -| `ping` | Local | Returns success; no backend fanout. | |
141 | | -| `DELETE` | Session | RMCP handles first; on success `session_id_layer` removes local session + backend transports. | |
| 52 | +`call_tool` and `get_prompt` run `before_*/after_*` hooks when a `GatewayPluginRuntimeHandle` is configured. Pre-hook may rewrite arguments or deny; post-hook may rewrite or reject the response. Pre-hook state is passed to the post-hook. |
0 commit comments