nodecode 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 95a912a8b03168006180f49b5d8f0958ee3725ce8aa162edcde82cde9e3e95fb
4
+ data.tar.gz: 5ecffa5becbac13595aa895aaeafd8f4c32e2b72025536e0e0de7a931781c88e
5
+ SHA512:
6
+ metadata.gz: '093616ec606f9913071ddc9c050e9e97aa7b550cbd3fc22c71eec3544c0b7f0acc53bbccfb2d5d2e562ad81e91e00b792f8de1c0508c43127d50f05097cbe818'
7
+ data.tar.gz: 5e8bb029af3df687a7e0ce9b0d8c17eb59e8e984079e54c2fcd6107ac8220eae0117507bbf41b0bd5e0c46557c0d5a7ce843fc1e386c87d4906bf1a3c8e46b45
data/.yardopts ADDED
@@ -0,0 +1,7 @@
1
+ --markup markdown
2
+ --readme README.md
3
+ --title "Nodecode Ruby SDK"
4
+ --no-private
5
+ lib/**/*.rb
6
+ -
7
+ LICENSE
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Foresight Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,147 @@
1
+ # nodecode (Ruby SDK)
2
+
3
+ Zero-dependency Ruby SDK for the [Nodecode](https://nodecode.ai/) inference API ([Cyber v1](https://nodecode.ai/cyber), Decide v1, Image v1) and Streamable HTTP [Model Context Protocol (MCP)](https://nodecode.ai/docs/cyber) endpoint, maintained by Foresight Labs (based in the EU, architectural [Zero Data Retention](https://nodecode.ai/zero-data-retention), zero KYC).
4
+
5
+ Built directly on Ruby's standard `Net::HTTP`, `URI`, and `JSON` libraries with zero third-party runtime dependencies.
6
+
7
+ ## Features
8
+
9
+ - **OpenAI-compatible chat and SSE streaming:** `chat_completion` and `chat_completion_stream` with first-class Cyber v1 reasoning extraction (`Nodecode.first_reasoning`, `Nodecode.delta_reasoning`).
10
+ - **Anthropic Messages support:** `anthropic_messages` sends `x-api-key` and `anthropic-version: 2023-06-01` to `/v1/messages`.
11
+ - **OpenAI Responses, models, images, and balance:** `responses`, `list_models`, `get_model`, `generate_image`, `Nodecode.decode_image_bytes`, `agent_balance`, and `list_crypto_coins`.
12
+ - **Structured HTTP error classes:** `AuthenticationError` (401), `InsufficientBalanceError` (402 with `refill_url`), `RateLimitError` (429), and `ServerError` (5xx) carrying status codes and request IDs.
13
+ - **Streamable HTTP MCP client (`Nodecode::MCP::Client`):** `initialize_session`, `list_tools`, `call_tool`, `list_resources`, `read_resource`, and `ping` supporting both JSON and SSE responses plus `Mcp-Session-Id` tracking.
14
+
15
+ ## Installation
16
+
17
+ Install the gem from RubyGems:
18
+
19
+ ```sh
20
+ gem install nodecode
21
+ ```
22
+
23
+ Or add it to your `Gemfile`:
24
+
25
+ ```ruby
26
+ gem "nodecode", "~> 0.1"
27
+ ```
28
+
29
+ ## Quickstart
30
+
31
+ Create an API key at [nodecode.ai/account/keys](https://nodecode.ai/account/keys) and export `NODECODE_API_KEY`:
32
+
33
+ ```ruby
34
+ require "nodecode"
35
+
36
+ client = Nodecode.new
37
+
38
+ resp = client.chat_completion(
39
+ model: Nodecode::MODEL_CYBER_V1,
40
+ messages: [
41
+ { role: "user", content: "22/tcp and 8080/tcp are open. What next, in order?" }
42
+ ],
43
+ max_tokens: 600
44
+ )
45
+
46
+ puts Nodecode.first_reasoning(resp)
47
+ puts Nodecode.first_content(resp)
48
+ ```
49
+
50
+ ## Streaming (SSE)
51
+
52
+ ```ruby
53
+ require "nodecode"
54
+
55
+ client = Nodecode.new
56
+
57
+ summary = client.chat_completion_stream(
58
+ model: Nodecode::MODEL_CYBER_V1,
59
+ messages: [
60
+ { role: "user", content: "Audit this Dockerfile for privilege escalation." }
61
+ ],
62
+ max_tokens: 1024
63
+ ) do |chunk|
64
+ delta = Nodecode.delta_content(chunk)
65
+ print delta if delta
66
+ end
67
+
68
+ puts "\nFinish reason: #{summary[:finish_reason]}"
69
+ ```
70
+
71
+ ## Anthropic Messages API
72
+
73
+ ```ruby
74
+ require "nodecode"
75
+
76
+ client = Nodecode.new
77
+
78
+ msg = client.anthropic_messages(
79
+ model: Nodecode::MODEL_CYBER_V1,
80
+ max_tokens: 512,
81
+ system: "Respond concisely with concrete commands.",
82
+ messages: [
83
+ { role: "user", content: "Check an Nginx config for SSRF misconfigurations." }
84
+ ]
85
+ )
86
+
87
+ puts msg.dig("content", 0, "text")
88
+ ```
89
+
90
+ ## Streamable HTTP MCP Client
91
+
92
+ Connect directly to `https://nodecode.ai/mcp` (no API key needed for public discovery tools):
93
+
94
+ ```ruby
95
+ require "nodecode"
96
+
97
+ mcp = Nodecode::MCP::Client.new
98
+ mcp.initialize_session
99
+
100
+ tools = mcp.list_tools
101
+ puts tools["tools"].map { |t| t["name"] }.join(", ")
102
+
103
+ result = mcp.call_tool("list_models")
104
+ puts Nodecode::MCP::Client.tool_text(result)
105
+ ```
106
+
107
+ ## Error Handling
108
+
109
+ ```ruby
110
+ begin
111
+ client.chat_completion(messages: [{ role: "user", content: "Hello" }])
112
+ rescue Nodecode::InsufficientBalanceError => e
113
+ warn "Balance exhausted (HTTP #{e.status}): refill at #{e.refill_url}"
114
+ rescue Nodecode::RateLimitError => e
115
+ warn "Rate limited (request #{e.request_id}): #{e.message}"
116
+ rescue Nodecode::APIError => e
117
+ warn "API error #{e.status}: #{e.message}"
118
+ end
119
+ ```
120
+
121
+ ## Documentation & Links
122
+
123
+ - [Nodecode](https://nodecode.ai/) - homepage and overview
124
+ - [Cyber v1](https://nodecode.ai/cyber) - 1M-context security model
125
+ - [Cyber v1 API Quickstart](https://nodecode.ai/docs/cyber) - OpenAI, Anthropic, and MCP integration guide
126
+ - [Models Reference](https://nodecode.ai/docs/models) - Cyber v1, Decide v1, and Image v1 specs
127
+ - [Pricing](https://nodecode.ai/docs/pricing) - token and image rates
128
+ - [Zero Data Retention](https://nodecode.ai/zero-data-retention) - ZDR architecture and invariants
129
+ - [OpenAPI Spec](https://nodecode.ai/openapi.json) - machine-readable API schema
130
+
131
+ ## Development
132
+
133
+ Run the offline unit test suite (requires Ruby 3.1+, zero external gems):
134
+
135
+ ```sh
136
+ ruby test/run_tests.rb
137
+ ```
138
+
139
+ Run the live unauthenticated API and MCP smoke test:
140
+
141
+ ```sh
142
+ ruby scripts/live_smoke.rb
143
+ ```
144
+
145
+ ## License
146
+
147
+ MIT License. Copyright (c) 2026 Foresight Labs.
@@ -0,0 +1,425 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "uri"
6
+ require_relative "errors"
7
+ require_relative "sse"
8
+ require_relative "version"
9
+
10
+ module Nodecode
11
+ # HTTP client for the Nodecode inference API (Cyber v1, Decide v1, Image v1)
12
+ # and agent balance/onboarding endpoints.
13
+ #
14
+ # @see https://nodecode.ai/ Nodecode homepage
15
+ # @see https://nodecode.ai/docs/cyber Cyber v1 API documentation
16
+ # @see https://nodecode.ai/zero-data-retention Zero Data Retention architecture
17
+ class Client
18
+ # Default Anthropic API version header sent to +/v1/messages+.
19
+ DEFAULT_ANTHROPIC_VERSION = "2023-06-01"
20
+
21
+ # @return [String, nil] API key used for authenticated endpoints
22
+ attr_reader :api_key
23
+
24
+ # @return [String] base URL for inference endpoints (defaults to +https://api.nodecode.ai/v1+)
25
+ attr_reader :base_url
26
+
27
+ # @return [String] base URL for site/agent endpoints (defaults to +https://nodecode.ai+)
28
+ attr_reader :site_url
29
+
30
+ # @return [Numeric] TCP open timeout in seconds
31
+ attr_reader :open_timeout
32
+
33
+ # @return [Numeric] HTTP read timeout in seconds
34
+ attr_reader :read_timeout
35
+
36
+ # Creates a new Nodecode API client.
37
+ #
38
+ # @param api_key [String, nil] Nodecode API key (defaults to +ENV["NODECODE_API_KEY"]+)
39
+ # @param base_url [String] inference API base URL
40
+ # @param site_url [String] site base URL for agent balance/coins endpoints
41
+ # @param open_timeout [Numeric] socket connect timeout in seconds
42
+ # @param read_timeout [Numeric] HTTP read timeout in seconds
43
+ # @param user_agent [String] custom User-Agent header value
44
+ def initialize(
45
+ api_key: ENV["NODECODE_API_KEY"],
46
+ base_url: Nodecode::DEFAULT_BASE_URL,
47
+ site_url: Nodecode::DEFAULT_SITE_URL,
48
+ open_timeout: 15,
49
+ read_timeout: 300,
50
+ user_agent: "nodecode-ruby/#{Nodecode::VERSION}"
51
+ )
52
+ @api_key = api_key
53
+ @base_url = base_url.to_s.sub(%r{/\z}, "")
54
+ @site_url = site_url.to_s.sub(%r{/\z}, "")
55
+ @open_timeout = open_timeout
56
+ @read_timeout = read_timeout
57
+ @user_agent = user_agent
58
+ end
59
+
60
+ # Lists all public Nodecode models and live pricing metadata.
61
+ #
62
+ # No API key is required for this endpoint.
63
+ #
64
+ # @return [Hash] parsed JSON list response containing +"data"+ and +"onboarding"+
65
+ def list_models
66
+ request_json(:get, "#{@base_url}/models", require_auth: false)
67
+ end
68
+
69
+ # Fetches metadata and pricing for a single model ID.
70
+ #
71
+ # @param model_id [String] model identifier such as +"nodecode-cyber-v1"+
72
+ # @return [Hash] parsed model object
73
+ def get_model(model_id)
74
+ encoded = URI.encode_www_form_component(model_id.to_s)
75
+ request_json(:get, "#{@base_url}/models/#{encoded}", require_auth: false)
76
+ end
77
+
78
+ # Creates an OpenAI-compatible chat completion (+POST /v1/chat/completions+).
79
+ #
80
+ # @param messages [Array<Hash>] conversation messages (+role+ and +content+)
81
+ # @param model [String] model identifier (defaults to {Nodecode::MODEL_CYBER_V1})
82
+ # @param max_tokens [Integer, nil] maximum completion tokens
83
+ # @param temperature [Float, nil] sampling temperature
84
+ # @param top_p [Float, nil] nucleus sampling threshold
85
+ # @param tools [Array<Hash>, nil] optional OpenAI tool definitions
86
+ # @param tool_choice [String, Hash, nil] optional tool choice directive
87
+ # @param reasoning_effort [String, nil] optional reasoning effort level
88
+ # @param extra [Hash] additional top-level JSON parameters
89
+ # @return [Hash] parsed chat completion response
90
+ def chat_completion(
91
+ messages:,
92
+ model: Nodecode::MODEL_CYBER_V1,
93
+ max_tokens: nil,
94
+ temperature: nil,
95
+ top_p: nil,
96
+ tools: nil,
97
+ tool_choice: nil,
98
+ reasoning_effort: nil,
99
+ extra: {}
100
+ )
101
+ payload = compact_payload(
102
+ {
103
+ "model" => model,
104
+ "messages" => messages,
105
+ "stream" => false,
106
+ "max_tokens" => max_tokens,
107
+ "temperature" => temperature,
108
+ "top_p" => top_p,
109
+ "tools" => tools,
110
+ "tool_choice" => tool_choice,
111
+ "reasoning_effort" => reasoning_effort
112
+ },
113
+ extra
114
+ )
115
+ request_json(:post, "#{@base_url}/chat/completions", body: payload)
116
+ end
117
+
118
+ # Streams an OpenAI-compatible chat completion over Server-Sent Events (SSE).
119
+ #
120
+ # Yields each parsed JSON chunk to the block and returns an aggregated summary Hash.
121
+ #
122
+ # @param messages [Array<Hash>] conversation messages
123
+ # @param model [String] model identifier (defaults to {Nodecode::MODEL_CYBER_V1})
124
+ # @param max_tokens [Integer, nil] maximum completion tokens
125
+ # @param temperature [Float, nil] sampling temperature
126
+ # @param top_p [Float, nil] nucleus sampling threshold
127
+ # @param tools [Array<Hash>, nil] optional OpenAI tool definitions
128
+ # @param tool_choice [String, Hash, nil] optional tool choice directive
129
+ # @param reasoning_effort [String, nil] optional reasoning effort level
130
+ # @param extra [Hash] additional top-level JSON parameters
131
+ # @yieldparam chunk [Hash] decoded SSE JSON chunk
132
+ # @return [Hash] aggregated summary with +:content+, +:reasoning+, +:finish_reason+, +:usage+, and +:chunks+
133
+ def chat_completion_stream(
134
+ messages:,
135
+ model: Nodecode::MODEL_CYBER_V1,
136
+ max_tokens: nil,
137
+ temperature: nil,
138
+ top_p: nil,
139
+ tools: nil,
140
+ tool_choice: nil,
141
+ reasoning_effort: nil,
142
+ extra: {},
143
+ &block
144
+ )
145
+ payload = compact_payload(
146
+ {
147
+ "model" => model,
148
+ "messages" => messages,
149
+ "stream" => true,
150
+ "max_tokens" => max_tokens,
151
+ "temperature" => temperature,
152
+ "top_p" => top_p,
153
+ "tools" => tools,
154
+ "tool_choice" => tool_choice,
155
+ "reasoning_effort" => reasoning_effort
156
+ },
157
+ extra
158
+ )
159
+
160
+ content = +""
161
+ reasoning = +""
162
+ finish_reason = nil
163
+ usage = nil
164
+ chunks = []
165
+
166
+ uri = URI.parse("#{@base_url}/chat/completions")
167
+ headers = build_headers(auth: :bearer, accept: "text/event-stream", content_type: "application/json")
168
+
169
+ with_http(uri) do |http|
170
+ req = Net::HTTP::Post.new(uri.request_uri, headers)
171
+ req.body = JSON.generate(payload)
172
+
173
+ http.request(req) do |resp|
174
+ status = resp.code.to_i
175
+ unless (200..299).cover?(status)
176
+ raise build_api_error(status, resp.body.to_s, resp)
177
+ end
178
+
179
+ parser = SSE::Parser.new do |event|
180
+ data = event[:data].to_s.strip
181
+ next if data.empty? || data == "[DONE]"
182
+
183
+ chunk = JSON.parse(data)
184
+ chunks << chunk
185
+ usage = chunk["usage"] if chunk["usage"]
186
+
187
+ delta_text = Nodecode.delta_content(chunk)
188
+ content << delta_text if delta_text
189
+
190
+ delta_thought = Nodecode.delta_reasoning(chunk)
191
+ reasoning << delta_thought if delta_thought
192
+
193
+ choice = chunk.dig("choices", 0)
194
+ finish_reason = choice["finish_reason"] if choice && choice["finish_reason"]
195
+
196
+ block.call(chunk) if block_given?
197
+ end
198
+
199
+ resp.read_body { |piece| parser.feed(piece) }
200
+ parser.finish
201
+ end
202
+ end
203
+
204
+ {
205
+ content: content,
206
+ reasoning: reasoning,
207
+ finish_reason: finish_reason,
208
+ usage: usage,
209
+ chunks: chunks
210
+ }
211
+ end
212
+
213
+ # Calls the Anthropic-compatible Messages endpoint (+POST /v1/messages+).
214
+ #
215
+ # Sends +x-api-key+ and +anthropic-version+ headers automatically.
216
+ #
217
+ # @param messages [Array<Hash>] Anthropic-format message turns
218
+ # @param model [String] model identifier (defaults to {Nodecode::MODEL_CYBER_V1})
219
+ # @param max_tokens [Integer] maximum output tokens (required by Anthropic Messages schema)
220
+ # @param system [String, Array<Hash>, nil] optional system prompt
221
+ # @param temperature [Float, nil] sampling temperature
222
+ # @param anthropic_version [String] value for +anthropic-version+ header
223
+ # @param extra [Hash] additional JSON request keys
224
+ # @return [Hash] parsed Anthropic message response
225
+ def anthropic_messages(
226
+ messages:,
227
+ model: Nodecode::MODEL_CYBER_V1,
228
+ max_tokens: 1024,
229
+ system: nil,
230
+ temperature: nil,
231
+ anthropic_version: DEFAULT_ANTHROPIC_VERSION,
232
+ extra: {}
233
+ )
234
+ payload = compact_payload(
235
+ {
236
+ "model" => model,
237
+ "messages" => messages,
238
+ "max_tokens" => max_tokens,
239
+ "system" => system,
240
+ "temperature" => temperature
241
+ },
242
+ extra
243
+ )
244
+ request_json(
245
+ :post,
246
+ "#{@base_url}/messages",
247
+ body: payload,
248
+ auth: :anthropic,
249
+ extra_headers: { "anthropic-version" => anthropic_version }
250
+ )
251
+ end
252
+
253
+ # Calls the OpenAI-compatible Responses endpoint (+POST /v1/responses+).
254
+ #
255
+ # @param input [String, Array<Hash>] text or structured input items
256
+ # @param model [String] model identifier (defaults to {Nodecode::MODEL_CYBER_V1})
257
+ # @param max_output_tokens [Integer, nil] maximum output tokens
258
+ # @param instructions [String, nil] optional system instructions
259
+ # @param extra [Hash] additional JSON request keys
260
+ # @return [Hash] parsed response payload
261
+ def responses(input:, model: Nodecode::MODEL_CYBER_V1, max_output_tokens: nil, instructions: nil, extra: {})
262
+ payload = compact_payload(
263
+ {
264
+ "model" => model,
265
+ "input" => input,
266
+ "max_output_tokens" => max_output_tokens,
267
+ "instructions" => instructions
268
+ },
269
+ extra
270
+ )
271
+ request_json(:post, "#{@base_url}/responses", body: payload)
272
+ end
273
+
274
+ # Generates an image using Image v1 (+POST /v1/images/generations+).
275
+ #
276
+ # @param prompt [String] image prompt
277
+ # @param model [String] image model ID (defaults to {Nodecode::MODEL_IMAGE_V1})
278
+ # @param size [String, nil] optional image dimensions such as +"1024x1024"+
279
+ # @param response_format [String, nil] optional response format (e.g. +"b64_json"+)
280
+ # @param extra [Hash] additional JSON request keys
281
+ # @return [Hash] parsed image generation response
282
+ def generate_image(prompt:, model: Nodecode::MODEL_IMAGE_V1, size: nil, response_format: nil, extra: {})
283
+ payload = compact_payload(
284
+ {
285
+ "model" => model,
286
+ "prompt" => prompt,
287
+ "size" => size,
288
+ "response_format" => response_format
289
+ },
290
+ extra
291
+ )
292
+ request_json(:post, "#{@base_url}/images/generations", body: payload)
293
+ end
294
+
295
+ # Reads the current prepaid balance for the configured API key (+GET /api/v1/agent/balance+).
296
+ #
297
+ # @return [Hash] balance metadata returned by +nodecode.ai+
298
+ def agent_balance
299
+ request_json(:get, "#{@site_url}/api/v1/agent/balance", require_auth: true)
300
+ end
301
+
302
+ # Lists crypto coins supported for autonomous agent orders and top-ups (+GET /api/v1/agent/coins+).
303
+ #
304
+ # No API key is required for this endpoint.
305
+ #
306
+ # @return [Hash] parsed JSON containing +"coins"+
307
+ def list_crypto_coins
308
+ request_json(:get, "#{@site_url}/api/v1/agent/coins", require_auth: false)
309
+ end
310
+
311
+ private
312
+
313
+ def request_json(method, url, body: nil, auth: :bearer, require_auth: true, extra_headers: {})
314
+ uri = URI.parse(url)
315
+ auth_mode = require_auth ? auth : (@api_key && !@api_key.empty? ? auth : :none)
316
+ headers = build_headers(
317
+ auth: auth_mode,
318
+ accept: "application/json",
319
+ content_type: body.nil? ? nil : "application/json",
320
+ extra: extra_headers
321
+ )
322
+
323
+ raw_body = nil
324
+ status = nil
325
+ response = nil
326
+
327
+ with_http(uri) do |http|
328
+ req_class = method == :post ? Net::HTTP::Post : Net::HTTP::Get
329
+ req = req_class.new(uri.request_uri, headers)
330
+ req.body = JSON.generate(body) unless body.nil?
331
+ response = http.request(req)
332
+ status = response.code.to_i
333
+ raw_body = response.body.to_s
334
+ end
335
+
336
+ unless (200..299).cover?(status)
337
+ raise build_api_error(status, raw_body, response)
338
+ end
339
+
340
+ return {} if raw_body.strip.empty?
341
+
342
+ JSON.parse(raw_body)
343
+ end
344
+
345
+ def build_headers(auth:, accept:, content_type: nil, extra: {})
346
+ headers = {
347
+ "Accept" => accept,
348
+ "User-Agent" => @user_agent
349
+ }
350
+ headers["Content-Type"] = content_type if content_type
351
+
352
+ case auth
353
+ when :bearer
354
+ raise AuthenticationError.new("Missing Nodecode API key (set api_key: or NODECODE_API_KEY)", status: 401) if @api_key.nil? || @api_key.empty?
355
+
356
+ headers["Authorization"] = "Bearer #{@api_key}"
357
+ when :anthropic
358
+ raise AuthenticationError.new("Missing Nodecode API key (set api_key: or NODECODE_API_KEY)", status: 401) if @api_key.nil? || @api_key.empty?
359
+
360
+ headers["x-api-key"] = @api_key
361
+ end
362
+
363
+ extra.each { |k, v| headers[k.to_s] = v.to_s unless v.nil? }
364
+ headers
365
+ end
366
+
367
+ def with_http(uri)
368
+ http = Net::HTTP.new(uri.host, uri.port)
369
+ http.use_ssl = (uri.scheme == "https")
370
+ http.open_timeout = @open_timeout
371
+ http.read_timeout = @read_timeout
372
+ http.start { |conn| yield conn }
373
+ end
374
+
375
+ def compact_payload(base, extra)
376
+ merged = base.reject { |_, v| v.nil? }
377
+ extra.each { |k, v| merged[k.to_s] = v unless v.nil? } if extra
378
+ merged
379
+ end
380
+
381
+ def build_api_error(status, raw_body, response)
382
+ parsed = begin
383
+ JSON.parse(raw_body)
384
+ rescue JSON::ParserError
385
+ nil
386
+ end
387
+
388
+ err_obj = parsed.is_a?(Hash) && parsed["error"].is_a?(Hash) ? parsed["error"] : nil
389
+ message =
390
+ if err_obj && err_obj["message"]
391
+ err_obj["message"].to_s
392
+ elsif parsed.is_a?(Hash) && parsed["message"]
393
+ parsed["message"].to_s
394
+ elsif !raw_body.strip.empty?
395
+ raw_body.strip[0, 300]
396
+ else
397
+ "Nodecode API returned HTTP #{status}"
398
+ end
399
+
400
+ request_id = response && (response["x-request-id"] || response["request-id"])
401
+ error_type = err_obj && err_obj["type"]
402
+ error_code = err_obj && err_obj["code"]
403
+ refill_url = (err_obj && (err_obj["refill_url"] || err_obj["topup_url"])) ||
404
+ (parsed.is_a?(Hash) && (parsed["refill_url"] || parsed["topup_url"]))
405
+
406
+ klass = case status
407
+ when 401 then AuthenticationError
408
+ when 402 then InsufficientBalanceError
409
+ when 429 then RateLimitError
410
+ when 500..599 then ServerError
411
+ else APIError
412
+ end
413
+
414
+ klass.new(
415
+ message,
416
+ status: status,
417
+ body: parsed || raw_body,
418
+ request_id: request_id,
419
+ error_type: error_type,
420
+ error_code: error_code,
421
+ refill_url: refill_url
422
+ )
423
+ end
424
+ end
425
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nodecode
4
+ # Base error raised by the Nodecode Ruby SDK.
5
+ class Error < StandardError; end
6
+
7
+ # Raised when the Nodecode HTTP API returns a non-2xx status code.
8
+ class APIError < Error
9
+ # @return [Integer] HTTP status code returned by the API
10
+ attr_reader :status
11
+
12
+ # @return [Hash, String, nil] parsed JSON response body or raw response text
13
+ attr_reader :body
14
+
15
+ # @return [String, nil] request identifier header if present
16
+ attr_reader :request_id
17
+
18
+ # @return [String, nil] API error type string if present
19
+ attr_reader :error_type
20
+
21
+ # @return [String, nil] API error code string if present
22
+ attr_reader :error_code
23
+
24
+ # @return [String, nil] top-up or billing URL returned on HTTP 402 responses
25
+ attr_reader :refill_url
26
+
27
+ # @param message [String] human-readable error message
28
+ # @param status [Integer] HTTP status code
29
+ # @param body [Hash, String, nil] response payload
30
+ # @param request_id [String, nil] optional request ID from headers
31
+ # @param error_type [String, nil] optional API error type
32
+ # @param error_code [String, nil] optional API error code
33
+ # @param refill_url [String, nil] optional refill URL for 402 responses
34
+ def initialize(message, status:, body: nil, request_id: nil, error_type: nil, error_code: nil, refill_url: nil)
35
+ @status = status
36
+ @body = body
37
+ @request_id = request_id
38
+ @error_type = error_type
39
+ @error_code = error_code
40
+ @refill_url = refill_url
41
+ super(message)
42
+ end
43
+ end
44
+
45
+ # Raised on HTTP 401 authentication failures.
46
+ class AuthenticationError < APIError; end
47
+
48
+ # Raised on HTTP 402 insufficient credit balance responses.
49
+ class InsufficientBalanceError < APIError; end
50
+
51
+ # Raised on HTTP 429 rate limit responses.
52
+ class RateLimitError < APIError; end
53
+
54
+ # Raised on HTTP 5xx upstream or gateway failures.
55
+ class ServerError < APIError; end
56
+
57
+ # Raised when a Streamable HTTP MCP JSON-RPC call fails.
58
+ class MCPError < Error
59
+ # @return [Integer, nil] JSON-RPC error code if provided
60
+ attr_reader :code
61
+
62
+ # @return [Object, nil] optional JSON-RPC error data payload
63
+ attr_reader :data
64
+
65
+ # @param message [String] error message
66
+ # @param code [Integer, nil] JSON-RPC error code
67
+ # @param data [Object, nil] optional error data
68
+ def initialize(message, code: nil, data: nil)
69
+ @code = code
70
+ @data = data
71
+ super(message)
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,204 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "uri"
6
+ require_relative "errors"
7
+ require_relative "sse"
8
+ require_relative "version"
9
+
10
+ module Nodecode
11
+ # Streamable HTTP Model Context Protocol (MCP) JSON-RPC 2.0 client.
12
+ #
13
+ # Connects to +https://nodecode.ai/mcp+ (or any Streamable HTTP MCP server),
14
+ # tracks +Mcp-Session-Id+ headers across calls, and decodes both JSON and SSE responses.
15
+ #
16
+ # @see https://nodecode.ai/docs/cyber Nodecode Cyber v1 & MCP documentation
17
+ module MCP
18
+ # Default MCP protocol version advertised during +initialize+.
19
+ PROTOCOL_VERSION = "2025-03-26"
20
+
21
+ # Stateful Streamable HTTP client for an MCP server.
22
+ class Client
23
+ # @return [String] MCP endpoint URL
24
+ attr_reader :endpoint
25
+
26
+ # @return [String, nil] active +Mcp-Session-Id+ assigned by the server
27
+ attr_reader :session_id
28
+
29
+ # @param endpoint [String] Streamable HTTP MCP URL (defaults to {Nodecode::DEFAULT_MCP_URL})
30
+ # @param api_key [String, nil] optional Bearer API key
31
+ # @param open_timeout [Numeric] connect timeout in seconds
32
+ # @param read_timeout [Numeric] read timeout in seconds
33
+ # @param user_agent [String] custom User-Agent string
34
+ def initialize(
35
+ endpoint: Nodecode::DEFAULT_MCP_URL,
36
+ api_key: nil,
37
+ open_timeout: 15,
38
+ read_timeout: 60,
39
+ user_agent: "nodecode-ruby/#{Nodecode::VERSION}"
40
+ )
41
+ @endpoint = endpoint.to_s
42
+ @api_key = api_key
43
+ @open_timeout = open_timeout
44
+ @read_timeout = read_timeout
45
+ @user_agent = user_agent
46
+ @session_id = nil
47
+ @next_id = 0
48
+ end
49
+
50
+ # Performs the MCP +initialize+ handshake.
51
+ #
52
+ # @param client_name [String] MCP client identifier
53
+ # @param client_version [String] MCP client version
54
+ # @param protocol_version [String] MCP protocol revision string
55
+ # @return [Hash] server capabilities and metadata
56
+ def initialize_session(
57
+ client_name: "nodecode-ruby",
58
+ client_version: Nodecode::VERSION,
59
+ protocol_version: PROTOCOL_VERSION
60
+ )
61
+ rpc(
62
+ "initialize",
63
+ {
64
+ "protocolVersion" => protocol_version,
65
+ "capabilities" => {},
66
+ "clientInfo" => {
67
+ "name" => client_name,
68
+ "version" => client_version
69
+ }
70
+ }
71
+ )
72
+ end
73
+
74
+ # Lists available tools on the MCP server (+tools/list+).
75
+ #
76
+ # @return [Hash] tool catalog payload containing +"tools"+
77
+ def list_tools
78
+ rpc("tools/list", {})
79
+ end
80
+
81
+ # Invokes a tool on the MCP server (+tools/call+).
82
+ #
83
+ # @param name [String] tool name (e.g. +"list_models"+ or +"list_crypto_coins"+)
84
+ # @param arguments [Hash] JSON-serializable tool arguments
85
+ # @return [Hash] tool call result containing +"content"+
86
+ def call_tool(name, arguments = {})
87
+ rpc("tools/call", { "name" => name.to_s, "arguments" => arguments || {} })
88
+ end
89
+
90
+ # Lists readable MCP resources (+resources/list+).
91
+ #
92
+ # @return [Hash] resource catalog payload
93
+ def list_resources
94
+ rpc("resources/list", {})
95
+ end
96
+
97
+ # Reads an MCP resource by URI (+resources/read+).
98
+ #
99
+ # @param uri [String] resource URI
100
+ # @return [Hash] resource content payload
101
+ def read_resource(uri)
102
+ rpc("resources/read", { "uri" => uri.to_s })
103
+ end
104
+
105
+ # Sends a JSON-RPC +ping+ request to the MCP server.
106
+ #
107
+ # @return [Hash] empty result object on success
108
+ def ping
109
+ rpc("ping", {})
110
+ end
111
+
112
+ # Sends a raw JSON-RPC 2.0 request to the MCP endpoint.
113
+ #
114
+ # @param method [String] JSON-RPC method name
115
+ # @param params [Hash] method parameters
116
+ # @return [Object] JSON-RPC +"result"+ value
117
+ def rpc(method, params = {})
118
+ @next_id += 1
119
+ req_id = @next_id
120
+ uri = URI.parse(@endpoint)
121
+
122
+ headers = {
123
+ "Content-Type" => "application/json",
124
+ "Accept" => "application/json, text/event-stream",
125
+ "User-Agent" => @user_agent
126
+ }
127
+ headers["Authorization"] = "Bearer #{@api_key}" if @api_key && !@api_key.empty?
128
+ headers["Mcp-Session-Id"] = @session_id if @session_id
129
+
130
+ http = Net::HTTP.new(uri.host, uri.port)
131
+ http.use_ssl = (uri.scheme == "https")
132
+ http.open_timeout = @open_timeout
133
+ http.read_timeout = @read_timeout
134
+
135
+ response = http.start do |conn|
136
+ req = Net::HTTP::Post.new(uri.request_uri, headers)
137
+ req.body = JSON.generate({
138
+ "jsonrpc" => "2.0",
139
+ "id" => req_id,
140
+ "method" => method,
141
+ "params" => params
142
+ })
143
+ conn.request(req)
144
+ end
145
+
146
+ @session_id = response["mcp-session-id"] if response["mcp-session-id"] && !response["mcp-session-id"].empty?
147
+
148
+ status = response.code.to_i
149
+ raw_body = response.body.to_s
150
+ unless (200..299).cover?(status)
151
+ raise MCPError.new("MCP HTTP #{status}: #{raw_body.strip[0, 300]}", code: status)
152
+ end
153
+
154
+ message = decode_response(response["content-type"].to_s, raw_body, req_id)
155
+ if message["error"]
156
+ err = message["error"]
157
+ raise MCPError.new(
158
+ err["message"].to_s,
159
+ code: err["code"],
160
+ data: err["data"]
161
+ )
162
+ end
163
+
164
+ message["result"]
165
+ end
166
+
167
+ # Extracts joined text blocks from a +tools/call+ result Hash.
168
+ #
169
+ # @param result [Hash] result returned by {#call_tool}
170
+ # @return [String] concatenated text content blocks
171
+ def self.tool_text(result)
172
+ return "" unless result.is_a?(Hash) && result["content"].is_a?(Array)
173
+
174
+ result["content"]
175
+ .select { |item| item.is_a?(Hash) && item["type"] == "text" && item["text"].is_a?(String) }
176
+ .map { |item| item["text"] }
177
+ .join("\n")
178
+ end
179
+
180
+ private
181
+
182
+ def decode_response(content_type, raw_body, expected_id)
183
+ if content_type.downcase.include?("text/event-stream")
184
+ messages = []
185
+ SSE.parse(raw_body) do |event|
186
+ data = event[:data].to_s.strip
187
+ next if data.empty?
188
+
189
+ parsed = JSON.parse(data)
190
+ messages << parsed if parsed.is_a?(Hash)
191
+ end
192
+ matched = messages.find { |m| m["id"] == expected_id } || messages.last
193
+ raise MCPError.new("Empty SSE response from MCP server") unless matched
194
+
195
+ matched
196
+ else
197
+ JSON.parse(raw_body)
198
+ end
199
+ rescue JSON::ParserError => e
200
+ raise MCPError.new("Invalid JSON from MCP server: #{e.message}")
201
+ end
202
+ end
203
+ end
204
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Nodecode
6
+ # Incremental Server-Sent Events (SSE) parser for streaming completions and MCP responses.
7
+ module SSE
8
+ # Parses an SSE stream from a String or chunked body reader.
9
+ #
10
+ # Yields each complete event as a Hash containing +:event+ and +:data+.
11
+ # Lines beginning with +:+ are ignored as SSE comments.
12
+ #
13
+ # @param input [String, #each_line] raw SSE text or line-iterable stream
14
+ # @yieldparam event [Hash] parsed SSE frame with +:event+ and +:data+ keys
15
+ # @return [Array<Hash>] all parsed events when no block is given
16
+ def self.parse(input, &block)
17
+ return enum_for(:parse, input).to_a unless block_given?
18
+
19
+ parser = Parser.new(&block)
20
+ if input.is_a?(String)
21
+ parser.feed(input)
22
+ else
23
+ input.each_line { |line| parser.feed(line) }
24
+ end
25
+ parser.finish
26
+ nil
27
+ end
28
+
29
+ # Incremental stateful SSE frame decoder that accepts arbitrary byte chunks.
30
+ class Parser
31
+ # @yieldparam event [Hash] parsed event hash (+:event+, +:data+, +:id+)
32
+ def initialize(&block)
33
+ @callback = block
34
+ @buffer = +""
35
+ @event_name = nil
36
+ @event_id = nil
37
+ @data_lines = []
38
+ end
39
+
40
+ # Feeds a chunk of UTF-8 text into the parser and dispatches any completed events.
41
+ #
42
+ # @param chunk [String] incoming chunk from an HTTP stream
43
+ # @return [void]
44
+ def feed(chunk)
45
+ return if chunk.nil? || chunk.empty?
46
+
47
+ @buffer << chunk
48
+ while (newline_idx = @buffer.index("\n"))
49
+ line = @buffer.slice!(0..newline_idx)
50
+ line = line.chomp("\n").chomp("\r")
51
+ process_line(line)
52
+ end
53
+ end
54
+
55
+ # Flushes any remaining buffered line or event at end-of-stream.
56
+ #
57
+ # @return [void]
58
+ def finish
59
+ unless @buffer.empty?
60
+ line = @buffer.chomp("\r")
61
+ @buffer.clear
62
+ process_line(line)
63
+ end
64
+ dispatch_event
65
+ end
66
+
67
+ private
68
+
69
+ def process_line(line)
70
+ if line.empty?
71
+ dispatch_event
72
+ return
73
+ end
74
+
75
+ return if line.start_with?(":")
76
+
77
+ field, value = line.split(":", 2)
78
+ value = value.nil? ? "" : value.sub(/\A /, "")
79
+
80
+ case field
81
+ when "event"
82
+ @event_name = value
83
+ when "data"
84
+ @data_lines << value
85
+ when "id"
86
+ @event_id = value unless value.include?("\0")
87
+ end
88
+ end
89
+
90
+ def dispatch_event
91
+ return if @data_lines.empty? && @event_name.nil?
92
+
93
+ payload = {
94
+ event: @event_name || "message",
95
+ data: @data_lines.join("\n")
96
+ }
97
+ payload[:id] = @event_id if @event_id
98
+
99
+ @event_name = nil
100
+ @event_id = nil
101
+ @data_lines = []
102
+
103
+ @callback.call(payload) if @callback
104
+ end
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nodecode
4
+ # Current semantic version of the Nodecode Ruby SDK.
5
+ VERSION = "0.1.0"
6
+ end
data/lib/nodecode.rb ADDED
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "nodecode/version"
4
+ require_relative "nodecode/errors"
5
+ require_relative "nodecode/sse"
6
+ require_relative "nodecode/client"
7
+ require_relative "nodecode/mcp"
8
+
9
+ # Zero-dependency Ruby SDK for the Nodecode inference API (Cyber v1, Decide v1, Image v1)
10
+ # and Streamable HTTP Model Context Protocol (MCP) endpoint.
11
+ #
12
+ # @see https://nodecode.ai/ Nodecode
13
+ # @see https://nodecode.ai/cyber Cyber v1 security model
14
+ # @see https://nodecode.ai/docs/cyber Cyber v1 API quickstart
15
+ # @see https://nodecode.ai/zero-data-retention Architectural Zero Data Retention
16
+ module Nodecode
17
+ # Default inference API base URL.
18
+ DEFAULT_BASE_URL = "https://api.nodecode.ai/v1"
19
+
20
+ # Default Nodecode site base URL for agent onboarding and balance endpoints.
21
+ DEFAULT_SITE_URL = "https://nodecode.ai"
22
+
23
+ # Default Streamable HTTP MCP endpoint.
24
+ DEFAULT_MCP_URL = "https://nodecode.ai/mcp"
25
+
26
+ # Model identifier for Cyber v1 (1M context security reasoning model).
27
+ MODEL_CYBER_V1 = "nodecode-cyber-v1"
28
+
29
+ # Model identifier for Decide v1 (fast classifier model).
30
+ MODEL_DECIDE_V1 = "nodecode-decide-v1"
31
+
32
+ # Model identifier for Image v1 (image generation model).
33
+ MODEL_IMAGE_V1 = "nodecode-image-v1"
34
+
35
+ # Convenience constructor returning a {Nodecode::Client}.
36
+ #
37
+ # @param kwargs [Hash] keyword arguments forwarded to {Nodecode::Client#initialize}
38
+ # @return [Nodecode::Client]
39
+ def self.new(**kwargs)
40
+ Client.new(**kwargs)
41
+ end
42
+
43
+ # Extracts the assistant text content from the first choice of a chat completion response.
44
+ #
45
+ # @param response [Hash] chat completion response hash
46
+ # @return [String, nil]
47
+ def self.first_content(response)
48
+ return nil unless response.is_a?(Hash)
49
+
50
+ response.dig("choices", 0, "message", "content")
51
+ end
52
+
53
+ # Extracts Cyber v1 reasoning text from the first choice of a chat completion response.
54
+ #
55
+ # Checks both +reasoning_content+ and +reasoning+ fields.
56
+ #
57
+ # @param response [Hash] chat completion response hash
58
+ # @return [String, nil]
59
+ def self.first_reasoning(response)
60
+ return nil unless response.is_a?(Hash)
61
+
62
+ msg = response.dig("choices", 0, "message")
63
+ return nil unless msg.is_a?(Hash)
64
+
65
+ msg["reasoning_content"] || msg["reasoning"]
66
+ end
67
+
68
+ # Extracts incremental text content from a streaming chat completion chunk.
69
+ #
70
+ # @param chunk [Hash] decoded SSE chunk hash
71
+ # @return [String, nil]
72
+ def self.delta_content(chunk)
73
+ return nil unless chunk.is_a?(Hash)
74
+
75
+ chunk.dig("choices", 0, "delta", "content")
76
+ end
77
+
78
+ # Extracts incremental Cyber v1 reasoning text from a streaming chat completion chunk.
79
+ #
80
+ # @param chunk [Hash] decoded SSE chunk hash
81
+ # @return [String, nil]
82
+ def self.delta_reasoning(chunk)
83
+ return nil unless chunk.is_a?(Hash)
84
+
85
+ delta = chunk.dig("choices", 0, "delta")
86
+ return nil unless delta.is_a?(Hash)
87
+
88
+ delta["reasoning_content"] || delta["reasoning"]
89
+ end
90
+
91
+ # Decodes base64 image bytes from the first entry of a {Nodecode::Client#generate_image} response.
92
+ #
93
+ # @param response [Hash] response returned by {Nodecode::Client#generate_image}
94
+ # @return [String, nil] binary image bytes or +nil+ if +b64_json+ is absent
95
+ def self.decode_image_bytes(response)
96
+ return nil unless response.is_a?(Hash)
97
+
98
+ b64 = response.dig("data", 0, "b64_json")
99
+ return nil unless b64.is_a?(String) && !b64.empty?
100
+
101
+ b64.unpack1("m")
102
+ end
103
+ end
metadata ADDED
@@ -0,0 +1,59 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nodecode
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Foresight Labs
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: |-
13
+ Zero-dependency Ruby client for the Nodecode inference API (Cyber v1, Decide v1, Image v1)
14
+ and Streamable HTTP Model Context Protocol (MCP) endpoint. Built directly on Ruby's standard
15
+ Net::HTTP and JSON libraries with OpenAI-compatible chat completions, SSE streaming,
16
+ Anthropic Messages support, OpenAI Responses support, image generation, and MCP tooling.
17
+ email:
18
+ - hi@nodecode.ai
19
+ executables: []
20
+ extensions: []
21
+ extra_rdoc_files: []
22
+ files:
23
+ - ".yardopts"
24
+ - LICENSE
25
+ - README.md
26
+ - lib/nodecode.rb
27
+ - lib/nodecode/client.rb
28
+ - lib/nodecode/errors.rb
29
+ - lib/nodecode/mcp.rb
30
+ - lib/nodecode/sse.rb
31
+ - lib/nodecode/version.rb
32
+ homepage: https://nodecode.ai/
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ homepage_uri: https://nodecode.ai/
37
+ source_code_uri: https://github.com/nodecode-ai/nodecode-ruby
38
+ documentation_uri: https://nodecode.ai/docs/cyber
39
+ bug_tracker_uri: https://github.com/nodecode-ai/nodecode-ruby/issues
40
+ changelog_uri: https://github.com/nodecode-ai/nodecode-ruby/releases
41
+ rdoc_options: []
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '3.1'
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirements: []
55
+ rubygems_version: 4.0.22
56
+ specification_version: 4
57
+ summary: Zero-dependency Ruby SDK for the Nodecode inference API (Cyber v1, Decide
58
+ v1, Image v1) and MCP
59
+ test_files: []