clamo 0.12.0 → 1.0.1

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: 7596405122290bf9bce3c04760bbb5e03eef24f8e5e6b3c6e99105c8faa7d14e
4
- data.tar.gz: 219e2f1f54ffd99c03dcde0c18508d24625904daa2aa65f5c7c1aabbfacee11c
3
+ metadata.gz: 04f79d47039bcdc103787dd8b7e8317b7bbe0d2b0577062bb48e1adae7027df3
4
+ data.tar.gz: ca152903c69a49d623f78ccdcf39c9b210de3a5556f7fa5b2179d63cb3e8974a
5
5
  SHA512:
6
- metadata.gz: 7d6a2c1407df2fc1427a7c95500d07f4873660c2322bcd4ae1a4f642550e89d6a723e7854f2126404f985446432a8e59e2690873d28ff25b218e1f01e260898a
7
- data.tar.gz: eb941c6f05333536695f9f3d6531de593b592653b17c6fb5a10e18c5cca693c6cb2fe3e922a25f17c5a1bf3d90fae8b518674b14fc78b7b2926deff1f3d7223b
6
+ metadata.gz: ad6fbabb4e03a8ba5c01c7b79a8ab61321a07c893811bfd467bfabf0967119b685e28507098e2665f5728bc96cc5f3fe378439c02fb5e533599d09e6aa5431c2
7
+ data.tar.gz: b20dc6db24cf80b6554db5a6e29d99046e8f7b1ce712d011f44c4ae3f1230ac92cd8169fece8643f484292811c973a283de60f7de78e7fa22401bdeb9faaeb74
data/.rubocop.yml CHANGED
@@ -1,6 +1,10 @@
1
1
  AllCops:
2
2
  NewCops: enable
3
3
  TargetRubyVersion: 3.3
4
+ SuggestExtensions: false
5
+
6
+ plugins:
7
+ - rubocop-minitest
4
8
 
5
9
  Metrics/MethodLength:
6
10
  Enabled: false
@@ -23,5 +27,9 @@ Style/MultilineBlockChain:
23
27
  Style/StringLiterals:
24
28
  EnforcedStyle: double_quotes
25
29
 
30
+ Naming/PredicateMethod:
31
+ Exclude:
32
+ - "test/**/*"
33
+
26
34
  Style/StringLiteralsInInterpolation:
27
35
  EnforcedStyle: double_quotes
data/CHANGELOG.md CHANGED
@@ -4,6 +4,32 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
 
7
+ ## [1.0.1] - 2026-11-30
8
+
9
+ ### Changed
10
+
11
+ - Batch parallelism is now opt-in. A batch runs sequentially, in order, in the calling process and thread unless `Parallel.map` options (e.g. `in_threads: 4`) are passed to `dispatch`, `dispatch_json` or `handle_json`. Previously any batch of two or more requests went through `Parallel.map` whenever the `parallel` gem was installed, and its default is to fork one process per core: in-memory state changes made by service methods and `on_error` calls were lost to the parent process, and results had to be Marshal-able. To keep the old behavior, pass `in_processes: Parallel.processor_count`.
12
+
13
+ ### Fixed
14
+
15
+ - `handle_json`: a result that cannot be encoded as JSON (`NaN`, `Infinity`, circular structures) now returns `-32603 Internal error` for that request alone and is reported through `on_error`, instead of raising or failing the whole batch.
16
+ - Fractional request ids (e.g. `1.5`) are accepted, as the JSON-RPC 2.0 specification allows any Number.
17
+ - An invalid request echoes its `id` only when the id is itself a valid type; otherwise the response carries `"id": null`.
18
+ - A notification whose `params` is not an Array or Object (e.g. `"params": null`) no longer executes the method.
19
+ - Arity validation: a splat parameter no longer skips the check for required positional arguments.
20
+ - A private or protected singleton method that shadows a public method of the object's class now returns `-32601 Method not found` instead of `-32000 Server error`.
21
+ - A `LoadError` raised by a service method during a batch now propagates instead of replaying the whole batch sequentially.
22
+
23
+ ## [1.0.0] - 2026-03-15
24
+
25
+ ### Added
26
+
27
+ - RDoc comments on all public methods and modules.
28
+
29
+ ### Changed
30
+
31
+ - README restructured (table of contents, installation, roadmap). No functional changes since 0.12.0.
32
+
7
33
  ## [0.12.0] - 2026-03-14
8
34
 
9
35
  ### Changed
