instant_record 0.1.0 → 0.3.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.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,429 @@
1
+ require "json"
2
+
3
+ module InstantRecord
4
+ module Mcp
5
+ # Model Context Protocol (MCP) JSON-RPC 2.0 server over stdio.
6
+ #
7
+ # Reads newline-delimited JSON-RPC messages from `input` ($stdin) and writes
8
+ # newline-delimited JSON-RPC responses to `output` ($stdout). Diagnostic logs
9
+ # never touch `output` — they go to `err` ($stderr).
10
+ class Server
11
+ JSONRPC_VERSION = "2.0".freeze
12
+ SUPPORTED_PROTOCOLS = %w[2025-06-18 2025-03-26 2024-11-05].freeze
13
+ DEFAULT_PROTOCOL = "2024-11-05".freeze
14
+
15
+ PARSE_ERROR = -32700
16
+ INVALID_REQUEST = -32600
17
+ METHOD_NOT_FOUND = -32601
18
+ INVALID_PARAMS = -32602
19
+ INTERNAL_ERROR = -32603
20
+
21
+ def initialize(runtime, input: $stdin, output: $stdout, err: $stderr, name: "instant_record", version: InstantRecord::VERSION)
22
+ @runtime = runtime
23
+ @input = input
24
+ @output = output
25
+ @err = err
26
+ @name = name
27
+ @version = version
28
+ @output.sync = true if @output.respond_to?(:sync=)
29
+ end
30
+
31
+ def run
32
+ while (line = @input.gets)
33
+ line = line.strip
34
+ next if line.empty?
35
+
36
+ response = handle_line(line)
37
+ write_response(response) if response
38
+ end
39
+ end
40
+
41
+ def handle_line(line)
42
+ message = JSON.parse(line)
43
+ handle_message(message)
44
+ rescue JSON::ParserError => e
45
+ error_response(nil, PARSE_ERROR, "Parse error: #{e.message}")
46
+ end
47
+
48
+ def handle_message(message)
49
+ unless message.is_a?(Hash) && message["jsonrpc"] == JSONRPC_VERSION && message["method"].is_a?(String)
50
+ return error_response(message.is_a?(Hash) ? message["id"] : nil, INVALID_REQUEST, "Invalid JSON-RPC 2.0 request")
51
+ end
52
+
53
+ id = message["id"]
54
+ method = message["method"]
55
+ params = message["params"] || {}
56
+ notification = !message.key?("id")
57
+
58
+ case method
59
+ when "initialize"
60
+ result_response(id, handle_initialize(params))
61
+ when "notifications/initialized", "notifications/cancelled", "initialized"
62
+ nil
63
+ when "ping"
64
+ result_response(id, {})
65
+ when "tools/list"
66
+ result_response(id, { "tools" => tool_definitions })
67
+ when "tools/call"
68
+ result_response(id, handle_tool_call(params))
69
+ when "resources/list"
70
+ result_response(id, { "resources" => resource_definitions })
71
+ when "resources/read"
72
+ result_response(id, handle_resource_read(params))
73
+ else
74
+ notification ? nil : error_response(id, METHOD_NOT_FOUND, "Method not found: #{method}")
75
+ end
76
+ rescue ArgumentError => e
77
+ notification ? nil : error_response(id, INVALID_PARAMS, e.message)
78
+ rescue StandardError => e
79
+ @err&.puts("[instant_record:mcp] #{e.class}: #{e.message}")
80
+ notification ? nil : error_response(id, INTERNAL_ERROR, e.message)
81
+ end
82
+
83
+ def tool_definitions
84
+ [
85
+ {
86
+ "name" => "instant_record_status",
87
+ "description" => "Inspect local SQLite replica sync cursor, pending outbox count, identity, models, and available screens (<1ms offline).",
88
+ "inputSchema" => { "type" => "object", "properties" => {}, "additionalProperties" => false }
89
+ },
90
+ {
91
+ "name" => "instant_record_sync",
92
+ "description" => "Run a sync pass against the configured Rails server: push pending local outbox mutations and pull latest scoped changes.",
93
+ "inputSchema" => {
94
+ "type" => "object",
95
+ "properties" => {
96
+ "endpoint" => { "type" => "string", "description" => "Optional sync endpoint URL override." }
97
+ },
98
+ "additionalProperties" => false
99
+ }
100
+ },
101
+ {
102
+ "name" => "instant_record_models",
103
+ "description" => "List all synced models in the local SQLite replica with table names, columns, row counts, and pending write counts (<1ms offline).",
104
+ "inputSchema" => { "type" => "object", "properties" => {}, "additionalProperties" => false }
105
+ },
106
+ {
107
+ "name" => "instant_record_query",
108
+ "description" => "Query synced model records from the local SQLite replica with structured filters, sorting, column projection, and pagination (<1ms offline).",
109
+ "inputSchema" => {
110
+ "type" => "object",
111
+ "properties" => {
112
+ "model" => { "type" => "string", "description" => "Synced model or table name (e.g. Issue, Note, MailEntry)." },
113
+ "where" => {
114
+ "type" => "object",
115
+ "description" => "Column filters: exact values, arrays (IN), null (IS NULL), or operator objects ({eq, ne, gt, gte, lt, lte, like, in, is_null, not_null})."
116
+ },
117
+ "order" => {
118
+ "oneOf" => [
119
+ { "type" => "string" },
120
+ { "type" => "array", "items" => { "type" => "string" } }
121
+ ],
122
+ "description" => "Sort order such as 'created_at desc' or ['created_at desc', 'id desc']."
123
+ },
124
+ "columns" => {
125
+ "type" => "array",
126
+ "items" => { "type" => "string" },
127
+ "description" => "Optional subset of columns to return."
128
+ },
129
+ "limit" => { "type" => "integer", "minimum" => 1, "maximum" => 500, "default" => 50 },
130
+ "offset" => { "type" => "integer", "minimum" => 0, "default" => 0 }
131
+ },
132
+ "required" => ["model"],
133
+ "additionalProperties" => false
134
+ }
135
+ },
136
+ {
137
+ "name" => "instant_record_get",
138
+ "description" => "Fetch a single synced record by model and primary key ID from the local SQLite replica (<1ms offline).",
139
+ "inputSchema" => {
140
+ "type" => "object",
141
+ "properties" => {
142
+ "model" => { "type" => "string", "description" => "Synced model or table name." },
143
+ "id" => { "type" => "string", "description" => "Primary key value." }
144
+ },
145
+ "required" => %w[model id],
146
+ "additionalProperties" => false
147
+ }
148
+ },
149
+ {
150
+ "name" => "instant_record_search",
151
+ "description" => "Case-insensitive multi-term search across one or all synced models in the local SQLite replica (<1ms offline).",
152
+ "inputSchema" => {
153
+ "type" => "object",
154
+ "properties" => {
155
+ "query" => { "type" => "string", "description" => "Search query string (whitespace-separated terms must all match)." },
156
+ "models" => {
157
+ "type" => "array",
158
+ "items" => { "type" => "string" },
159
+ "description" => "Optional list of models to restrict search to."
160
+ },
161
+ "columns" => {
162
+ "type" => "array",
163
+ "items" => { "type" => "string" },
164
+ "description" => "Optional list of columns to search (when restricting to models that share those columns)."
165
+ },
166
+ "limit" => { "type" => "integer", "minimum" => 1, "maximum" => 500, "default" => 50 }
167
+ },
168
+ "required" => ["query"],
169
+ "additionalProperties" => false
170
+ }
171
+ },
172
+ {
173
+ "name" => "instant_record_outbox",
174
+ "description" => "Inspect locally queued offline outbox mutations waiting to sync to the server (<1ms offline).",
175
+ "inputSchema" => {
176
+ "type" => "object",
177
+ "properties" => {
178
+ "limit" => { "type" => "integer", "minimum" => 1, "maximum" => 500, "default" => 100 }
179
+ },
180
+ "additionalProperties" => false
181
+ }
182
+ },
183
+ {
184
+ "name" => "instant_record_render_screen",
185
+ "description" => "Render a compiled native screen (app/screens/*_screen.rb) from the local SQLite replica as structured JSON (<1ms offline).",
186
+ "inputSchema" => {
187
+ "type" => "object",
188
+ "properties" => {
189
+ "screen" => { "type" => "string", "description" => "Screen name (e.g. mailbox, thread)." },
190
+ "params" => { "type" => "object", "description" => "Screen parameters (string key/value pairs)." }
191
+ },
192
+ "required" => ["screen"],
193
+ "additionalProperties" => false
194
+ }
195
+ },
196
+ {
197
+ "name" => "instant_record_action",
198
+ "description" => "Execute a validated local native screen action (Screen#perform) inside the compiled host offline, running validations and queueing outbox mutations (<1ms offline).",
199
+ "inputSchema" => {
200
+ "type" => "object",
201
+ "properties" => {
202
+ "screen" => { "type" => "string", "description" => "Screen name." },
203
+ "action" => { "type" => "string", "description" => "Action name passed to Screen#perform." },
204
+ "params" => { "type" => "object", "description" => "Screen parameters." },
205
+ "args" => { "type" => "object", "description" => "Action arguments." },
206
+ "values" => { "type" => "object", "description" => "Form field values." },
207
+ "render" => { "type" => "boolean", "description" => "Re-render the screen after the action.", "default" => false },
208
+ "sync" => { "type" => "boolean", "description" => "Run a sync pass immediately after the action.", "default" => false }
209
+ },
210
+ "required" => %w[screen action],
211
+ "additionalProperties" => false
212
+ }
213
+ },
214
+ {
215
+ "name" => "instant_record_request",
216
+ "description" => "Dispatch a validated local HTTP request (GET/POST/PATCH/DELETE) through the compiled Rails app inside the native host offline, running controller & model validations and queueing outbox mutations (<1ms offline).",
217
+ "inputSchema" => {
218
+ "type" => "object",
219
+ "properties" => {
220
+ "method" => { "type" => "string", "enum" => %w[GET POST PATCH PUT DELETE], "description" => "HTTP method." },
221
+ "path" => { "type" => "string", "description" => "Application path (e.g. /todo/issues)." },
222
+ "params" => { "type" => "object", "description" => "Request parameters (encoded as query string for GET, form or JSON for writes)." },
223
+ "body" => { "type" => "string", "description" => "Optional raw request body." },
224
+ "content_type" => { "type" => "string", "description" => "Optional Content-Type header." },
225
+ "headers" => { "type" => "object", "description" => "Optional HTTP headers." },
226
+ "sync" => { "type" => "boolean", "description" => "Run a sync pass after a successful request.", "default" => false }
227
+ },
228
+ "required" => %w[method path],
229
+ "additionalProperties" => false
230
+ }
231
+ },
232
+ {
233
+ "name" => "instant_record_history",
234
+ "description" => "Inspect local history pagination state or fetch an older keyset history page from the server into the local SQLite replica.",
235
+ "inputSchema" => {
236
+ "type" => "object",
237
+ "properties" => {
238
+ "key" => { "type" => "string", "description" => "History pagination key (e.g. older:support)." },
239
+ "query" => { "type" => "string", "description" => "Optional /records query string to fetch from the server." },
240
+ "endpoint" => { "type" => "string", "description" => "Optional sync endpoint override." }
241
+ },
242
+ "required" => ["key"],
243
+ "additionalProperties" => false
244
+ }
245
+ }
246
+ ]
247
+ end
248
+
249
+ def resource_definitions
250
+ base = [
251
+ {
252
+ "uri" => "instant-record://status",
253
+ "name" => "Replica Status",
254
+ "description" => "Current sync cursor, pending outbox count, identity, and local SQLite replica metadata.",
255
+ "mimeType" => "application/json"
256
+ },
257
+ {
258
+ "uri" => "instant-record://models",
259
+ "name" => "Synced Models",
260
+ "description" => "Schema and row counts for every synced model in the local SQLite replica.",
261
+ "mimeType" => "application/json"
262
+ },
263
+ {
264
+ "uri" => "instant-record://outbox",
265
+ "name" => "Pending Outbox Mutations",
266
+ "description" => "Queued offline mutations waiting to sync to the Rails server.",
267
+ "mimeType" => "application/json"
268
+ }
269
+ ]
270
+
271
+ @runtime.list_models["models"].each do |model|
272
+ base << {
273
+ "uri" => "instant-record://models/#{model['name']}",
274
+ "name" => "#{model['name']} Records",
275
+ "description" => "Recent records of #{model['name']} (#{model['count']} local rows).",
276
+ "mimeType" => "application/json"
277
+ }
278
+ end
279
+ base
280
+ end
281
+
282
+ private
283
+
284
+ def handle_initialize(params)
285
+ requested = params["protocolVersion"].to_s
286
+ negotiated = SUPPORTED_PROTOCOLS.include?(requested) ? requested : DEFAULT_PROTOCOL
287
+ {
288
+ "protocolVersion" => negotiated,
289
+ "capabilities" => {
290
+ "tools" => {},
291
+ "resources" => {}
292
+ },
293
+ "serverInfo" => {
294
+ "name" => @name,
295
+ "version" => @version
296
+ }
297
+ }
298
+ end
299
+
300
+ def handle_tool_call(params)
301
+ name = params["name"].to_s
302
+ args = params["arguments"] || {}
303
+ raise ArgumentError, "Tool arguments must be an object" unless args.is_a?(Hash)
304
+
305
+ data = dispatch_tool(name, args)
306
+ is_error = data.is_a?(Hash) && data.key?("ok") && data["ok"] == false
307
+ tool_result(data, is_error: is_error)
308
+ rescue ArgumentError, Error => e
309
+ tool_result({ "ok" => false, "error" => e.message }, is_error: true)
310
+ end
311
+
312
+ def dispatch_tool(name, args)
313
+ case name
314
+ when "instant_record_status"
315
+ @runtime.status
316
+ when "instant_record_sync"
317
+ @runtime.sync(endpoint: args["endpoint"])
318
+ when "instant_record_models"
319
+ @runtime.list_models
320
+ when "instant_record_query"
321
+ @runtime.query_records(
322
+ model: args.fetch("model") { raise ArgumentError, "Missing required argument: model" },
323
+ where: args["where"] || {},
324
+ order: args["order"],
325
+ limit: args["limit"] || Replica::DEFAULT_LIMIT,
326
+ offset: args["offset"] || 0,
327
+ columns: args["columns"]
328
+ )
329
+ when "instant_record_get"
330
+ @runtime.get_record(
331
+ model: args.fetch("model") { raise ArgumentError, "Missing required argument: model" },
332
+ id: args.fetch("id") { raise ArgumentError, "Missing required argument: id" }
333
+ )
334
+ when "instant_record_search"
335
+ @runtime.search_records(
336
+ query: args.fetch("query") { raise ArgumentError, "Missing required argument: query" },
337
+ models: args["models"],
338
+ columns: args["columns"],
339
+ limit: args["limit"] || Replica::DEFAULT_LIMIT
340
+ )
341
+ when "instant_record_outbox"
342
+ @runtime.outbox(limit: args["limit"] || 100)
343
+ when "instant_record_render_screen"
344
+ @runtime.render_screen(
345
+ screen: args.fetch("screen") { raise ArgumentError, "Missing required argument: screen" },
346
+ params: args["params"] || {}
347
+ )
348
+ when "instant_record_action"
349
+ @runtime.perform_action(
350
+ screen: args.fetch("screen") { raise ArgumentError, "Missing required argument: screen" },
351
+ action: args.fetch("action") { raise ArgumentError, "Missing required argument: action" },
352
+ params: args["params"] || {},
353
+ args: args["args"] || {},
354
+ values: args["values"] || {},
355
+ render: !!args["render"],
356
+ sync: !!args["sync"]
357
+ )
358
+ when "instant_record_request"
359
+ @runtime.app_request(
360
+ method: args.fetch("method") { raise ArgumentError, "Missing required argument: method" },
361
+ path: args.fetch("path") { raise ArgumentError, "Missing required argument: path" },
362
+ params: args["params"],
363
+ body: args["body"],
364
+ headers: args["headers"] || {},
365
+ content_type: args["content_type"],
366
+ sync: !!args["sync"]
367
+ )
368
+ when "instant_record_history"
369
+ @runtime.fetch_history(
370
+ key: args.fetch("key") { raise ArgumentError, "Missing required argument: key" },
371
+ query: args["query"],
372
+ endpoint: args["endpoint"]
373
+ )
374
+ else
375
+ raise ArgumentError, "Unknown tool: #{name}"
376
+ end
377
+ end
378
+
379
+ def handle_resource_read(params)
380
+ uri = params["uri"].to_s
381
+ raise ArgumentError, "Missing required param: uri" if uri.empty?
382
+
383
+ data =
384
+ case uri
385
+ when "instant-record://status"
386
+ @runtime.status
387
+ when "instant-record://models"
388
+ @runtime.list_models
389
+ when "instant-record://outbox"
390
+ @runtime.outbox
391
+ when /\Ainstant-record:\/\/models\/(.+)\z/
392
+ @runtime.query_records(model: Regexp.last_match(1))
393
+ else
394
+ raise ArgumentError, "Unknown resource URI: #{uri}"
395
+ end
396
+
397
+ {
398
+ "contents" => [
399
+ {
400
+ "uri" => uri,
401
+ "mimeType" => "application/json",
402
+ "text" => JSON.generate(data)
403
+ }
404
+ ]
405
+ }
406
+ end
407
+
408
+ def tool_result(payload, is_error: false)
409
+ {
410
+ "content" => [{ "type" => "text", "text" => JSON.generate(payload) }],
411
+ "isError" => is_error
412
+ }
413
+ end
414
+
415
+ def result_response(id, result)
416
+ { "jsonrpc" => JSONRPC_VERSION, "id" => id, "result" => result }
417
+ end
418
+
419
+ def error_response(id, code, message)
420
+ { "jsonrpc" => JSONRPC_VERSION, "id" => id, "error" => { "code" => code, "message" => message } }
421
+ end
422
+
423
+ def write_response(payload)
424
+ @output.write("#{JSON.generate(payload)}\n")
425
+ @output.flush
426
+ end
427
+ end
428
+ end
429
+ end
@@ -0,0 +1,47 @@
1
+ require "pathname"
2
+ require_relative "version"
3
+ require_relative "mcp/http_exchange"
4
+ require_relative "mcp/host_process"
5
+ require_relative "mcp/replica"
6
+ require_relative "mcp/runtime"
7
+ require_relative "mcp/server"
8
+ require_relative "mcp/cli"
9
+
10
+ module InstantRecord
11
+ # Local MCP stdio server and offline CLI around a compiled native `host`
12
+ # binary (`InstantRecord::Compiler::NativeBuild`). Keeps a scoped local
13
+ # SQLite replica in sync with the Rails server using configurable auth and
14
+ # serves synced model queries, search, and validated local actions offline
15
+ # in sub-millisecond time.
16
+ module Mcp
17
+ Error = Class.new(StandardError)
18
+ HostError = Class.new(Error)
19
+ HostCrashedError = Class.new(HostError)
20
+
21
+ module_function
22
+
23
+ def default_host_path(root)
24
+ app_root = Pathname(root).expand_path
25
+ candidates = [
26
+ app_root.join("tmp/instant_record/compiled/.build-native/host"),
27
+ app_root.join("../compiled/.build-native/host").cleanpath
28
+ ]
29
+ found = candidates.find { |path| path.file? && path.executable? }
30
+ (found || candidates.first).to_s
31
+ end
32
+
33
+ def default_database_path(root, scope: nil)
34
+ slug = scope.to_s.strip.gsub(/[^a-zA-Z0-9._-]+/, "_")
35
+ slug = "default" if slug.empty?
36
+ Pathname(root).expand_path.join("tmp/instant_record/mcp", "#{slug}.sqlite3").to_s
37
+ end
38
+
39
+ def runtime(**options)
40
+ Runtime.new(**options)
41
+ end
42
+
43
+ def server(runtime, **options)
44
+ Server.new(runtime, **options)
45
+ end
46
+ end
47
+ end