UNPKG

h3

Version:

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

72 lines (59 loc) 1.5 kB
# MCP > H3 MCP related utils. ### `defineJsonRpcHandler()` Creates an H3 event handler that implements the JSON-RPC 2.0 specification. **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. **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); }, }, }), ); ```