data/PRD.md ADDED
@@ -0,0 +1,345 @@
1
+ # Clamo — Product Requirements Document
2
+
3
+ > Future requirements for Clamo, the minimal JSON-RPC 2.0 server library for Ruby.
4
+ >
5
+ > Current state: v1.0.0 — spec-compliant dispatch, arity validation, batch processing,
6
+ > optional parallelism, per-call configuration, zero runtime dependencies (~350 LOC).
7
+ >
8
+ > **16 requirements** across 5 tiers — 0 completed, 16 pending.
9
+
10
+ ---
11
+
12
+ ## Table of Contents
13
+
14
+ - [Tier 1 — Foundation](#tier-1--foundation)
15
+ - [Tier 2 — Observability & Lifecycle](#tier-2--observability--lifecycle)
16
+ - [Tier 3 — Multi-Object & Namespace](#tier-3--multi-object--namespace)
17
+ - [Tier 4 — Integration & Ecosystem](#tier-4--integration--ecosystem)
18
+ - [Tier 5 — Documentation & Examples](#tier-5--documentation--examples)
19
+ - [Dependency Graph](#dependency-graph)
20
+ - [Suggested Implementation Order](#suggested-implementation-order)
21
+ - [Design Principles](#design-principles)
22
+
23
+ ---
24
+
25
+ ## Tier 1 — Foundation
26
+
27
+ High-value, no-dependency features that unlock later tiers.
28
+
29
+ ### 1.1 Method Metadata Caching
30
+
31
+ - [ ] Cache resolved `Method` objects and parameter signatures per service object
32
+ - [ ] Avoid repeated `public_method_defined?` / `.method()` reflection on every request
33
+ - [ ] Provide a registry API: `Clamo::Server.method_metadata(object, method_name)`
34
+ - [ ] Support cache invalidation (explicit `reset!` and optional TTL)
35
+
36
+ **Why:** Every dispatch currently reflects on the service object from scratch. Caching
37
+ method metadata improves throughput for high-frequency services and provides the
38
+ introspection foundation that Service Discovery, Autodoc, Schemas, and Profiling require.
39
+
40
+ **Depends on:** None. Unlocks: Service Discovery (1.5), Profiling (2.3), Auto-Prefixing (3.1), Schemas (4.3), Autodoc (4.4).
41
+
42
+ ### 1.2 Method Allowlists / Denylists
43
+
44
+ - [ ] Allow restricting which methods are callable via `allow:` / `deny:` keyword options
45
+ - [ ] Support both per-call and per-object-registration configuration
46
+ - [ ] Deny takes precedence over allow when both are specified
47
+ - [ ] Return `-32601 Method not found` for denied methods (indistinguishable from non-existent)
48
+
49
+ **Why:** `public_method_defined?` prevents private-method access, but real services often
50
+ need finer control — exposing a subset of public methods, or hiding specific methods
51
+ without making them private. This is the most-requested security feature for production
52
+ JSON-RPC services.
53
+
54
+ **Depends on:** None. Unlocks: Auto-Prefixing (3.1).
55
+
56
+ ### 1.3 Error Data Builder
57
+
58
+ - [ ] Provide a `Clamo::Error` exception class carrying `code`, `message`, and `data` fields
59
+ - [ ] Allow service methods to `raise Clamo::Error.new(code: -32001, message: "Not found", data: {id: 42})`
60
+ - [ ] Serialize the error fields into the JSON-RPC error response automatically
61
+ - [ ] Support the optional `data` field for structured error details (validation errors, field-level messages)
62
+ - [ ] Preserve the existing behavior of never leaking raw exception details for non-Clamo exceptions
63
+
64
+ **Why:** The JSON-RPC 2.0 spec defines an optional `data` field on error objects for
65
+ "additional information about the error." Currently Clamo strips all exception data for
66
+ security. Services need a safe, intentional way to attach structured error details
67
+ to responses. A dedicated exception class is the simplest path: raise it to send
68
+ structured errors, raise anything else and Clamo strips it as before.
69
+
70
+ **Depends on:** None. Unlocks: Schemas (4.3).
71
+
72
+ ### 1.4 Context Injection
73
+
74
+ - [ ] Allow passing a `context:` keyword through dispatch that is forwarded to the service method
75
+ - [ ] Support both explicit argument injection and a thread-local accessor pattern
76
+ - [ ] Do not change the method signature contract for methods that don't need context
77
+
78
+ **Why:** Real-world services need request-scoped data (authenticated user, request ID,
79
+ tenant, locale) available inside dispatched methods. Without context injection, users must
80
+ resort to thread-locals or global state, both of which are error-prone and hard to test.
81
+ This is a prerequisite for meaningful Rack/Rails integration.
82
+
83
+ **Depends on:** None. Unlocks: Hooks (2.1), Rack Middleware (4.1), Rails Helpers (4.2).
84
+
85
+ ### 1.5 Service Discovery
86
+
87
+ - [ ] Provide a built-in `rpc.discover` JSON-RPC method that returns available methods and their signatures
88
+ - [ ] For each method, report: name, parameter names, parameter kinds (required/optional/keyword/splat)
89
+ - [ ] Respect allowlists/denylists (1.2) — only discover callable methods
90
+ - [ ] Enrich output with schema information when Schemas (4.3) are available
91
+ - [ ] Reserve the `rpc.*` namespace for system methods (per JSON-RPC 2.0 spec recommendation)
92
+
93
+ **Why:** JSON-RPC has no built-in discoverability. MCP and LSP both rely on method
94
+ enumeration for tool/capability discovery. A runtime `rpc.discover` method makes Clamo
95
+ services self-describing without external documentation. This is distinct from Autodoc
96
+ (4.4), which generates static Markdown — Service Discovery is a live, queryable API.
97
+
98
+ **Depends on:** Method Metadata Caching (1.1). Unlocks: MCP Adapter (4.5), Autodoc (4.4).
99
+
100
+ ---
101
+
102
+ ## Tier 2 — Observability & Lifecycle
103
+
104
+ Lifecycle hooks that enable logging, profiling, and instrumentation.
105
+
106
+ ### 2.1 Hooks (before/after dispatch)
107
+
108
+ - [ ] Re-introduce `before_dispatch` and `after_dispatch` hooks with improved design
109
+ - [ ] Support both global and per-call hook registration
110
+ - [ ] `before_dispatch` receives `(method, params, context)` — raise to halt
111
+ - [ ] `after_dispatch` receives `(method, params, result, duration)` on success
112
+ - [ ] `on_error` continues to handle the failure path
113
+ - [ ] Hooks must be composable (multiple hooks run in registration order)
114
+
115
+ **Why:** Hooks were added in v0.8.0 and removed in v0.10.0 because callers could wrap
116
+ `dispatch` directly. However, wrapping doesn't compose well for cross-cutting concerns
117
+ (auth, logging, metrics) especially in batch requests where individual method calls need
118
+ instrumentation. A hook-based approach is cleaner for multi-concern lifecycles.
119
+
120
+ **Depends on:** Context Injection (1.4) — hooks should receive context. Unlocks: Observability (2.2), Profiling (2.3).
121
+
122
+ ### 2.2 Observability & Logging
123
+
124
+ - [ ] Provide a structured logging interface (not tied to any specific logger)
125
+ - [ ] Log at minimum: method name, params (redactable), duration, outcome (success/error)
126
+ - [ ] Support log-level filtering (debug/info/warn/error)
127
+ - [ ] Integrate with Hooks (2.1) so custom instrumentation is possible
128
+
129
+ **Why:** Production services need visibility into what Clamo is dispatching. A
130
+ logger-agnostic interface lets users plug in Rails.logger, $stdout, or structured logging
131
+ (e.g., Semantic Logger) without Clamo taking an opinion on the logging library.
132
+
133
+ **Depends on:** Hooks (2.1). Unlocks: Rails Helpers (4.2).
134
+
135
+ ### 2.3 Profiling
136
+
137
+ - [ ] Measure and expose per-method dispatch duration
138
+ - [ ] Provide a simple profiling hook or middleware that collects timing data
139
+ - [ ] Support aggregation (min/max/avg/p99) for long-running services
140
+ - [ ] Keep profiling opt-in and zero-overhead when disabled
141
+
142
+ **Why:** Before optimizing, you need to measure. Profiling helps users identify slow
143
+ methods, arity-check overhead, and serialization costs in their JSON-RPC services.
144
+
145
+ **Depends on:** Hooks (2.1), Method Metadata Caching (1.1). Unlocks: None (leaf feature).
146
+
147
+ ---
148
+
149
+ ## Tier 3 — Multi-Object & Namespace
150
+
151
+ Support for composing multiple service objects into a single JSON-RPC endpoint.
152
+
153
+ ### 3.1 Method Auto-Prefixing
154
+
155
+ - [ ] Map a service object to a method prefix: `object: MyAuth, prefix: "auth"` makes `auth.login` call `MyAuth.login`
156
+ - [ ] Support configurable separator (default: `"."`)
157
+ - [ ] Prefix is stripped before dispatch, so service methods keep clean names
158
+ - [ ] Prefixed methods appear in allowlists/denylists and metadata cache with their full name
159
+
160
+ **Why:** JSON-RPC services commonly use dotted method names to namespace operations
161
+ (e.g., `user.create`, `auth.login`). Without auto-prefixing, users must manually route
162
+ or name their Ruby methods with dots/underscores, which is unidiomatic.
163
+
164
+ **Depends on:** Method Metadata Caching (1.1), Method Allowlists/Denylists (1.2). Unlocks: Namespace Fusion (3.2).
165
+
166
+ ### 3.2 Namespace Fusion (Multiple Objects)
167
+
168
+ - [ ] Accept an array or hash of `{ prefix: object }` pairs instead of a single `object:`
169
+ - [ ] Route each request to the correct service object by method prefix
170
+ - [ ] Batch requests may span multiple service objects
171
+ - [ ] Detect and reject duplicate method names across objects at registration time
172
+
173
+ **Why:** Non-trivial services split logic across multiple modules. Namespace fusion lets
174
+ users compose independently developed service objects into a single JSON-RPC endpoint
175
+ without a manual dispatch layer.
176
+
177
+ **Depends on:** Method Auto-Prefixing (3.1). Unlocks: Examples (5.1).
178
+
179
+ ---
180
+
181
+ ## Tier 4 — Integration & Ecosystem
182
+
183
+ Adapters and helpers for common Ruby frameworks and protocols.
184
+
185
+ ### 4.1 Rack Middleware / Helpers
186
+
187
+ - [ ] Provide `Clamo::Rack::Middleware` that reads the request body, dispatches, and writes the response
188
+ - [ ] Set correct `Content-Type: application/json` headers
189
+ - [ ] Handle HTTP method filtering (POST only by convention)
190
+ - [ ] Support mounting at a path prefix (e.g., `map "/rpc"`)
191
+ - [ ] Integrate with Context Injection (1.4) to pass Rack env as context
192
+
193
+ **Why:** Most Ruby JSON-RPC services run behind Rack (Puma, Falcon, etc.). A thin Rack
194
+ adapter eliminates the boilerplate of reading the body, calling `handle_json`, and writing
195
+ the response — which every user currently writes by hand. This is ~30 LOC and immediately
196
+ doubles the addressable user base.
197
+
198
+ **Depends on:** Context Injection (1.4). Unlocks: Rails Helpers (4.2), MCP Adapter (4.5), Examples (5.1).
199
+
200
+ ### 4.2 Rails Helpers
201
+
202
+ - [ ] Provide a Rails controller concern or base controller for JSON-RPC endpoints
203
+ - [ ] Support Rails routing conventions (`post "/rpc", to: "jsonrpc#dispatch"`)
204
+ - [ ] Integrate with Rails.logger via Observability (2.2)
205
+ - [ ] Forward `current_user` / request context via Context Injection (1.4)
206
+
207
+ **Why:** Rails is the most common Ruby web framework. A first-class integration lowers
208
+ the barrier to adoption and ensures Clamo works well with Rails conventions (strong
209
+ parameters, CSRF, logging, etc.).
210
+
211
+ **Depends on:** Rack Middleware (4.1), Context Injection (1.4), Observability (2.2). Unlocks: Examples (5.1).
212
+
213
+ ### 4.3 Schemas (Request/Response Validation)
214
+
215
+ - [ ] Allow declaring parameter schemas per method (types, required fields, constraints)
216
+ - [ ] Validate incoming params against schema before dispatch
217
+ - [ ] Return `-32602 Invalid params` with structured error data on schema violations
218
+ - [ ] Support JSON Schema or a lightweight DSL — evaluate both before choosing
219
+
220
+ **Why:** Arity validation catches wrong argument counts, but not wrong types or values.
221
+ Schema validation adds a declarative safety layer that catches malformed requests before
222
+ they reach service logic, improving reliability and API documentation.
223
+
224
+ **Depends on:** Method Metadata Caching (1.1), Error Data Builder (1.3). Unlocks: Autodoc (4.4).
225
+
226
+ ### 4.4 Autodoc (Markdown Generation)
227
+
228
+ - [ ] Introspect service objects and generate method documentation automatically
229
+ - [ ] Include method name, parameters (with types from schemas if available), and description
230
+ - [ ] Output Markdown by default; support pluggable formatters
231
+ - [ ] Complement Service Discovery (1.5) — Autodoc generates static docs, `rpc.discover` is runtime
232
+
233
+ **Why:** JSON-RPC services lack the built-in discoverability of REST APIs (no URL
234
+ structure, no OpenAPI by convention). Autodoc makes services self-documenting, which is
235
+ especially valuable for developer onboarding and API reference generation.
236
+
237
+ **Depends on:** Method Metadata Caching (1.1), Service Discovery (1.5), Schemas (4.3) — optional but enriches output. Unlocks: None (leaf feature).
238
+
239
+ ### 4.5 MCP Server Adapter
240
+
241
+ - [ ] Provide `Clamo::MCP` adapter for the Model Context Protocol (JSON-RPC 2.0 over stdio/SSE)
242
+ - [ ] Handle MCP lifecycle methods: `initialize`, `tools/list`, `tools/call`
243
+ - [ ] Map Ruby service methods to MCP tool definitions using Service Discovery (1.5)
244
+ - [ ] Support stdio transport (for CLI tools and AI IDE integrations)
245
+ - [ ] Support SSE transport (for web-based MCP clients)
246
+ - [ ] Consider shipping as a separate gem (`clamo-mcp`) to keep the core dependency-free
247
+
248
+ **Why:** MCP (Model Context Protocol) is the emerging standard for AI tool integration,
249
+ used by Claude, Cursor, Windsurf, and other AI-powered development tools. MCP uses
250
+ JSON-RPC 2.0 as its transport layer — Clamo already speaks the protocol. An MCP adapter
251
+ makes Clamo the fastest path to building Ruby MCP servers, positioning the library at the
252
+ center of the AI tooling ecosystem.
253
+
254
+ **Depends on:** Service Discovery (1.5), Rack Middleware (4.1) — for SSE transport. Unlocks: Examples (5.1).
255
+
256
+ ---
257
+
258
+ ## Tier 5 — Documentation & Examples
259
+
260
+ ### 5.1 Usage Examples
261
+
262
+ - [ ] Basic Rack/Puma example (standalone JSON-RPC server)
263
+ - [ ] Rails integration example (controller + routes)
264
+ - [ ] MCP server example (JSON-RPC over stdio for AI tool integration)
265
+ - [ ] Multi-object namespace fusion example
266
+ - [ ] Error handling patterns (custom error data, logging)
267
+ - [ ] Testing patterns (using `JSONRPCTestHelpers`)
268
+
269
+ **Why:** The current README covers the API surface but lacks runnable examples for common
270
+ integration patterns. Examples are the fastest path to adoption.
271
+
272
+ **Depends on:** Rack Helpers (4.1), Rails Helpers (4.2), MCP Adapter (4.5), Namespace
273
+ Fusion (3.2) — examples should demonstrate the features they cover. Unlocks: None (leaf feature).
274
+
275
+ ---
276
+
277
+ ## Dependency Graph
278
+
279
+ ```
280
+ Depth 0 ─ no prerequisites (build in parallel)
281
+ 1.1 Method Metadata Caching
282
+ 1.2 Allowlists / Denylists
283
+ 1.3 Error Data Builder
284
+ 1.4 Context Injection
285
+
286
+ Depth 1 ─ needs one or more Depth-0 items (build in parallel)
287
+ 1.5 Service Discovery ◄── 1.1
288
+ 2.1 Hooks ◄── 1.4
289
+ 3.1 Auto-Prefixing ◄── 1.1 + 1.2
290
+ 4.1 Rack Middleware ◄── 1.4
291
+ 4.3 Schemas ◄── 1.1 + 1.3
292
+
293
+ Depth 2 ─ needs one or more Depth-1 items
294
+ 2.2 Observability ◄── 2.1
295
+ 2.3 Profiling ◄── 2.1 + 1.1
296
+ 3.2 Namespace Fusion ◄── 3.1
297
+ 4.4 Autodoc ◄── 1.1 + 1.5 + (4.3)
298
+ 4.5 MCP Adapter ◄── 1.5 + 4.1
299
+
300
+ Depth 3
301
+ 4.2 Rails Helpers ◄── 4.1 + 2.2
302
+
303
+ Depth 4
304
+ 5.1 Examples ◄── 4.1 + 4.2 + 4.5 + 3.2
305
+ ```
306
+
307
+ ---
308
+
309
+ ## Suggested Implementation Order
310
+
311
+ Phases map directly to the dependency graph depths. Items within each phase can
312
+ be built in parallel — they share no mutual dependencies. The **Value** column
313
+ indicates adoption impact: how much each feature expands real-world usability.
314
+
315
+ | Phase | Items | Prerequisites | Value |
316
+ |-------|-------|---------------|-------|
317
+ | 1 | 1.3 Error Data Builder | None | Critical — unblocks structured error responses |
318
+ | 1 | 1.4 Context Injection | None | Critical — unblocks Rack/Rails/hooks |
319
+ | 1 | 1.2 Allowlists / Denylists | None | High — production security requirement |
320
+ | 1 | 1.1 Method Metadata Caching | None | High — foundation for introspection features |
321
+ | 2 | 4.1 Rack Middleware | 1.4 | Critical — trivial effort, doubles user base |
322
+ | 2 | 1.5 Service Discovery | 1.1 | High — MCP readiness, runtime introspection |
323
+ | 2 | 2.1 Hooks | 1.4 | High — enables observability stack |
324
+ | 2 | 3.1 Auto-Prefixing | 1.1, 1.2 | Medium — namespace support |
325
+ | 2 | 4.3 Schemas | 1.1, 1.3 | Medium — type validation |
326
+ | 3 | 4.5 MCP Adapter | 1.5, 4.1 | High — strategic AI ecosystem positioning |
327
+ | 3 | 2.2 Observability | 2.1 | Medium — production logging |
328
+ | 3 | 2.3 Profiling | 2.1, 1.1 | Low — optimization tool |
329
+ | 3 | 3.2 Namespace Fusion | 3.1 | Medium — multi-service composition |
330
+ | 3 | 4.4 Autodoc | 1.1, 1.5, (4.3) | Low — static docs generation |
331
+ | 4 | 4.2 Rails Helpers | 4.1, 2.2 | Medium — Rails adoption |
332
+ | 5 | 5.1 Examples | 4.1, 4.2, 4.5, 3.2 | High — adoption accelerator |
333
+
334
+ ---
335
+
336
+ ## Design Principles
337
+
338
+ These principles carry forward from v1.0.0 and apply to all future work:
339
+
340
+ 1. **Zero required dependencies** — new features must not add mandatory gems
341
+ 2. **Opt-in complexity** — features are off by default; users enable what they need
342
+ 3. **Spec compliance** — never deviate from JSON-RPC 2.0 behavior
343
+ 4. **Security by default** — never leak internal details unless explicitly opted in
344
+ 5. **Thread safety** — all mutable state must be snapshot or synchronized
345
+ 6. **Minimal LOC** — resist abstraction until the third use case demands it
data/README.md CHANGED
@@ -1,7 +1,47 @@
1
1
  # Clamo
2
2
 
3
- A Ruby implementation of [JSON-RPC 2.0](https://www.jsonrpc.org/specification) designed for simplicity and compliance with the specification.
3
+ [![CI](https://github.com/rubakas/clamo/actions/workflows/main.yml/badge.svg)](https://github.com/rubakas/clamo/actions/workflows/main.yml)
4
+ [![Gem Version](https://badge.fury.io/rb/clamo.svg)](https://badge.fury.io/rb/clamo)
5
+ [![Ruby](https://img.shields.io/badge/ruby-%3E%3D%203.3-ruby.svg)](https://www.ruby-lang.org)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
7
+ [![JSON-RPC 2.0](https://img.shields.io/badge/JSON--RPC-2.0-orange.svg)](https://www.jsonrpc.org/specification)
8
+
9
+ A Ruby implementation of [JSON-RPC 2.0](https://www.jsonrpc.org/specification) designed for simplicity and compliance with the specification. Expose any Ruby module or class as a JSON-RPC service with minimal effort — just point Clamo at your object and its public methods become callable.
10
+
11
+ JSON-RPC 2.0 is the transport protocol behind [MCP](https://modelcontextprotocol.io/) and [LSP](https://microsoft.github.io/language-server-protocol/) — Clamo makes it easy to build spec-compliant services in Ruby.
12
+
13
+ ## Table of Contents
14
+
15
+ - [Installation](#installation)
16
+ - [Usage](#usage)
17
+ - [Basic Usage](#basic-usage)
18
+ - [Batch Requests](#batch-requests)
19
+ - [Notifications](#notifications)
20
+ - [Error Handling](#error-handling)
21
+ - [Configuration](#configuration)
22
+ - [Error Callback](#error-callback)
23
+ - [Per-Call Configuration](#per-call-configuration)
24
+ - [Advanced Features](#advanced-features)
25
+ - [Parallel Processing](#parallel-processing)
26
+ - [Building JSON-RPC Requests](#building-json-rpc-requests)
27
+ - [Roadmap](#roadmap)
28
+ - [Development](#development)
29
+ - [Contributing](#contributing)
30
+ - [License](#license)
31
+
32
+ ## Installation
33
+
34
+ Add to your Gemfile:
4
35
 
36
+ ```ruby
37
+ gem "clamo"
38
+ ```
39
+
40
+ Or install directly:
41
+
42
+ ```
43
+ gem install clamo
44
+ ```
5
45
 
6
46
  ## Usage
7
47
 
@@ -54,17 +94,7 @@ response = Clamo::Server.dispatch(
54
94
 
55
95
  The longer names `parsed_dispatch_to_object`, `unparsed_dispatch_to_object`, and `handle` still work as deprecated aliases.
56
96
 
57
- ### Handling Different Parameter Types
58
-
59
- Clamo supports both positional (array) and named (object/hash) parameters:
60
-
61
- ```ruby
62
- # Positional parameters
63
- request = '{"jsonrpc": "2.0", "method": "add", "params": [1, 2], "id": 1}'
64
-
65
- # Named parameters
66
- request = '{"jsonrpc": "2.0", "method": "subtract", "params": {"a": 5, "b": 3}, "id": 2}'
67
- ```
97
+ Both positional (`[1, 2]`) and named (`{"a": 5, "b": 3}`) parameters are supported — they map to positional and keyword arguments on the Ruby method respectively.
68
98
 
69
99
  ### Batch Requests
70
100
 
@@ -102,21 +132,6 @@ puts response
102
132
  # => nil
103
133
  ```
104
134
 
105
- ### Building JSON-RPC Requests
106
-
107
- Clamo provides utilities for building JSON-RPC requests:
108
-
109
- ```ruby
110
- request = Clamo::JSONRPC.build_request(
111
- method: "add",
112
- params: [1, 2],
113
- id: 1
114
- )
115
-
116
- puts request
117
- # => {"jsonrpc" => "2.0", "method" => "add", "params" => [1, 2], "id" => 1}
118
- ```
119
-
120
135
  ## Error Handling
121
136
 
122
137
  Clamo follows the JSON-RPC 2.0 specification for error handling:
@@ -162,16 +177,50 @@ Per-call config is snapshotted at the start of each dispatch, so concurrent muta
162
177
 
163
178
  ### Parallel Processing
164
179
 
165
- Batch requests are processed in parallel when the [parallel](https://github.com/grosser/parallel) gem is available. If `parallel` is not installed, batches fall back to sequential processing. You can pass options to `Parallel.map`:
180
+ Batch requests are processed sequentially, in order, in the calling process and thread. Parallel processing is opt-in: add the [parallel](https://github.com/grosser/parallel) gem to your bundle and pass any `Parallel.map` option to switch it on:
166
181
 
167
182
  ```ruby
168
183
  Clamo::Server.dispatch(
169
184
  request: batch_request,
170
185
  object: MyService,
171
- in_processes: 4 # Parallel processing option
186
+ in_threads: 4 # Any Parallel.map option enables parallel processing
172
187
  )
173
188
  ```
174
189
 
190
+ Prefer `in_threads:`. With `in_processes:` each request runs in a forked child, so changes a method makes to in-memory state and calls to `on_error` do not reach the parent process, and results must be Marshal-able. If options are passed but `parallel` is not installed, the batch still runs sequentially.
191
+
192
+ ### Building JSON-RPC Requests
193
+
194
+ Clamo provides utilities for building JSON-RPC requests:
195
+
196
+ ```ruby
197
+ request = Clamo::JSONRPC.build_request(
198
+ method: "add",
199
+ params: [1, 2],
200
+ id: 1
201
+ )
202
+
203
+ puts request
204
+ # => {"jsonrpc" => "2.0", "method" => "add", "params" => [1, 2], "id" => 1}
205
+ ```
206
+
207
+ ## Roadmap
208
+
209
+ - [x] Per-call configuration
210
+ - [ ] Method metadata caching
211
+ - [ ] Method allowlists/denylists
212
+ - [ ] Observability and logging
213
+ - [ ] Profiling
214
+ - [ ] Hooks
215
+ - [ ] Rack helpers and framework helpers (Rails)
216
+ - [ ] Autodoc (Markdown?)
217
+ - [ ] Error data builder
218
+ - [ ] Schemas
219
+ - [ ] Method auto-prefixing (namespace to prefix)
220
+ - [ ] Multiple objects (namespace fusion)
221
+ - [ ] Context injection
222
+ - [ ] More examples
223
+
175
224
  ## Development
176
225
 
177
226
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
data/lib/clamo/jsonrpc.rb CHANGED
@@ -1,8 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Clamo
4
+ # Utilities for building and validating JSON-RPC 2.0 messages.
4
5
  module JSONRPC
6
+ # Standard JSON-RPC 2.0 error codes and messages.
5
7
  module ProtocolErrors
8
+ # Immutable descriptor pairing an error code with its message.
6
9
  ErrorDescriptor = Data.define(:code, :message)
7
10
 
8
11
  PARSE_ERROR = ErrorDescriptor.new(code: -32_700, message: "Parse error")
@@ -14,6 +17,13 @@ module Clamo
14
17
  end
15
18
 
16
19
  class << self
20
+ # Builds a JSON-RPC 2.0 request Hash.
21
+ #
22
+ # Clamo::JSONRPC.build_request(method: "add", params: [1, 2], id: 1)
23
+ # # => {"jsonrpc"=>"2.0", "method"=>"add", "params"=>[1, 2], "id"=>1}
24
+ #
25
+ # +method+ is required. +params+ (Array or Hash) and +id+ are optional.
26
+ # Omitting +id+ produces a notification.
17
27
  def build_request(**opts)
18
28
  raise ArgumentError, "method is required" unless opts.key?(:method)
19
29
 
@@ -24,10 +34,13 @@ module Clamo
24
34
  .then { |r| opts.key?(:id) ? r.merge("id" => opts[:id]) : r }
25
35
  end
26
36
 
37
+ # Builds a successful JSON-RPC 2.0 response Hash.
27
38
  def build_result_response(id:, result:)
28
39
  { "jsonrpc" => "2.0", "result" => result, "id" => id }
29
40
  end
30
41
 
42
+ # Builds a JSON-RPC 2.0 error response Hash.
43
+ # Requires +error:+ with +:code+ and +:message+ keys. +:data+ is optional.
31
44
  def build_error_response(**opts)
32
45
  raise ArgumentError, "error code is required" unless opts.dig(:error, :code)
33
46
  raise ArgumentError, "error message is required" unless opts.dig(:error, :message)
@@ -41,6 +54,7 @@ module Clamo
41
54
  }.reject { |k, _| k == "data" && !opts[:error].key?(:data) } }
42
55
  end
43
56
 
57
+ # Builds a JSON-RPC 2.0 error response from an ErrorDescriptor.
44
58
  def build_error_response_from(descriptor:, id: nil)
45
59
  build_error_response(
46
60
  id: id,
@@ -51,6 +65,7 @@ module Clamo
51
65
  )
52
66
  end
53
67
 
68
+ # Convenience method for a parse error (-32700) response.
54
69
  def build_error_response_parse_error
55
70
  build_error_response(
56
71
  id: nil,
@@ -71,6 +86,11 @@ module Clamo
71
86
  end
72
87
  end
73
88
 
89
+ # Used internally by Clamo::Server — not part of the public API.
90
+ def valid_id?(id)
91
+ id.is_a?(String) || id.is_a?(Numeric) || id.is_a?(NilClass)
92
+ end
93
+
74
94
  # Used internally by Clamo::Server — not part of the public API.
75
95
  def valid_request?(request)
76
96
  request.is_a?(Hash) &&
@@ -90,12 +110,7 @@ module Clamo
90
110
  end
91
111
 
92
112
  def proper_id_if_any?(request)
93
- if key_indifferent?(request, "id")
94
- id = fetch_indifferent(request, "id")
95
- id.is_a?(String) || id.is_a?(Integer) || id.is_a?(NilClass)
96
- else
97
- true
98
- end
113
+ !key_indifferent?(request, "id") || valid_id?(fetch_indifferent(request, "id"))
99
114
  end
100
115
 
101
116
  def validate_params_type!(params)
data/lib/clamo/server.rb CHANGED
@@ -3,61 +3,118 @@
3
3
  require "json"
4
4
 
5
5
  module Clamo
6
+ # JSON-RPC 2.0 request dispatcher. All public methods on the target +object+
7
+ # become callable JSON-RPC methods.
8
+ #
9
+ # Three entry points, from highest to lowest level:
10
+ # - handle_json — JSON string in, JSON string out
11
+ # - dispatch_json — JSON string in, parsed Hash out
12
+ # - dispatch — parsed Hash in, parsed Hash out
13
+ #
14
+ # == Example
15
+ #
16
+ # Clamo::Server.handle_json(
17
+ # request: '{"jsonrpc":"2.0","method":"add","params":[1,2],"id":1}',
18
+ # object: MyService
19
+ # )
20
+ # # => '{"jsonrpc":"2.0","result":3,"id":1}'
6
21
  module Server
7
- Config = Data.define(:on_error)
22
+ # +serialize+ is set by #handle_json: successful results are encoded to JSON
23
+ # as soon as they are produced, so an unencodable result fails only its own
24
+ # request (see #serialize_result).
25
+ Config = Data.define(:on_error, :serialize)
8
26
 
9
27
  class << self
28
+ # Global error callback. Called with +(exception, method, params)+ whenever
29
+ # a dispatched method raises. Fires for both requests and notifications.
10
30
  attr_accessor :on_error
11
31
 
12
- # JSON string in, JSON string out. Full round-trip for HTTP/socket integrations.
32
+ # JSON string in, JSON string out. The primary entry point for HTTP/socket
33
+ # integrations. Returns +nil+ for notifications (no response expected).
13
34
  #
14
35
  # Clamo::Server.handle_json(request: body, object: MyService)
15
36
  #
16
- def handle_json(request:, object:, **)
17
- response = dispatch_json(request: request, object: object, **)
18
- response&.to_json
37
+ # A result that cannot be encoded as JSON (NaN, circular structures, ...)
38
+ # becomes an Internal error (-32603) for that request alone, and is
39
+ # reported through +on_error+. Other responses in a batch are unaffected.
40
+ #
41
+ # Accepts the same options as #dispatch.
42
+ def handle_json(request:, object:, on_error: self.on_error, **)
43
+ config = Config.new(on_error: on_error, serialize: true)
44
+ render_json(dispatch_json_with(request: request, object: object, config: config, **))
19
45
  end
20
46
 
21
47
  alias handle handle_json
22
48
 
23
- # JSON string in, parsed response out.
49
+ # JSON string in, parsed response Hash out. Parses the JSON and delegates
50
+ # to #dispatch. Returns a Hash (or Array of Hashes for batches), or +nil+
51
+ # for notifications.
24
52
  #
25
- # Clamo::Server.dispatch_json(request: json_string, object: MyModule)
53
+ # Clamo::Server.dispatch_json(request: json_string, object: MyService)
26
54
  #
27
- def dispatch_json(request:, object:, **)
28
- raise ArgumentError, "object is required" unless object
29
-
30
- begin
31
- parsed = JSON.parse(request)
32
- rescue JSON::JSONError
33
- return JSONRPC.build_error_response_parse_error
34
- end
35
-
36
- dispatch(request: parsed, object: object, **)
55
+ # Accepts the same options as #dispatch.
56
+ def dispatch_json(request:, object:, on_error: self.on_error, **)
57
+ config = Config.new(on_error: on_error, serialize: false)
58
+ dispatch_json_with(request: request, object: object, config: config, **)
37
59
  end
38
60
 
39
61
  alias unparsed_dispatch_to_object dispatch_json
40
62
 
41
- # Parsed hash in, parsed response out.
63
+ # Parsed Hash (or Array) in, parsed response Hash out. Validates the
64
+ # request, resolves the method on +object+, checks parameter arity,
65
+ # and dispatches. Returns +nil+ for notifications.
42
66
  #
43
- # Clamo::Server.dispatch(request: hash_or_array, object: MyModule)
67
+ # Clamo::Server.dispatch(request: hash_or_array, object: MyService)
44
68
  #
69
+ # ==== Options
70
+ # +on_error+:: Error callback for this call, overrides the global on_error.
71
+ # Extra keyword arguments (e.g. +in_threads: 4+) are forwarded to
72
+ # +Parallel.map+ for batch requests and switch batch processing from
73
+ # sequential to parallel. They require the +parallel+ gem; without it the
74
+ # batch still runs sequentially.
45
75
  def dispatch(request:, object:,
46
76
  on_error: self.on_error,
47
- **opts)
77
+ **)
48
78
  raise ArgumentError, "object is required" unless object
49
79
 
80
+ config = Config.new(on_error: on_error, serialize: false)
81
+ dispatch_with(request: request, object: object, config: config, **)
82
+ end
83
+
84
+ alias parsed_dispatch_to_object dispatch
85
+
86
+ private
87
+
88
+ def dispatch_json_with(request:, object:, config:, **)
89
+ raise ArgumentError, "object is required" unless object
90
+
91
+ begin
92
+ parsed = JSON.parse(request)
93
+ rescue JSON::JSONError
94
+ return JSONRPC.build_error_response_parse_error
95
+ end
96
+
97
+ dispatch_with(request: parsed, object: object, config: config, **)
98
+ end
99
+
100
+ def dispatch_with(request:, object:, config:, **)
50
101
  request = normalize_request_keys(request)
51
- config = Config.new(on_error: on_error)
52
102
 
53
- response_for(request: request, object: object, config: config, **opts) do |method, params|
103
+ response_for(request: request, object: object, config: config, **) do |method, params|
54
104
  dispatch_to_ruby(object: object, method: method, params: params)
55
105
  end
56
106
  end
57
107
 
58
- alias parsed_dispatch_to_object dispatch
59
-
60
- private
108
+ # Joins the responses produced under +serialize: true+. Successful results
109
+ # arrive already encoded as Strings; everything else is still a Hash.
110
+ def render_json(response)
111
+ case response
112
+ when nil then nil
113
+ when String then response
114
+ when Array then "[#{response.map { |item| item.is_a?(String) ? item : item.to_json }.join(",")}]"
115
+ else response.to_json
116
+ end
117
+ end
61
118
 
62
119
  def normalize_request_keys(request)
63
120
  case request
@@ -72,8 +129,14 @@ module Clamo
72
129
  if object.is_a?(Module)
73
130
  object.singleton_class.public_method_defined?(name, false)
74
131
  else
75
- object.class.public_method_defined?(name, false) ||
132
+ singleton_has = object.singleton_class.public_method_defined?(name, false) ||
133
+ object.singleton_class.protected_method_defined?(name, false) ||
134
+ object.singleton_class.private_method_defined?(name, false)
135
+ if singleton_has
76
136
  object.singleton_class.public_method_defined?(name, false)
137
+ else
138
+ object.class.public_method_defined?(name, false)
139
+ end
77
140
  end
78
141
  end
79
142
 
@@ -86,7 +149,8 @@ module Clamo
86
149
  end
87
150
 
88
151
  # Extra keyword arguments (**) are forwarded to response_for_batch only,
89
- # where they become options for Parallel.map (e.g., in_processes: 4).
152
+ # where they become options for Parallel.map (e.g., in_threads: 4) and
153
+ # opt the batch into parallel processing (see #map_batch).
90
154
  # For single requests they are silently ignored.
91
155
  def response_for(request:, object:, config:, **, &block)
92
156
  case request
@@ -103,8 +167,9 @@ module Clamo
103
167
  error = validate_request_structure(request)
104
168
  return error if error
105
169
 
106
- error = validate_params_type(request)
107
- return error if error
170
+ # Not via a validate_* helper: error_for is nil for notifications, which
171
+ # a caller would read as "valid" and go on to execute the method.
172
+ return error_for(request, JSONRPC::ProtocolErrors::INVALID_PARAMS) unless JSONRPC.proper_params_if_any?(request)
108
173
 
109
174
  unless method_known?(object: object, method: request["method"])
110
175
  return error_for(request, JSONRPC::ProtocolErrors::METHOD_NOT_FOUND)
@@ -135,11 +200,23 @@ module Clamo
135
200
  result.empty? ? nil : result
136
201
  end
137
202
 
138
- def map_batch(items, **, &)
203
+ # Parallelism is opt-in: without options the batch runs in order in the
204
+ # calling process and thread. Parallel.map's own default is to fork one
205
+ # process per core, where a service method's state changes and on_error
206
+ # calls would be lost to the parent.
207
+ def map_batch(items, **opts, &)
208
+ return items.map(&) if opts.empty? || !parallel_available?
209
+
210
+ Parallel.map(items, **opts, &)
211
+ end
212
+
213
+ # Only the require is guarded: a LoadError raised by a service method while
214
+ # the batch runs must propagate, not trigger a serial replay of the batch.
215
+ def parallel_available?
139
216
  require "parallel"
140
- Parallel.map(items, **, &)
217
+ true
141
218
  rescue LoadError
142
- items.map(&)
219
+ false
143
220
  end
144
221
 
145
222
  def error_for(request, descriptor)
@@ -151,16 +228,12 @@ module Clamo
151
228
  def validate_request_structure(request)
152
229
  return if JSONRPC.valid_request?(request)
153
230
 
154
- JSONRPC.build_error_response_from(
155
- id: request.is_a?(Hash) ? request["id"] : nil,
156
- descriptor: JSONRPC::ProtocolErrors::INVALID_REQUEST
157
- )
158
- end
159
-
160
- def validate_params_type(request)
161
- return if JSONRPC.proper_params_if_any?(request)
231
+ # The id is echoed only when it is itself valid; otherwise the spec
232
+ # requires null.
233
+ id = request["id"] if request.is_a?(Hash)
234
+ id = nil unless JSONRPC.valid_id?(id)
162
235
 
163
- error_for(request, JSONRPC::ProtocolErrors::INVALID_PARAMS)
236
+ JSONRPC.build_error_response_from(id: id, descriptor: JSONRPC::ProtocolErrors::INVALID_REQUEST)
164
237
  end
165
238
 
166
239
  def dispatch_notification(request, block, config)
@@ -177,12 +250,25 @@ module Clamo
177
250
  method = request["method"]
178
251
  params = request["params"]
179
252
  result = block.yield(method, params)
180
- JSONRPC.build_result_response(id: request["id"], result: result)
253
+ serialize_result(JSONRPC.build_result_response(id: request["id"], result: result), method, params, config)
181
254
  rescue StandardError => e
182
255
  config.on_error&.call(e, method, params)
183
256
  JSONRPC.build_error_response_from(id: request["id"], descriptor: JSONRPC::ProtocolErrors::SERVER_ERROR)
184
257
  end
185
258
 
259
+ # Encodes the response here rather than in #handle_json, where the method
260
+ # and params needed for +on_error+ are no longer known. Kept outside the
261
+ # dispatch rescue so a service method raising a JSON error is still a
262
+ # Server error, not an Internal error.
263
+ def serialize_result(response, method, params, config)
264
+ return response unless config.serialize
265
+
266
+ response.to_json
267
+ rescue JSON::JSONError => e
268
+ config.on_error&.call(e, method, params)
269
+ JSONRPC.build_error_response_from(id: response["id"], descriptor: JSONRPC::ProtocolErrors::INTERNAL_ERROR)
270
+ end
271
+
186
272
  def params_match_arity?(object:, method:, params:)
187
273
  ruby_method = resolve_method(object, method)
188
274
  return true unless ruby_method
@@ -207,9 +293,10 @@ module Clamo
207
293
  by_type = parameters.group_by(&:first)
208
294
 
209
295
  return false if by_type.key?(:keyreq)
210
- return true if by_type.key?(:rest)
211
296
 
212
297
  required = by_type.fetch(:req, []).size
298
+ return count >= required if by_type.key?(:rest)
299
+
213
300
  count.between?(required, required + by_type.fetch(:opt, []).size)
214
301
  end
215
302
 
data/lib/clamo/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Clamo
4
- VERSION = "0.12.0"
4
+ VERSION = "1.0.1"
5
5
  end
data/lib/clamo.rb CHANGED
@@ -4,5 +4,10 @@ require_relative "clamo/version"
4
4
  require_relative "clamo/jsonrpc"
5
5
  require_relative "clamo/server"
6
6
 
7
+ # Clamo is a minimal, spec-compliant JSON-RPC 2.0 server for Ruby.
8
+ # Expose any module or class as a JSON-RPC service — public methods
9
+ # become callable via JSON-RPC requests.
10
+ #
11
+ # See Clamo::Server for the main entry points.
7
12
  module Clamo
8
13
  end
metadata CHANGED
@@ -1,16 +1,17 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: clamo
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.12.0
4
+ version: 1.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andriy Tyurnikov
8
- bindir: exe
8
+ bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies: []
12
- description: Minimal, spec-compliant JSON-RPC 2.0 server for Ruby with request validation,
13
- method dispatch, batch processing, and notification support.
12
+ description: Minimal, spec-compliant JSON-RPC 2.0 server for Ruby. Expose any module
13
+ or class as a JSON-RPC service with request validation, batch processing, and notification
14
+ support.
14
15
  email:
15
16
  - Andriy.Tyurnikov@gmail.com
16
17
  executables: []
@@ -20,6 +21,7 @@ files:
20
21
  - ".rubocop.yml"
21
22
  - CHANGELOG.md
22
23
  - LICENSE
24
+ - PRD.md
23
25
  - README.md
24
26
  - Rakefile
25
27
  - lib/clamo.rb
@@ -48,7 +50,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
48
50
  - !ruby/object:Gem::Version
49
51
  version: '0'
50
52
  requirements: []
51
- rubygems_version: 4.0.3
53
+ rubygems_version: 4.0.20
52
54
  specification_version: 4
53
55
  summary: JSON-RPC 2.0 server toolkit for Ruby
54
56
  test_files: []