You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
refactor(core): extract Dispatcher; Protocol composes it (zero behavior change)
Introduce `Dispatcher<ContextT>` (`packages/core/src/shared/dispatcher.ts`)
holding the request-handler registry, middleware chain, and `dispatch()`
entry point. `Protocol` now composes a `protected readonly dispatcher`
and delegates:
- `setRequestHandler` / `removeRequestHandler` / `assertCanSetRequestHandler`
- `fallbackRequestHandler` (now `dispatcher.fallbackHandler`)
- `_onrequest` invokes `dispatcher.dispatch(request, ctx)` for lookup,
middleware onion, and JSON-RPC response wrapping
The previous `_wrapHandler` override hook is replaced by `dispatcher.use()`:
- `Server` registers `_callToolResultMiddleware` (was `_wrapHandler` for tools/call)
- `Client` registers `_validationMiddleware` (was `_wrapHandler` for
elicitation/create + sampling/createMessage)
Same validation runs on the same paths; the observation point moves from
per-registration wrapping to per-dispatch middleware.
`dispatch()`'s catch block preserves `_onrequest`'s error behavior verbatim:
thrown errors surface their `code` (if a safe integer), `message`, and `data`.
No sanitization is introduced.
Tests:
- `dispatcher.test.ts` added (11 tests for setHandler/dispatch/middleware/error)
- `wrapHandler.test.ts` deleted (covered by rewritten customMethods test)
- `customMethods.test.ts` adapts one test from spying on `_wrapHandler` to
spying via middleware; same assertion (both 2-arg and 3-arg routes through)
No existing test assertions changed.
Extract Dispatcher from Protocol. Protocol composes `protected readonly dispatcher`; setRequestHandler/_onrequest delegate. The protected `_wrapHandler` override hook is replaced by `dispatcher.use(middleware)`.
2.**`Protocol.connect()`** routes to `_onrequest()`, `_onresponse()`, or `_onnotification()`
163
163
3.**`Protocol._onrequest()`**:
164
-
-Looks up handler in `_requestHandlers` map (keyed by method name)
164
+
-Checks `dispatcher.canHandle(method)`; sends a `MethodNotFound` error and returns early if no handler (or fallback) is registered
165
165
- Creates `BaseContext` with `signal`, `sessionId`, `sendNotification`, `sendRequest`, etc.
166
166
- Calls `buildContext()` to let subclasses enrich the context (e.g., Server adds HTTP request info)
167
-
- Invokes handler, sends JSON-RPC response back via transport
167
+
- Calls `dispatcher.dispatch()` which looks up the handler (keyed by method name), runs the middleware chain, invokes the handler, and wraps the result as a JSON-RPC response
168
+
- Sends the response back via transport
168
169
4.**Handler** was registered via `setRequestHandler('method', handler)`
0 commit comments