Skip to main content

Module router

Module router 

Source
Expand description

Method-name -> async-handler registry and the JSON-RPC dispatch algorithm.

Why: the transport loop (crate::serve::transport) only knows how to turn bytes into a trusty_common::mcp::Request and a Response back into bytes; it must not know which methods exist. The Router is the seam in between: handlers register under a method name once, and every future ticket that adds a method (session.* #2054, task.* #2056, harness.describe #2066) does so with one router.register(...) call, never touching the transport or the dispatch algorithm.

What: MethodHandler is an object-safe async-handler trait, blanket implemented for any Fn(Value, ConnectionContext) -> Future<Output = Result<Value, RpcError>> (so plain async fn(Value, ConnectionContext) -> Result<Value, RpcError> items and closures both register directly, no adapter boilerplate). Every handler receives a ConnectionContext — most (ping, health, session.list, …) ignore it; session.attach (#2054) uses it to push server-initiated notifications back to the calling connection. Threading it through uniformly keeps one call signature for every method rather than a second handler trait carved out for streaming methods. Router::dispatch implements the JSON-RPC 2.0 error model end-to-end for methods it knows about:

  • -32600 Invalid Request — non-"2.0" jsonrpc version, or an empty method name.
  • -32601 Method not found — no handler registered under the name.
  • handler-returned RpcError (typically -32602/-32603, or a #2054 domain code like -32007 session_not_found) is copied onto the wire error verbatim, data included.
  • -32700 Parse error is produced by Router::dispatch_json, not Router::dispatch — the STDIO transport (crate::serve::transport, one JSON object per line) and the HTTP transport (crate::serve::http, one JSON object per POST /rpc body) both receive raw bytes rather than an already-parsed Request, and both need the exact same “parse or -32700” behaviour. Centralising it here means the error message and code can never drift between the two wire formats.

Per JSON-RPC 2.0 §4.1, a request with no id is a notification: the server must never reply, even with an error, though the handler (if one matches) still executes for its side effects. dispatch computes the response normally and then swaps in Response::suppressed() at the end when the original request had no id.

Test: see tests below — one case per error code, a notification that still executes its handler but suppresses the reply, and a successful round trip.

Structs§

Router
Method-name -> handler registry and JSON-RPC 2.0 dispatcher.

Traits§

MethodHandler
Object-safe async handler for one JSON-RPC method.