ultimate_json_rpc 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 57a4e2297d9a88e829782f6ba971a4d358cf342cf608e85cdd45b4532f1d5cc5
4
- data.tar.gz: 561c9b24aaf6369bc54429592ac5a3d3ef21577eba4df66591badbbca6f4f274
3
+ metadata.gz: f45af26595bc5213dcf9c08cad72d1cc59f9bfc271ab41738c5b85b53cca4700
4
+ data.tar.gz: 5103120fc4d68e4dbb5d2128ae557be55a46d2b018c89fcfd699cf9dd2815772
5
5
  SHA512:
6
- metadata.gz: a66e18a36696028d540dfdeffbf3136b2b413fd0c326ffc0ca4878b5c24eb96c19820f765491739ebc0d9a33076d68856e54f9808364e3615a9ed754f2106ca5
7
- data.tar.gz: 26f3451b0dc98ea82c04051a415efa68cf7d26131718ad051cf1842e898cb9a8b86b00ce3fe6685d3d191c4d5e9d61147727076abf41d3e3bf1a6238f8247b59
6
+ metadata.gz: 01576525f8649d759117e23335c67c81491aae9b9514b6d29d02e99d8bb13756bb97387a2707954169fe2eb44ca0f52757851c8cf0f3ca8270618811ccb266a4
7
+ data.tar.gz: 11b1f04708ec18d8acd99da8ab1c13cf79e00f7fdc86b9ba1b381870134af335df4d1c6dd8fe1aabce816efa1b72d5e68db7e305fc3cd298564c842136898320
data/CHANGELOG.md CHANGED
@@ -7,6 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.0.0] - 2026-11-30
11
+
12
+ **2.0 removes everything the gem used to decide on your behalf.** It registers exactly the methods you tell it to: no name is refused, no name is skipped, nothing is put into the request context unless you put it there, and `rpc.discover` is not answered unless you register it. Every registered method is callable by anyone who can reach the server. Compare `server.methods_list` before and after upgrading; the README has an upgrade table.
13
+
14
+ ### Added
15
+ - `Server#expose_discovery` registers `rpc.discover`; `Server#discovery?` tells whether it is registered.
16
+ - `Server#openrpc_document` returns the OpenRPC description to the application itself, whether or not discovery is exposed to clients.
17
+
18
+ ### Changed
19
+ - **Breaking:** `rpc.discover` is no longer answered by default. In 1.x every server described all of its methods to any client that asked. It is now "Method not found" until you call `server.expose_discovery`. `Extras::Docs` reads the description from the server directly, so it works without exposing discovery and no longer runs middleware.
20
+ - **Breaking:** `Transport::Rack` and `Transport::WebSocket` no longer put the Rack env into `request.context` by default. In 1.1.0 every request got `{ rack_env: env }` without being asked. The context is now empty unless you pass `context:`, a callable that receives the env and returns exactly what should be visible. To get the 1.1.0 behaviour back, pass `context: ->(env) { { rack_env: env } }`.
21
+ - **Breaking:** `only:` raises `ArgumentError` for a name the target has no public method for. Previously the name was ignored, with a warning only when nothing at all was exposed.
22
+ - **Breaking:** the dangerous-method blocklist is removed. `expose` used to refuse any method, namespace or `expose_method` name containing one of 41 words (`open`, `load`, `send`, `system`, `public`, ...). A client can only call a registered name, so the list never protected against clients; it only overruled the developer's own `expose` call. `expose` now registers what the call says: `expose(Kernel)` and `only: [:send]` do exactly that.
23
+ - **Breaking:** `expose(target)` no longer skips a method your class defines just because every object has one of the same name. A class that defines a public `to_s`, `inspect` or `send` now gets it registered; use `except:` or `only:` to leave it out. A bare `Object.new` still contributes only the methods defined on it.
24
+ - `expose(target, only: [...])` now looks each name up on the target instead of filtering the list of methods `expose` would find by itself, so it reaches inherited and mixed-in methods and any other public method the target responds to.
25
+
26
+ ### Fixed
27
+ - A "Method not found" error carried `data: "Internal server error"` unless `expose_errors` was on. It now always carries `data: "Method not found: <name>"`, as the README already described.
28
+ - `expose` found no methods on a module that uses `extend self`.
29
+ - README: `assert_rpc_success response, 5` (the expected value is the `expected:` keyword), a `params_schema` example whose keys did not match the method's parameter names and so validated nothing, and a `rate_limit` method that does not exist.
30
+ - `examples/mcp_server.rb` reported division by zero to the client as a bare "Internal error".
31
+
32
+ ### Internal
33
+ - The README's Ruby blocks and every file in `examples/` are now executed by the test suite (`test/test_readme.rb`, `test/test_examples.rb`), so the documentation cannot drift from the code unnoticed.
34
+
35
+ ## [1.1.0] - 2026-11-30
36
+
37
+ ### Added
38
+ - `Server#handle` and `Server#handle_parsed` accept `context:`, a Hash that seeds `request.context` for every request in the call (each batch item gets its own copy). This is how a transport tells middleware, `authorize` blocks and rate limiters who the caller is.
39
+ - `UltimateJsonRpc.current_request` returns the request being dispatched on the current fiber, so exposed methods can read `request.context`. Previously the context was only visible to middleware, despite the README saying handlers could use it.
40
+ - `Transport::Rack` seeds the context with `{ rack_env: env }` and accepts `context:` (a callable taking the env) to build a custom one. `Transport::WebSocket` does the same with the handshake env, and `on_message` accepts `context:`.
41
+ - Test helpers `rpc_call` and `rpc_notify` accept `context:`.
42
+
43
+ ### Changed
44
+ - Params are now checked against the method's signature before the call, instead of rescuing `ArgumentError` and matching its message. A wrong argument count, missing keyword or unknown keyword still returns `-32602 Invalid params`, and the method no longer runs at all in those cases.
45
+ - A method declared with a catch-all signature (`*args`, `**opts`, e.g. a `Forwardable` delegator) accepts any params, so an arity error raised further down is now `-32603 Internal error` rather than `-32602`.
46
+
47
+ ### Fixed
48
+ - An `ArgumentError` raised inside a method body whose message starts with "wrong number of arguments" or "missing keyword" (typically a bug in a nested call) was reported to the client as `-32602 Invalid params`. It is now `-32603 Internal error`.
49
+ - A callable object that only implements `#call` can now be invoked with named params; previously this failed with an internal error.
50
+ - MCP adapter: `initialize`, `notifications/initialized`, `tools/list` and `tools/call` now accept the params real clients send (`protocolVersion`, `capabilities`, `clientInfo`, `cursor`, `_meta`). Previously any `initialize` request carrying params was rejected with `-32602 Invalid params`, so the handshake failed with every real MCP client.
51
+
10
52
  ## [1.0.0] - 2026-03-20
11
53
 
12
54
  ### Added
data/README.md CHANGED
@@ -1,13 +1,23 @@
1
1
  # UltimateJsonRpc
2
2
 
