UNPKG

h3

Version:

Minimal H(TTP) framework built for high performance and portability.

76 lines (61 loc) 2.1 kB
# MCP > H3 MCP related utils. ### `defineJsonRpcHandler()` Creates an H3 event handler that implements the JSON-RPC 2.0 specification. **Security defaults:** requests must have a JSON `Content-Type` (CSRF, see `validateContentType`), cross-origin requests are rejected (CSRF and DNS rebinding, see `allowedOrigins`), and batches are capped at 50 requests (fan-out amplification, see `maxBatchSize`). **Example:** ```ts app.post( "/rpc", defineJsonRpcHandler({ methods: { echo: ({ params }, event) => { return `Received \`${params}\` on path \`${event.url.pathname}\``; }, sum: ({ params }, event) => { return params.a + params.b; }, }, }), ); ``` ### `defineJsonRpcWebSocketHandler()` Creates an H3 event handler that implements JSON-RPC 2.0 over WebSocket. This is an opt-in feature that allows JSON-RPC communication over WebSocket connections for bi-directional messaging. Each incoming WebSocket text message is processed as a JSON-RPC request, and responses are sent back to the peer. **Security:** unlike `defineJsonRpcHandler()`, this does not check the request `Origin`. WebSocket upgrades are not subject to CORS, so a page on any origin can open a connection carrying the visitor's cookies (cross-site WebSocket hijacking). Validate `Origin` in the `upgrade` hook and throw a `Response` to abort the connection. **Example:** ```ts app.get( "/rpc/ws", defineJsonRpcWebSocketHandler({ methods: { echo: ({ params }) => { return `Received: ${Array.isArray(params) ? params[0] : params?.message}`; }, sum: ({ params }) => { return params.a + params.b; }, }, }), ); ``` **Example:** ```ts // With additional WebSocket hooks app.get( "/rpc/ws", defineJsonRpcWebSocketHandler({ methods: { greet: ({ params }) => `Hello, ${params.name}!`, }, hooks: { open(peer) { console.log(`Peer connected: ${peer.id}`); }, close(peer, details) { console.log(`Peer disconnected: ${peer.id}`, details); }, }, }), ); ```