3
3
  [![CI](https://github.com/rubakas/ultimate_json_rpc/actions/workflows/main.yml/badge.svg)](https://github.com/rubakas/ultimate_json_rpc/actions/workflows/main.yml)
4
+ [![Gem Version](https://img.shields.io/gem/v/ultimate_json_rpc.svg)](https://rubygems.org/gems/ultimate_json_rpc)
5
+ [![Downloads](https://img.shields.io/gem/dt/ultimate_json_rpc.svg)](https://rubygems.org/gems/ultimate_json_rpc)
6
+ [![Ruby](https://img.shields.io/badge/ruby-%3E%3D%203.2-ruby.svg)](https://www.ruby-lang.org)
7
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
8
+ [![JSON-RPC 2.0](https://img.shields.io/badge/JSON--RPC-2.0-orange.svg)](https://www.jsonrpc.org/specification)
4
9
 
5
10
  Network-agnostic JSON-RPC 2.0 server that exposes Ruby modules, classes, and instances as callable RPC endpoints. UltimateJsonRpc handles JSON-RPC message parsing, method dispatch, and response serialization — transport (HTTP, WebSocket, stdio, TCP, etc.) is the caller's responsibility.
6
11
 
12
+ > [!WARNING]
13
+ > **Every method you register can be called by anyone who can reach the server, with any arguments.**
14
+ > UltimateJsonRpc registers exactly what you tell it to and nothing else. It has no list of forbidden methods, skips nothing because of its name, adds no authentication, puts nothing into the request context on its own, and does not describe its methods to clients unless you register that too. `server.expose(obj)` publishes every public method defined on `obj`. Read [Which methods get exposed](#which-methods-get-exposed) before you expose anything.
15
+
7
16
  ## Installation
8
17
 
9
18
  Add to your Gemfile:
10
19
 
20
+ <!-- readme-test: skip (a Gemfile line, not code to run) -->
11
21
  ```ruby
12
22
  gem "ultimate_json_rpc"
13
23
  ```
@@ -41,6 +51,44 @@ server.expose_method("double", description: "Double a number") { |n| n * 2 }
41
51
  server.expose_method("greet") { |name:, greeting: "Hello"| "#{greeting}, #{name}!" }
42
52
  ```
43
53
 
54
+ ### Which methods get exposed
55
+
56
+ **Exactly the ones you register. UltimateJsonRpc never adds to that list, never removes from it, and never refuses a name.**
57
+
58
+ These are all the rules there are:
59
+
60
+ | You write | What gets registered |
61
+ |---|---|
62
+ | `server.expose(target)` | Every public method defined directly on `target`. For a module or class: its own singleton methods (`def self.add`), plus its instance methods if it does `extend self`. For an instance: the public methods written in its class, and those defined on the object itself. |
63
+ | `server.expose(target, only: [...])` | Exactly the named public methods, wherever they are defined, inherited ones included. A name `target` has no public method for raises `ArgumentError`. |
64
+ | `server.expose(target, except: [...])` | What `server.expose(target)` would register, minus the named ones. |
65
+ | `server.expose_method(name) { ... }` | That one block or callable, under that name. |
66
+
67
+ `expose(target)` leaves out inherited and mixed-in methods, and a bare `Object.new` contributes only the methods defined on that object. Nothing else is left out.
68
+
69
+ What follows from these rules is your responsibility, not the gem's:
70
+
71
+ - **Anyone who can reach the server can call every registered method, with any JSON arguments, as often as they like.** There is no authentication, authorization or rate limiting unless you add it ([Authorization](#authorization), [Rate limiting](#rate-limiting)).
72
+ - **There is no list of forbidden methods.** `server.expose(Kernel)` registers `system`, `eval` and `exec`. `only: [:instance_eval]` registers `instance_eval`. Versions before 2.0 refused these; 2.0 does what the call says.
73
+ - **No method is skipped because of what it is called.** If your class defines a public `to_s`, `inspect` or `send`, `server.expose(obj)` registers it.
74
+ - **`expose(target)` takes the method list as it is when it runs.** A public method someone adds to an exposed class later is published at the next boot, and nobody is asked. Use `only:` to make the list part of your code.
75
+ - **The server does not describe itself to clients.** `rpc.discover` is "Method not found" until you call `server.expose_discovery`; after that it lists every registered method to anyone who asks ([Service discovery](#service-discovery)).
76
+
77
+ State the list, look at it, and lock it:
78
+
79
+ ```ruby
80
+ module Admin
81
+ def self.status = "ok"
82
+ def self.wipe_everything = "gone" # public, so server.expose(Admin) would publish it
83
+ end
84
+
85
+ server.expose(Admin, only: [:status]) # the list is now part of your code
86
+ server.methods_list # => ["status"]
87
+ server.freeze # nothing more can be registered
88
+ ```
89
+
90
+ A test such as `assert_equal %w[status], server.methods_list` keeps it that way.
91
+
44
92
  ### Chainable API
45
93
 
46
94
  All setup methods return `self`, and the server is callable via `to_proc`:
@@ -60,20 +108,31 @@ responses = json_requests.map(&server)
60
108
  Declare return types for discovery metadata (purely informational, no runtime enforcement):
61
109
 
62
110
  ```ruby
63
- server.expose_method("add", returns: { "type" => "number" }) { |a, b| a + b }
111
+ server.expose_method("sum", returns: { "type" => "number" }) { |a, b| a + b }
64
112
  server.expose(Calculator, returns: { add: { "type" => "number" } })
65
113
  ```
66
114
 
67
115
  ### Service discovery
68
116
 
69
- Built-in `rpc.discover` returns an [OpenRPC](https://open-rpc.org/) 1.3.2-compatible document:
117
+ The server can describe its methods as an [OpenRPC](https://open-rpc.org/) 1.3.2-compatible document. Your own code can always read it:
70
118
 
71
119
  ```ruby
120
+ server.openrpc_document
121
+ # => {"openrpc"=>"1.3.2", "info"=>{"title"=>"My API", "version"=>"1.0"}, "methods"=>[...]}
122
+ ```
123
+
124
+ **Clients cannot, unless you say so.** `rpc.discover` is not answered until you register it:
125
+
126
+ ```ruby
127
+ server.expose_discovery
128
+
72
129
  request = '{"jsonrpc":"2.0","method":"rpc.discover","id":1}'
73
130
  server.handle(request)
74
131
  # => '{"jsonrpc":"2.0","result":{"openrpc":"1.3.2","info":{"title":"My API","version":"1.0"},"methods":[...]},"id":1}'
75
132
  ```
76
133
 
134
+ Once registered, it tells any client the name, parameters and description of every method. To limit who may ask, use `server.authorize("rpc.discover") { |request| ... }`.
135
+
77
136
  ### Middleware
78
137
 
79
138
  Add cross-cutting concerns like logging, auth, or rate limiting:
@@ -114,15 +173,37 @@ server.use(except: ["ping", "health"]) do |request, next_call|
114
173
  end
115
174
  ```
116
175
 
117
- Middleware can pass data to handlers via `request.context`:
176
+ ### Request context
177
+
178
+ `request.context` is a per-request Hash for everything that is not part of the JSON-RPC message: who is calling, over which connection, with which credentials.
179
+
180
+ **It is empty unless you fill it.** No adapter adds anything by itself: not the Rack env, not a header, not the caller's address. To fill it, pass `context:` to `handle` (or `handle_parsed`); every request, including each item of a batch, gets its own copy:
181
+
182
+ ```ruby
183
+ server.handle(json, context: { user: current_user, ip: request.ip })
184
+ ```
185
+
186
+ With the Rack and WebSocket adapters, the context is whatever your `context:` callable returns, and empty if you gave none (see [Transport examples](#transport-examples)).
187
+
188
+ Middleware reads the context and can add to it:
118
189
 
119
190
  ```ruby
120
191
  server.use do |request, next_call|
121
- request.context[:user] = authenticate(request)
192
+ request.context[:user] = authenticate(request.context[:token])
122
193
  next_call.call
123
194
  end
124
195
  ```
125
196
 
197
+ Exposed methods reach it through `UltimateJsonRpc.current_request`, which is set while the middleware chain and the method run and is `nil` otherwise:
198
+
199
+ ```ruby
200
+ module Account
201
+ def self.whoami = UltimateJsonRpc.current_request.context[:user].name
202
+ end
203
+ ```
204
+
205
+ `current_request` is fiber-local and is inherited by fibers and threads started from inside the method, so it is safe with concurrent batches and threaded servers.
206
+
126
207
  ### Instrumentation hooks
127
208
 
128
209
  Read-only lifecycle hooks for observability — they can't alter responses or swallow errors:
@@ -139,6 +220,7 @@ Hook errors are rescued and logged via `Kernel.warn`, never breaking dispatch.
139
220
 
140
221
  Swap the JSON encoder/decoder (defaults to stdlib `JSON`):
141
222
 
223
+ <!-- readme-test: skip (needs the oj gem) -->
142
224
  ```ruby
143
225
  require "oj"
144
226
  Oj.mimic_JSON
@@ -171,17 +253,17 @@ server = UltimateJsonRpc::Server.new(timeout: 5)
171
253
  Declare parameter schemas to validate incoming params before dispatch:
172
254
 
173
255
  ```ruby
174
- server.expose_method("add", params_schema: {
256
+ server.expose_method("sum", params_schema: {
175
257
  a: { "type" => "number" },
176
258
  b: { "type" => "number" }
177
259
  }) { |a, b| a + b }
178
260
 
179
261
  server.expose(Calculator, params_schema: {
180
- add: { left: { "type" => "number" }, right: { "type" => "number" } }
262
+ add: { a: { "type" => "number" }, b: { "type" => "number" } }
181
263
  })
182
264
  ```
183
265
 
184
- Supported JSON Schema keywords: `type` (`string`, `number`, `integer`, `boolean`, `array`, `object`, `null`) and `enum`. On mismatch, returns `-32602 Invalid params` with a descriptive message. Schemas also appear in `rpc.discover` output.
266
+ Supported JSON Schema keywords: `type` (`string`, `number`, `integer`, `boolean`, `array`, `object`, `null`) and `enum`. On mismatch, returns `-32602 Invalid params` with a descriptive message. Schemas also appear in the OpenRPC document.
185
267
 
186
268
  ### Method deprecation
187
269
 
@@ -193,7 +275,7 @@ server.expose_method("old_multiply", deprecated: "Use multiply_v2 instead") { |a
193
275
  server.expose(Calculator, deprecated: { add: "Use add_v2" })
194
276
  ```
195
277
 
196
- Deprecated methods still work normally but appear flagged in `rpc.discover` output.
278
+ Deprecated methods still work normally but appear flagged in the OpenRPC document.
197
279
 
198
280
  ### Per-method profiling
199
281
 
@@ -256,18 +338,27 @@ server.register_error(code: 42, message: "InsufficientFunds", description: "Acco
256
338
  server.register_error(code: 43, message: "AccountLocked")
257
339
  ```
258
340
 
259
- Registered errors appear in `rpc.discover` under `components.errors`, so consumers know which error codes to expect.
341
+ Registered errors appear in the OpenRPC document under `components.errors`, so consumers know which error codes to expect.
260
342
 
261
343
  ### Error handling
262
344
 
263
345
  Raise `ApplicationError` for custom error codes, or `ServerError` for implementation-defined errors:
264
346
 
265
347
  ```ruby
266
- raise UltimateJsonRpc::ApplicationError.new(code: 42, message: "Custom error", data: { "detail" => "info" })
267
- raise UltimateJsonRpc::ServerError.new(code: -32_001, message: "Server shutting down")
348
+ server.expose_method("withdraw") do |amount|
349
+ raise UltimateJsonRpc::ApplicationError.new(code: 42, message: "Insufficient funds", data: { "balance" => 10 }) if amount > 10
350
+
351
+ "ok"
352
+ end
353
+
354
+ server.expose_method("status") do
355
+ raise UltimateJsonRpc::ServerError.new(code: -32_050, message: "Server shutting down")
356
+ end
268
357
  ```
269
358
 
270
- Ruby's `ArgumentError` automatically maps to JSON-RPC Invalid params (`-32602`). All other exceptions become Internal error (`-32603`).
359
+ Params are checked against the method's signature before it is called: a wrong number of positional arguments, a missing required keyword, or an unknown keyword returns Invalid params (`-32602`) without running the method. Every exception raised inside the method, including `ArgumentError`, becomes Internal error (`-32603`).
360
+
361
+ A block passed to `expose_method` keeps Ruby's block semantics: extra positional arguments are ignored and missing ones are `nil`. Pass a lambda (`->(a, b) { ... }`) when you want the argument count enforced.
271
362
 
272
363
  ### Error visibility
273
364
 
@@ -283,7 +374,7 @@ server = UltimateJsonRpc::Server.new(expose_errors: true)
283
374
 
284
375
  `ApplicationError`, `ServerError`, and `MethodNotFound` always expose their details regardless of this setting, since those are intentionally raised by your code.
285
376
 
286
- Protocol-level errors (`InvalidRequest`, `InvalidParams`, `ArgumentError`, and unhandled exceptions) are gated by `expose_errors`. `InvalidParams` is a JSON-RPC schema check (type mismatch, enum violation) — for application-level business validation, raise `ApplicationError` instead.
377
+ Protocol-level errors (`InvalidRequest`, `InvalidParams`, and unhandled exceptions) are gated by `expose_errors`. `InvalidParams` is a protocol-level check (signature mismatch, schema type mismatch, enum violation) — for application-level business validation, raise `ApplicationError` instead.
287
378
 
288
379
  ### Freezing
289
380
 
@@ -297,28 +388,29 @@ server.handle(request) # still works
297
388
  ### Features
298
389
 
299
390
  - **JSON-RPC 2.0** compliant (requests, notifications, batch requests)
300
- - **Expose modules** — singleton methods become RPC methods
391
+ - **Expose modules** — singleton methods become RPC methods, including modules that `extend self`
301
392
  - **Expose instances** — public methods become RPC methods
302
393
  - **Expose blocks** — `server.expose_method("name") { ... }` for standalone methods
303
394
  - **Namespacing** — `server.expose(obj, namespace: "ns")` makes methods callable as `ns.method_name`
304
- - **Method filtering** — `server.expose(obj, only: [:add])` or `except: [:internal]`
395
+ - **Method filtering** — `server.expose(obj, only: [:add])` or `except: [:internal]`; `only:` also reaches inherited methods
305
396
  - **Method descriptions** — `descriptions:` hash or `description:` keyword for discovery
306
397
  - **Return type annotations** — `returns:` hash or keyword for discovery metadata
307
- - **Service metadata** — `name:` and `version:` appear in `rpc.discover` responses
398
+ - **Service metadata** — `name:` and `version:` appear in the OpenRPC document
308
399
  - **Positional and keyword params** — arrays map to positional args, objects map to keyword args
309
- - **Service discovery** — built-in `rpc.discover` returns OpenRPC 1.3.2-compatible schema
400
+ - **Service discovery** — `server.openrpc_document` for you; `rpc.discover` for clients once you call `expose_discovery`
310
401
  - **Middleware** — `server.use { |request, next_call| ... }` for cross-cutting concerns
402
+ - **Request context** — transports seed `request.context`; methods read it via `UltimateJsonRpc.current_request`
311
403
  - **Scoped middleware** — `only:` / `except:` with glob patterns to target specific methods or namespaces
312
404
  - **Instrumentation hooks** — `on(:request)`, `on(:response)`, `on(:error)` for read-only observability
313
405
  - **Parameter validation** — `params_schema:` with JSON Schema types and enum constraints
314
406
  - **Request timeout** — `Server.new(timeout: 5)` prevents slow handlers from blocking
315
407
  - **Method deprecation** — mark methods as deprecated in discovery metadata
316
- - **Error catalog** — `register_error` documents app error codes in `rpc.discover`
408
+ - **Error catalog** — `register_error` documents app error codes in the OpenRPC document
317
409
  - **Authorization** — `authorize("admin.*") { |req| ... }` for declarative access control
318
410
  - **Error handling** — standard JSON-RPC error codes, `ApplicationError`, and `ServerError`
319
411
  - **Error visibility** — `expose_errors: true` to include exception messages in error responses
320
- - **Rate limiting** — sliding-window `rate_limit(max:, period:)` with per-caller keying
321
- - **Security** — dangerous methods (eval, system, exec, etc.) are automatically blocked
412
+ - **Rate limiting** — sliding-window `Extras::RateLimiter.new(server, max:, period:)` with per-caller keying
413
+ - **Explicit surface** — a client can only call what you registered; `methods_list` shows it
322
414
  - **Chainable API** — all setup methods return `self`
323
415
  - **Callable** — `to_proc` enables `requests.map(&server)`
324
416
  - **Rack adapter** — `UltimateJsonRpc::Transport::Rack.new(server)` for instant HTTP deployment
@@ -351,6 +443,12 @@ run UltimateJsonRpc::Transport::Rack.new(server)
351
443
 
352
444
  `UltimateJsonRpc::Transport::Rack` handles Content-Type, returns 200 for responses, 204 for notifications, and 405 for non-POST requests.
353
445
 
446
+ Nothing from the HTTP request reaches `request.context` unless you say so. Pass `context:`, a callable that receives the Rack env and returns exactly what middleware, `authorize` blocks and your methods should see:
447
+
448
+ ```ruby
449
+ run UltimateJsonRpc::Transport::Rack.new(server, context: ->(env) { { token: env["HTTP_AUTHORIZATION"] } })
450
+ ```
451
+
354
452
  #### MCP (Model Context Protocol)
355
453
 
356
454
  Expose methods as AI tools via MCP:
@@ -370,6 +468,7 @@ UltimateJsonRpc::Extras::MCP.new(server).run
370
468
 
371
469
  Use the WebSocket adapter with any Rack-compatible library (e.g., `faye-websocket`):
372
470
 
471
+ <!-- readme-test: skip (needs faye-websocket and a live connection) -->
373
472
  ```ruby
374
473
  require "ultimate_json_rpc/transport/websocket"
375
474
 
@@ -380,12 +479,15 @@ ws = Faye::WebSocket.new(env)
380
479
  ws_handler.call(env, ws)
381
480
  ```
382
481
 
482
+ As with Rack, nothing from the handshake reaches `request.context` unless you pass `WebSocket.new(server, context: ->(env) { ... })`; what it returns is used for every message on that socket.
483
+
383
484
  See `examples/websocket_server.ru` for a complete runnable example.
384
485
 
385
486
  #### TCP
386
487
 
387
488
  Use the built-in TCP adapter for internal microservices:
388
489
 
490
+ <!-- readme-test: skip (starts a server that runs until interrupted) -->
389
491
  ```ruby
390
492
  require "ultimate_json_rpc/transport/tcp"
391
493
 
@@ -447,22 +549,45 @@ require "ultimate_json_rpc/extras/test_helpers"
447
549
  class MyTest < Minitest::Test
448
550
  include UltimateJsonRpc::Extras::TestHelpers
449
551
 
552
+ def setup
553
+ @server = UltimateJsonRpc::Server.new.expose(Calculator)
554
+ end
555
+
450
556
  def test_addition
451
- response = rpc_call(server, "add", params: [2, 3])
452
- assert_rpc_success response, 5
557
+ response = rpc_call(@server, "add", params: [2, 3])
558
+ assert_rpc_success response, expected: 5
453
559
  end
454
560
 
455
561
  def test_method_not_found
456
- response = rpc_call(server, "nonexistent")
562
+ response = rpc_call(@server, "nonexistent")
457
563
  assert_rpc_error response, code: -32_601
458
564
  end
459
565
 
460
566
  def test_notification
461
- assert_rpc_notification server, "add", params: [1, 2]
567
+ assert_rpc_notification @server, "add", params: [1, 2]
568
+ end
569
+
570
+ def test_caller_identity
571
+ @server.expose_method("whoami") { UltimateJsonRpc.current_request.context[:user] }
572
+ response = rpc_call(@server, "whoami", context: { user: "alice" })
573
+ assert_rpc_success response, expected: "alice"
462
574
  end
463
575
  end
464
576
  ```
465
577
 
578
+ ## Upgrading from 1.x to 2.0
579
+
580
+ 2.0 removes everything the gem used to decide on your behalf. Before deploying it, print `server.methods_list` under 1.x and under 2.0 and compare the two.
581
+
582
+ | 1.x | 2.0 | What to do |
583
+ |---|---|---|
584
+ | `expose` raised "method name '...' is dangerous" for 41 names (`open`, `load`, `send`, `system`, ...), also as namespaces and in `expose_method`. | No name is refused. | If you counted on that error to stop something being published, list the methods with `only:`. |
585
+ | `expose(obj)` skipped a method your class defined when every object has one of that name (`to_s`, `inspect`, `send`, `hash`, `==`). | It is registered like any other public method. | Remove it with `except:`, or use `only:`. |
586
+ | `only:` ignored a name the target did not have. | `only:` raises `ArgumentError` for it, and finds inherited methods. | Fix the name. |
587
+ | (1.1 only) The Rack and WebSocket adapters put `{ rack_env: env }` into `request.context`. | The context is empty unless you pass `context:`. | `Transport::Rack.new(server, context: ->(env) { { token: env["HTTP_AUTHORIZATION"] } })` |
588
+ | `rpc.discover` was always answered. | It is "Method not found" until you register it. | `server.expose_discovery`, if clients need it. `server.openrpc_document` and `Extras::Docs` work without it. |
589
+ | "Method not found" carried `data: "Internal server error"`. | It carries `data: "Method not found: <name>"`. | Nothing, unless a client matched on the old text. |
590
+
466
591
  ## Development
467
592
 
468
593
  ```bash
@@ -23,8 +23,10 @@ module MathTools
23
23
  def self.add(a, b) = a + b
24
24
  def self.subtract(a, b) = a - b
25
25
  def self.multiply(a, b) = a * b
26
+ # An ApplicationError's message is passed on to the client as the tool's
27
+ # error text. Any other exception reaches it as a bare "Internal error".
26
28
  def self.divide(a, b)
27
- raise ArgumentError, "Division by zero" if b.zero?
29
+ raise UltimateJsonRpc::ApplicationError.new(code: 1, message: "Division by zero") if b.zero?
28
30
 
29
31
  a.to_f / b
30
32
  end
@@ -6,25 +6,6 @@ module UltimateJsonRpc
6
6
  VARIADIC_DEFAULTS = { rest: "args", keyrest: "kwargs" }.freeze
7
7
  private_constant :VARIADIC_DEFAULTS
8
8
 
9
- DANGEROUS_METHODS = %w[
10
- eval instance_eval class_eval module_eval
11
- send public_send __send__
12
- system exec spawn fork
13
- define_method remove_method undef_method
14
- binding method_missing respond_to_missing?
15
- exit exit! abort
16
- require require_relative load
17
- open
18
- instance_variable_get instance_variable_set
19
- class_variable_get class_variable_set
20
- const_get const_set remove_const
21
- method
22
- include extend prepend
23
- attr_accessor attr_reader attr_writer
24
- public private protected
25
- ].freeze
26
- private_constant :DANGEROUS_METHODS
27
-
28
9
  TYPE_CHECKS = {
29
10
  "string" => String, "number" => Numeric, "integer" => Integer,
30
11
  "boolean" => [TrueClass, FalseClass], "array" => Array,
@@ -94,10 +75,90 @@ module UltimateJsonRpc
94
75
  end
95
76
  private_constant :ParamValidator
96
77
 
78
+ # Checks params against the callable's signature before it is called. Doing
79
+ # this up front, instead of rescuing ArgumentError around the call, means an
80
+ # ArgumentError raised inside the method body is never reported to the
81
+ # client as Invalid params.
82
+ module SignatureValidator
83
+ # What a callable accepts, worked out once when it is registered.
84
+ # +max_args+ is nil when there is no upper limit on positional arguments.
85
+ Signature = Data.define(:min_args, :max_args, :keywords, :required_keywords, :keyrest)
86
+ NO_PARAMS = {}.freeze
87
+ private_constant :Signature, :NO_PARAMS
88
+
89
+ private
90
+
91
+ def build_signature(callable)
92
+ names = signature_source(callable).parameters.group_by(&:first)
93
+ .transform_values { |list| list.map { |_, name| name.to_s } }
94
+ min_args, max_args = positional_range(callable, names)
95
+ Signature.new(
96
+ min_args:, max_args:, keyrest: names.key?(:keyrest),
97
+ keywords: names.values_at(:key, :keyreq).compact.flatten.freeze,
98
+ required_keywords: names.fetch(:keyreq, []).freeze
99
+ )
100
+ end
101
+
102
+ # A block (non-lambda Proc) ignores extra positional arguments and fills
103
+ # missing ones with nil, so any number of them is acceptable.
104
+ def positional_range(callable, names)
105
+ return [0, nil] if callable.is_a?(Proc) && !callable.lambda?
106
+
107
+ required = names.fetch(:req, []).size
108
+ [required, names.key?(:rest) ? nil : required + names.fetch(:opt, []).size]
109
+ end
110
+
111
+ # A callable object that is neither a Proc nor a Method describes its
112
+ # signature through its #call method.
113
+ def signature_source(callable) = callable.respond_to?(:parameters) ? callable : callable.method(:call)
114
+
115
+ def validate_signature!(signature, params)
116
+ case params
117
+ when Hash then check_keywords!(signature, params)
118
+ when Array, nil then check_keywords!(signature, NO_PARAMS)
119
+ else return
120
+ end
121
+ check_arity!(signature, params.is_a?(Array) ? params.size : 0)
122
+ end
123
+
124
+ def check_keywords!(signature, params)
125
+ reject_unknown_keywords!(signature, params) unless signature.keyrest
126
+ return if signature.required_keywords.empty?
127
+
128
+ missing = signature.required_keywords.reject { |name| params.key?(name) || params.key?(name.to_sym) }
129
+ return if missing.empty?
130
+
131
+ raise InvalidParams, "missing keyword#{"s" if missing.size > 1}: #{missing.map { |k| ":#{k}" }.join(", ")}"
132
+ end
133
+
134
+ def reject_unknown_keywords!(signature, params)
135
+ unknown = params.each_key.find { |key| !signature.keywords.include?(key.to_s) }
136
+ raise InvalidParams, "unknown keyword: #{unknown}" if unknown
137
+ end
138
+
139
+ def check_arity!(signature, given)
140
+ min = signature.min_args
141
+ max = signature.max_args
142
+ return if given >= min && (max.nil? || given <= max)
143
+
144
+ expected = if max.nil? then "#{min}+"
145
+ elsif max == min then min.to_s
146
+ else "#{min}..#{max}"
147
+ end
148
+ raise InvalidParams, "wrong number of arguments (given #{given}, expected #{expected})"
149
+ end
150
+
151
+ # A natively implemented callable (Math.method(:sqrt), :upcase.to_proc)
152
+ # may report its signature as "anything goes" and do its own arity check.
153
+ def native?(callable) = callable.respond_to?(:source_location) && callable.source_location.nil?
154
+ end
155
+ private_constant :SignatureValidator
156
+
97
157
  class Handler
98
158
  include ParamValidator
159
+ include SignatureValidator
99
160
 
100
- Entry = Struct.new(:callable, :description, :returns, :deprecated, :params_schema)
161
+ Entry = Struct.new(:callable, :signature, :description, :returns, :deprecated, :params_schema)
101
162
  private_constant :Entry
102
163
 
103
164
  def initialize
@@ -108,10 +169,10 @@ module UltimateJsonRpc
108
169
  params_schema: nil)
109
170
  validate_expose_args!(target, only, except)
110
171
  prefix = namespace.to_s.then { |ns| ns.empty? ? "" : "#{ns}." }
111
- methods = filter_methods(callable_methods(target), only: only, except: except)
112
- Kernel.warn "UltimateJsonRpc: expose registered 0 methods from #{target.inspect}" if methods.empty?
113
- methods.each do |m|
114
- register_exposed(prefix:, method_name: m, target:, descriptions:, returns:, deprecated:, params_schema:)
172
+ callables = only ? named_callables(target, only) : discovered_callables(target, except)
173
+ Kernel.warn "UltimateJsonRpc: expose registered 0 methods from #{target.inspect}" if callables.empty?
174
+ callables.each do |method_name, callable|
175
+ register_exposed(prefix:, method_name:, callable:, descriptions:, returns:, deprecated:, params_schema:)
115
176
  end
116
177
  end
117
178
 
@@ -122,6 +183,7 @@ module UltimateJsonRpc
122
183
  validate_method_name!(name)
123
184
  @entries[name] = Entry.new(
124
185
  callable: callable,
186
+ signature: build_signature(callable),
125
187
  description: description&.to_s,
126
188
  returns: returns,
127
189
  deprecated: normalize_deprecated(deprecated),
@@ -133,6 +195,7 @@ module UltimateJsonRpc
133
195
  entry = @entries[method_name]
134
196
  raise MethodNotFound, method_name unless entry
135
197
 
198
+ validate_signature!(entry.signature, params)
136
199
  validate_params!(entry.callable, params, entry.params_schema)
137
200
  invoke_callable(entry.callable, params)
138
201
  end
@@ -188,11 +251,12 @@ module UltimateJsonRpc
188
251
  desc
189
252
  end
190
253
 
191
- def register_exposed(prefix:, method_name:, target:, descriptions:, returns:, deprecated:, params_schema:)
254
+ def register_exposed(prefix:, method_name:, callable:, descriptions:, returns:, deprecated:, params_schema:)
192
255
  full_name = "#{prefix}#{method_name}"
193
256
  validate_method_name!(full_name)
194
257
  @entries[full_name] = Entry.new(
195
- callable: target.method(method_name.to_sym),
258
+ callable: callable,
259
+ signature: build_signature(callable),
196
260
  description: extract_metadata(descriptions, method_name)&.to_s,
197
261
  returns: extract_metadata(returns, method_name),
198
262
  deprecated: normalize_deprecated(extract_metadata(deprecated, method_name)),
@@ -215,27 +279,42 @@ module UltimateJsonRpc
215
279
  source[method_name.to_s]
216
280
  end
217
281
 
218
- def callable_methods(target)
219
- if target.is_a?(Module)
220
- target.singleton_methods(false).map(&:to_s)
221
- else
222
- ((target.class.public_instance_methods(false) - Object.public_instance_methods) |
223
- target.singleton_methods(false)).map(&:to_s)
224
- end
282
+ # What expose registers is decided by the call alone, never by what a
283
+ # method happens to be called.
284
+ #
285
+ # With only:, exactly the named public methods, wherever they are defined.
286
+ def named_callables(target, only)
287
+ Array(only).map(&:to_s).uniq.to_h { |name| [name, named_callable(target, name)] }
288
+ end
289
+
290
+ def named_callable(target, name)
291
+ target.public_method(name)
292
+ rescue NameError
293
+ raise ArgumentError, "#{target.inspect} has no public method '#{name}'"
294
+ end
295
+
296
+ # Without only:, the public methods defined directly on the target.
297
+ def discovered_callables(target, except)
298
+ names = defined_methods(target) - Array(except).map(&:to_s)
299
+ names.to_h { |name| [name, target.method(name)] }
225
300
  end
226
301
 
227
- def filter_methods(methods, only:, except:)
228
- if only
229
- allowed = Array(only).map(&:to_s)
230
- methods.select { |m| allowed.include?(m) }
231
- elsif except
232
- blocked = Array(except).map(&:to_s)
233
- methods.reject { |m| blocked.include?(m) }
234
- else
235
- methods
302
+ # A module or class: its own singleton methods, plus its instance methods
303
+ # when it extends itself. An instance: the methods of its class and those
304
+ # defined on the object itself. Object is not anyone's own class, so a
305
+ # bare Object.new contributes only what was defined on it.
306
+ def defined_methods(target)
307
+ names = target.singleton_methods(false)
308
+ if target.is_a?(Module)
309
+ names |= target.public_instance_methods(false) if extends_itself?(target)
310
+ elsif !target.instance_of?(Object)
311
+ names |= target.class.public_instance_methods(false)
236
312
  end
313
+ names.map(&:to_s)
237
314
  end
238
315
 
316
+ def extends_itself?(mod) = !mod.is_a?(Class) && mod.singleton_class.include?(mod)
317
+
239
318
  def validate_expose_args!(target, only, except)
240
319
  raise ArgumentError, "target must not be nil" if target.nil?
241
320
  raise ArgumentError, "cannot use both :only and :except" if only && except
@@ -245,18 +324,10 @@ module UltimateJsonRpc
245
324
  raise ArgumentError, "method name must not be empty" if name.empty?
246
325
  raise ArgumentError, "method names starting with 'rpc.' are reserved" if name.start_with?("rpc.")
247
326
 
248
- validate_segments!(name)
327
+ raise ArgumentError, "method name contains empty segment" if name.split(".", -1).any?(&:empty?)
249
328
  raise ArgumentError, "method '#{name}' is already registered" if @entries.key?(name)
250
329
  end
251
330
 
252
- def validate_segments!(name)
253
- segments = name.include?(".") ? name.split(".", -1) : [name]
254
- segments.each do |segment|
255
- raise ArgumentError, "method name contains empty segment" if segment.empty?
256
- raise ArgumentError, "method name '#{segment}' is dangerous" if DANGEROUS_METHODS.include?(segment)
257
- end
258
- end
259
-
260
331
  def resolve_callable(callable, block)
261
332
  raise ArgumentError, "provide either a callable or a block, not both" if callable && block
262
333
  raise ArgumentError, "a callable or block is required" unless callable || block
@@ -266,43 +337,23 @@ module UltimateJsonRpc
266
337
  end
267
338
  end
268
339
 
269
- DISPATCH_ARG_ERROR = /\Awrong number of arguments\b|\Amissing keywords?: /
270
- private_constant :DISPATCH_ARG_ERROR
340
+ NATIVE_ARITY_ERROR = /\Awrong number of arguments\b/
341
+ private_constant :NATIVE_ARITY_ERROR
271
342
 
343
+ # Only called after validate_signature!, so every Hash key is a keyword
344
+ # the callable accepts.
272
345
  def invoke_callable(callable, params)
273
346
  case params
274
347
  when Array then callable.call(*params)
275
- when Hash then callable.call(**safe_symbolize_keys(callable, params))
348
+ when Hash then callable.call(**params.transform_keys(&:to_sym))
276
349
  when nil then callable.call
277
350
  else raise InvalidParams, "params must be an Array, Hash, or nil"
278
351
  end
279
352
  rescue ArgumentError => e
280
- raise InvalidParams, e.message if e.message.match?(DISPATCH_ARG_ERROR)
353
+ raise InvalidParams, e.message if native?(callable) && e.message.match?(NATIVE_ARITY_ERROR)
281
354
 
282
355
  raise
283
356
  end
284
-
285
- def safe_symbolize_keys(callable, params)
286
- return params.transform_keys(&:to_sym) if accepts_keyrest?(callable)
287
-
288
- known = known_keyword_params(callable)
289
- params.each_with_object({}) do |(k, v), h|
290
- key = k.to_s
291
- raise InvalidParams, "unknown keyword: #{key}" unless known.key?(key)
292
-
293
- h[known[key]] = v
294
- end
295
- end
296
-
297
- def known_keyword_params(callable)
298
- callable.parameters.each_with_object({}) do |(type, name), map|
299
- map[name.to_s] = name if name && %i[key keyreq].include?(type)
300
- end
301
- end
302
-
303
- def accepts_keyrest?(callable)
304
- callable.parameters.any? { |type, _| type == :keyrest }
305
- end
306
357
  end
307
358
  end
308
359
  end
@@ -7,12 +7,15 @@ module UltimateJsonRpc
7
7
 
8
8
  attr_reader :method_name, :params, :id, :context
9
9
 
10
- def initialize(data)
10
+ # +context+ seeds the request context, typically with what the transport
11
+ # knows about the caller. It is copied, so each request in a batch gets
12
+ # its own Hash to write to.
13
+ def initialize(data, context: nil)
11
14
  validate!(data)
12
15
  @method_name = data["method"].dup.freeze
13
16
  @params = deep_freeze(deep_dup(data["params"]))
14
17
  @id = data["id"].is_a?(String) ? data["id"].dup.freeze : data["id"]
15
- @context = {}
18
+ @context = context ? context.dup : {}
16
19
  end
17
20
 
18
21
  def notification?
@@ -18,14 +18,11 @@ module UltimateJsonRpc
18
18
 
19
19
  private
20
20
 
21
+ # Read straight from the server, so it works whether or not discovery is
22
+ # exposed to clients. The round trip gives the document as a client
23
+ # would see it (string keys throughout).
21
24
  def discover
22
- @discover ||= begin
23
- request = { "jsonrpc" => "2.0", "method" => "rpc.discover", "id" => 1 }
24
- result = @json.parse(@server.handle(@json.generate(request)))
25
- raise "rpc.discover returned an error: #{result["error"]&.inspect}" unless result.key?("result")
26
-
27
- result["result"]
28
- end
25
+ @discover ||= @json.parse(@json.generate(@server.openrpc_document))
29
26
  end
30
27
 
31
28
  def title_section
@@ -37,10 +37,13 @@ module UltimateJsonRpc
37
37
 
38
38
  def build_mcp_server
39
39
  mcp = Server.new(name: @app_server.name, version: @app_server.version, json: @json)
40
- mcp.expose_method("initialize") { mcp_initialize }
41
- mcp.expose_method("notifications/initialized") { nil }
42
- mcp.expose_method("tools/list") { mcp_tools_list }
43
- mcp.expose_method("tools/call") { |name:, arguments: {}| mcp_tools_call(name, arguments) }
40
+ # Every handler takes ** because clients send params these handlers do not
41
+ # use (protocolVersion, capabilities, clientInfo, cursor, _meta, ...), and
42
+ # an undeclared keyword is rejected as Invalid params.
43
+ mcp.expose_method("initialize") { |**| mcp_initialize }
44
+ mcp.expose_method("notifications/initialized") { |**| nil }
45
+ mcp.expose_method("tools/list") { |**| mcp_tools_list }
46
+ mcp.expose_method("tools/call") { |name:, arguments: {}, **| mcp_tools_call(name, arguments) }
44
47
  mcp
45
48
  end
46
49
 
@@ -3,18 +3,18 @@
3
3
  module UltimateJsonRpc
4
4
  module Extras
5
5
  module TestHelpers
6
- def rpc_call(server, method, params: nil, id: 1)
6
+ def rpc_call(server, method, params: nil, id: 1, context: nil)
7
7
  json = rpc_json_adapter(server)
8
8
  request = { "jsonrpc" => "2.0", "method" => method, "id" => id }
9
9
  request["params"] = params if params
10
- json.parse(server.handle(json.generate(request)))
10
+ json.parse(server.handle(json.generate(request), context:))
11
11
  end
12
12
 
13
- def rpc_notify(server, method, params: nil)
13
+ def rpc_notify(server, method, params: nil, context: nil)
14
14
  json = rpc_json_adapter(server)
15
15
  request = { "jsonrpc" => "2.0", "method" => method }
16
16
  request["params"] = params if params
17
- server.handle(json.generate(request))
17
+ server.handle(json.generate(request), context:)
18
18
  end
19
19
 
20
20
  def rpc_batch(server, *requests)
@@ -3,6 +3,12 @@
3
3
  require "timeout"
4
4
 
5
5
  module UltimateJsonRpc
6
+ InvalidRequest = Core::InvalidRequest
7
+ InvalidParams = Core::InvalidParams
8
+ MethodNotFound = Core::MethodNotFound
9
+ ApplicationError = Core::ApplicationError
10
+ ServerError = Core::ServerError
11
+
6
12
  GENERIC_ERROR_DATA = "Internal server error"
7
13
  GENERIC_PARAMS_DATA = "Invalid method parameters"
8
14
  private_constant :GENERIC_ERROR_DATA, :GENERIC_PARAMS_DATA
@@ -10,36 +16,36 @@ module UltimateJsonRpc
10
16
  module BatchProcessor
11
17
  private
12
18
 
13
- def handle_batch(requests)
19
+ def handle_batch(requests, context)
14
20
  return @json.generate(Core::Response.error(Core::INVALID_REQUEST, nil)) if requests.empty?
15
21
  if batch_too_large?(requests)
16
22
  return @json.generate(Core::Response.error(Core::INVALID_REQUEST, nil, data: "Batch too large"))
17
23
  end
18
24
 
19
- json_parts = process_batch_items(requests)
25
+ json_parts = process_batch_items(requests, context)
20
26
  json_parts.empty? ? nil : "[#{json_parts.join(",")}]"
21
27
  end
22
28
 
23
- def process_batch_items(requests)
29
+ def process_batch_items(requests, context)
24
30
  if @concurrent_batches
25
- pool_dispatch(requests).compact
31
+ pool_dispatch(requests) { |req| safe_serialize(req, context) }.compact
26
32
  else
27
- requests.filter_map { |req| serialize_single(req) }
33
+ requests.filter_map { |req| serialize_single(req, context) }
28
34
  end
29
35
  end
30
36
 
31
- def pool_dispatch(requests)
37
+ def pool_dispatch(requests, &)
32
38
  queue = Queue.new
33
39
  requests.each_with_index { |req, i| queue << [req, i] }
34
40
  results = Array.new(requests.size)
35
- spawn_workers(queue:, results:, pool_size: [requests.size, @max_concurrency].min)
41
+ spawn_workers(queue:, results:, pool_size: [requests.size, @max_concurrency].min, &)
36
42
  results
37
43
  end
38
44
 
39
- def spawn_workers(queue:, results:, pool_size:)
45
+ def spawn_workers(queue:, results:, pool_size:, &work)
40
46
  mutex = Mutex.new
41
47
  pool_size.times.map do
42
- Thread.new { drain_queue(queue, results, mutex) }
48
+ Thread.new { drain_queue(queue, results, mutex, &work) }
43
49
  end.each(&:join)
44
50
  end
45
51
 
@@ -50,13 +56,13 @@ module UltimateJsonRpc
50
56
  rescue ThreadError
51
57
  break
52
58
  end
53
- result = safe_serialize(req)
59
+ result = yield req
54
60
  mutex.synchronize { results[i] = result }
55
61
  end
56
62
  end
57
63
 
58
- def safe_serialize(data)
59
- serialize_single(data)
64
+ def safe_serialize(data, context)
65
+ serialize_single(data, context)
60
66
  rescue Exception # rubocop:disable Lint/RescueException -- worker threads must never die silently
61
67
  id = data.is_a?(Hash) ? extract_id(data) : nil
62
68
  begin
@@ -80,15 +86,26 @@ module UltimateJsonRpc
80
86
  private_constant :BatchProcessor
81
87
 
82
88
  module OpenRPCBuilder
83
- private
84
-
85
- def build_openrpc_document
89
+ # The OpenRPC description of every registered method. Always available to
90
+ # the application itself; clients get it only after #expose_discovery.
91
+ def openrpc_document
86
92
  doc = { "openrpc" => "1.3.2", "info" => build_info, "methods" => @handler.methods_info }
87
93
  doc.delete("info") if doc["info"].empty?
88
94
  doc["components"] = { "errors" => @error_catalog } if @error_catalog&.any?
89
95
  doc
90
96
  end
91
97
 
98
+ # Registers rpc.discover, which returns #openrpc_document to any client
99
+ # that asks. Until this is called, rpc.discover is Method not found.
100
+ def expose_discovery
101
+ @discovery = true
102
+ self
103
+ end
104
+
105
+ def discovery? = @discovery
106
+
107
+ private
108
+
92
109
  def build_info
93
110
  { "title" => @name, "version" => @version, "description" => @description }.compact
94
111
  end
@@ -162,10 +179,14 @@ module UltimateJsonRpc
162
179
  @max_concurrency = max_concurrency
163
180
  @json = @json_adapter = json
164
181
  @handler = Core::Handler.new
182
+ @discovery = false
165
183
  @middleware = []
166
184
  @hooks = HOOK_EVENTS.to_h { |e| [e, []] }
167
185
  end
168
186
 
187
+ # Registers the public methods defined directly on +target+, or exactly
188
+ # the names given in +only:+. Nothing is filtered or refused: every
189
+ # registered method can be called by any client that reaches the server.
169
190
  def expose(target, namespace: nil, only: nil, except: nil, descriptions: nil, returns: nil, deprecated: nil,
170
191
  params_schema: nil)
171
192
  @handler.expose(target, namespace:, only:, except:, descriptions:, returns:, deprecated:, params_schema:)
@@ -193,20 +214,25 @@ module UltimateJsonRpc
193
214
  self
194
215
  end
195
216
 
196
- def handle(json_string)
217
+ # +context+ is a Hash of what the transport knows about the caller (Rack
218
+ # env, authenticated user, ...). Each request starts with a copy of it as
219
+ # its +request.context+.
220
+ def handle(json_string, context: nil)
197
221
  data = @json.parse(json_string)
198
222
  rescue StandardError
199
223
  @json.generate(Core::Response.error(Core::PARSE_ERROR, nil))
200
224
  else
201
- handle_parsed(data)
225
+ handle_parsed(data, context:)
202
226
  end
203
227
 
204
228
  alias call handle
205
229
 
206
- def handle_parsed(data)
230
+ def handle_parsed(data, context: nil)
231
+ raise ArgumentError, "context must be a Hash" unless context.nil? || context.is_a?(Hash)
232
+
207
233
  case data
208
- when Array then handle_batch(data)
209
- when Hash then serialize_single(data)
234
+ when Array then handle_batch(data, context)
235
+ when Hash then serialize_single(data, context)
210
236
  else @json.generate(Core::Response.error(Core::INVALID_REQUEST, nil))
211
237
  end
212
238
  end
@@ -235,8 +261,8 @@ module UltimateJsonRpc
235
261
 
236
262
  private
237
263
 
238
- def serialize_single(data)
239
- request = parse_request(data)
264
+ def serialize_single(data, context = nil)
265
+ request = parse_request(data, context)
240
266
  return request unless request.is_a?(Core::Request)
241
267
 
242
268
  response = execute_request(request)
@@ -255,8 +281,8 @@ module UltimateJsonRpc
255
281
  end
256
282
  end
257
283
 
258
- def parse_request(data)
259
- Core::Request.new(data)
284
+ def parse_request(data, context)
285
+ Core::Request.new(data, context:)
260
286
  rescue Core::InvalidRequest
261
287
  @json.generate(Core::Response.error(Core::INVALID_REQUEST, extract_id(data)))
262
288
  end
@@ -275,7 +301,7 @@ module UltimateJsonRpc
275
301
 
276
302
  def timed_dispatch(request)
277
303
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
278
- result = with_timeout { build_chain(request).call }
304
+ result = with_current_request(request) { with_timeout { build_chain(request).call } }
279
305
  duration = elapsed(start)
280
306
  emit(:response, request, result, duration)
281
307
  [result, nil, duration]
@@ -307,7 +333,8 @@ module UltimateJsonRpc
307
333
  def elapsed(start) = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
308
334
 
309
335
  def precompile_middleware
310
- methods = @handler.methods_list + ["rpc.discover"]
336
+ methods = @handler.methods_list
337
+ methods += ["rpc.discover"] if @discovery
311
338
  @middleware_index = methods.to_h do |name|
312
339
  [name, @middleware.select { |_, matcher| matcher.call(name) }.freeze]
313
340
  end.freeze
@@ -329,6 +356,16 @@ module UltimateJsonRpc
329
356
  ->(name) { patterns.public_send(check) { |p| p.include?("*") ? File.fnmatch(p, name) : p == name } }
330
357
  end
331
358
 
359
+ # Restores the previous value so a server called from inside another
360
+ # server's method (as the MCP adapter does) does not clobber it.
361
+ def with_current_request(request)
362
+ previous = Fiber[CURRENT_REQUEST_KEY]
363
+ Fiber[CURRENT_REQUEST_KEY] = request
364
+ yield
365
+ ensure
366
+ Fiber[CURRENT_REQUEST_KEY] = previous
367
+ end
368
+
332
369
  def with_timeout(&)
333
370
  return yield unless @timeout
334
371
 
@@ -338,15 +375,16 @@ module UltimateJsonRpc
338
375
  end
339
376
 
340
377
  def invoke_handler(request)
341
- return @handler.call(request.method_name, request.params) unless request.method_name == "rpc.discover"
378
+ return openrpc_document if @discovery && request.method_name == "rpc.discover"
342
379
 
343
- build_openrpc_document
380
+ @handler.call(request.method_name, request.params)
344
381
  end
345
382
 
346
383
  def error_details(err)
347
384
  case err
348
385
  when Core::MethodNotFound
349
- [Core::METHOD_NOT_FOUND, Core::ERROR_MESSAGES[Core::METHOD_NOT_FOUND], generic_data(err)]
386
+ # The message only echoes the name the client sent, so it is never hidden.
387
+ [Core::METHOD_NOT_FOUND, Core::ERROR_MESSAGES[Core::METHOD_NOT_FOUND], err.message]
350
388
  when Core::ApplicationError, Core::ServerError then [err.code, err.message, err.rpc_data]
351
389
  when Core::InvalidParams then [Core::INVALID_PARAMS, nil, generic_data(err, GENERIC_PARAMS_DATA)]
352
390
  when Core::InvalidRequest then [Core::INVALID_REQUEST, nil, generic_data(err)]
@@ -8,8 +8,14 @@ module UltimateJsonRpc
8
8
  NOT_ALLOWED_HEADERS = CONTENT_TYPE.merge("allow" => "POST").freeze
9
9
  UNSUPPORTED_MEDIA_BODY = '{"jsonrpc":"2.0","error":{"code":-32600,"message":"Unsupported Media Type"},"id":null}'
10
10
 
11
- def initialize(server)
11
+ # +context+ is an optional callable that turns the Rack env into the
12
+ # request context, e.g. <tt>->(env) { { user: env["warden"].user } }</tt>.
13
+ # Without it nothing from the HTTP request reaches the context.
14
+ def initialize(server, context: nil)
15
+ raise ArgumentError, "context must respond to #call" unless context.nil? || context.respond_to?(:call)
16
+
12
17
  @server = server
18
+ @context = context
13
19
  end
14
20
 
15
21
  def call(env)
@@ -18,7 +24,7 @@ module UltimateJsonRpc
18
24
  return unsupported_media_type unless acceptable_content_type?(env)
19
25
 
20
26
  body = env["rack.input"]&.read.to_s
21
- response = @server.handle(body)
27
+ response = @server.handle(body, context: build_context(env))
22
28
 
23
29
  if response
24
30
  [200, CONTENT_TYPE.dup, [response]]
@@ -34,6 +40,8 @@ module UltimateJsonRpc
34
40
 
35
41
  private
36
42
 
43
+ def build_context(env) = @context&.call(env)
44
+
37
45
  def method_not_allowed
38
46
  [405, NOT_ALLOWED_HEADERS.dup, [NOT_ALLOWED_BODY]]
39
47
  end
@@ -5,17 +5,24 @@ module UltimateJsonRpc
5
5
  class WebSocket
6
6
  attr_reader :server
7
7
 
8
- def initialize(server)
8
+ # +context+ is an optional callable that turns the Rack env of the
9
+ # WebSocket handshake into the request context. Without it nothing from
10
+ # the handshake reaches the context.
11
+ def initialize(server, context: nil)
12
+ raise ArgumentError, "context must respond to #call" unless context.nil? || context.respond_to?(:call)
13
+
9
14
  @server = server
15
+ @context = context
10
16
  end
11
17
 
12
- def on_message(data)
13
- @server.handle(data.to_s)
18
+ def on_message(data, context: nil)
19
+ @server.handle(data.to_s, context:)
14
20
  end
15
21
 
16
- def call(_env, socket)
22
+ def call(env, socket)
23
+ context = @context&.call(env)
17
24
  socket.on(:message) do |event|
18
- response = on_message(event.respond_to?(:data) ? event.data : event)
25
+ response = on_message(event.respond_to?(:data) ? event.data : event, context:)
19
26
  socket.send(response) if response
20
27
  end
21
28
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module UltimateJsonRpc
4
- VERSION = "1.0.0"
4
+ VERSION = "2.0.0"
5
5
  end
@@ -7,6 +7,18 @@ module UltimateJsonRpc
7
7
  module Core
8
8
  class Error < StandardError; end
9
9
  end
10
+
11
+ CURRENT_REQUEST_KEY = :ultimate_json_rpc_current_request
12
+ private_constant :CURRENT_REQUEST_KEY
13
+
14
+ # The request being dispatched on the current fiber, or nil outside a
15
+ # dispatch. This is how an exposed method reaches the request context:
16
+ #
17
+ # def self.whoami = UltimateJsonRpc.current_request.context[:user]
18
+ #
19
+ # Set while the middleware chain and the method run. Fibers and threads
20
+ # started from there see the same request.
21
+ def self.current_request = Fiber[CURRENT_REQUEST_KEY]
10
22
  end
11
23
 
12
24
  require_relative "ultimate_json_rpc/core/errors"
@@ -1,6 +1,8 @@
1
1
  module UltimateJsonRpc
2
2
  VERSION: String
3
3
 
4
+ def self.current_request: () -> Core::Request?
5
+
4
6
  module Core
5
7
  class Error < StandardError
6
8
  end
@@ -56,7 +58,7 @@ module UltimateJsonRpc
56
58
  attr_reader id: String | Numeric | nil
57
59
  attr_reader context: Hash[Symbol, untyped]
58
60
 
59
- def initialize: (Hash[String, untyped]) -> void
61
+ def initialize: (Hash[String, untyped], ?context: Hash[Symbol, untyped]?) -> void
60
62
  def notification?: () -> bool
61
63
  end
62
64
 
@@ -104,15 +106,18 @@ module UltimateJsonRpc
104
106
  def use: (?only: Array[String | Symbol] | String | Symbol | nil, ?except: Array[String | Symbol] | String | Symbol | nil) { (Core::Request, Proc) -> untyped } -> self
105
107
  def on: (Symbol) { (*untyped) -> void } -> self
106
108
  def register_error: (code: Integer, message: String, ?description: String?) -> self
109
+ def expose_discovery: () -> self
110
+ def discovery?: () -> bool
111
+ def openrpc_document: () -> Hash[String, untyped]
107
112
  def authorize: (*String, ?code: Integer, ?message: String) { (Core::Request) -> boolish } -> self
108
113
  def to_proc: () -> Proc
109
114
  def inspect: () -> String
110
115
  def expose_errors?: () -> bool
111
116
  def concurrent_batches?: () -> bool
112
117
  def method?: (String) -> bool
113
- def handle: (String) -> String?
118
+ def handle: (String, ?context: Hash[Symbol, untyped]?) -> String?
114
119
  alias call handle
115
- def handle_parsed: (untyped) -> String?
120
+ def handle_parsed: (untyped, ?context: Hash[Symbol, untyped]?) -> String?
116
121
  def methods_list: () -> Array[String]
117
122
  def methods_info: () -> Array[Hash[String, untyped]]
118
123
  def size: () -> Integer
@@ -129,7 +134,7 @@ module UltimateJsonRpc
129
134
  end
130
135
 
131
136
  class Rack
132
- def initialize: (Server) -> void
137
+ def initialize: (Server, ?context: (^(Hash[String, untyped]) -> Hash[Symbol, untyped])?) -> void
133
138
  def call: (Hash[String, untyped]) -> [Integer, Hash[String, String], Array[String]]
134
139
  def freeze: () -> self
135
140
  end
@@ -148,8 +153,8 @@ module UltimateJsonRpc
148
153
  class WebSocket
149
154
  attr_reader server: Server
150
155
 
151
- def initialize: (Server) -> void
152
- def on_message: (untyped) -> String?
156
+ def initialize: (Server, ?context: (^(Hash[String, untyped]) -> Hash[Symbol, untyped])?) -> void
157
+ def on_message: (untyped, ?context: Hash[Symbol, untyped]?) -> String?
153
158
  def call: (untyped, untyped) -> void
154
159
  def freeze: () -> self
155
160
  end
@@ -197,8 +202,8 @@ module UltimateJsonRpc
197
202
  end
198
203
 
199
204
  module TestHelpers
200
- def rpc_call: (Server, String, ?params: untyped, ?id: String | Integer) -> Hash[String, untyped]
201
- def rpc_notify: (Server, String, ?params: untyped) -> String?
205
+ def rpc_call: (Server, String, ?params: untyped, ?id: String | Integer, ?context: Hash[Symbol, untyped]?) -> Hash[String, untyped]
206
+ def rpc_notify: (Server, String, ?params: untyped, ?context: Hash[Symbol, untyped]?) -> String?
202
207
  def rpc_batch: (Server, *Hash[String, untyped]) -> Array[Hash[String, untyped]]?
203
208
  def assert_rpc_success: (Hash[String, untyped], ?expected: untyped, ?msg: String?) -> void
204
209
  def assert_rpc_error: (Hash[String, untyped], ?code: Integer?, ?message: String?, ?msg: String?) -> void
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ultimate_json_rpc
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andriy Tyurnikov
@@ -69,7 +69,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
69
69
  - !ruby/object:Gem::Version
70
70
  version: '0'
71
71
  requirements: []
72
- rubygems_version: 4.0.8
72
+ rubygems_version: 4.0.20
73
73
  specification_version: 4
74
74
  summary: Expose Ruby objects through JSON-RPC
75
75
  test_files: []