Skip to content

Conversation

@wonderwhy-er
Copy link
Owner

@wonderwhy-er wonderwhy-er commented Sep 5, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of configuration lists: accepts JSON-formatted strings, consistently converts single strings and scalar values into arrays, and logs clear errors on invalid JSON.
    • Stricter validation of configuration inputs to prevent unexpected types and provide clearer feedback.
  • Chores
    • Tightened input schema for configuration values to allow only strings, numbers, booleans, string arrays, or null.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 5, 2025

Walkthrough

Refines setConfigValue parsing for array-like settings in src/tools/config.ts, adding stricter JSON parsing and scalar-to-string coercion. Tightens input validation by narrowing SetConfigValueArgsSchema.value types in src/tools/schemas.ts from any to a specific union. No exported function signatures changed.

Changes

Cohort / File(s) Summary
Config parsing adjustments
src/tools/config.ts
Refactors handling of array-valued settings: preserves original string, attempts JSON.parse on strings, logs parse failures, wraps non-JSON strings without '[' as single-item arrays using the original string, coerces non-string scalars to strings before wrapping, leaves arrays unchanged.
Schema type narrowing
src/tools/schemas.ts
Narrows SetConfigValueArgsSchema.value from z.any() to a union: z.string(), z.number(), z.boolean(), z.array(z.string()), z.null().

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Config as setConfigValue
  participant JSON as JSON.parse
  participant Log as Logger
  participant Store as ConfigStore

  Caller->>Config: setConfigValue(key, value)
  alt value is array
    Config->>Store: save array value
  else value is string
    Config->>JSON: parse(originalString)
    alt parse succeeds
      JSON-->>Config: parsed (array/object)
      Config->>Store: save parsed
    else parse fails
      JSON-->>Config: error
      Config->>Log: log parse error
      alt originalString lacks '['
        Config->>Store: save [originalString]
      else
        Config->>Store: save originalString (string)
      end
    end
  else value is non-null, non-string scalar
    Config->>Store: save [String(value)]
  else value is null
    Config->>Store: save null
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through configs, nose to the wire,
Strings turn to arrays, as parsers conspire.
Booleans and numbers get wrapped just right,
Schemas now stricter, snug-fitting tight.
With a thump of joy, I stash and I log—
A tidy warren for every cog. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-set-config-schema

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/tools/config.ts (1)

86-110: Array-key normalization can yield ["[object Object]"] and mishandle null; enforce string[]

If a JSON string like "{...}" is parsed earlier, this branch converts the object to ["[object Object]"]. Also, null becomes ["null"]. For allowedDirectories/blockedCommands, normalize to string[], treat null as [], and only accept parsed arrays (fallback to single-item arrays otherwise).

Apply:

-      if ((parsed.data.key === 'allowedDirectories' || parsed.data.key === 'blockedCommands') && 
-          !Array.isArray(valueToStore)) {
-        if (typeof valueToStore === 'string') {
-          const originalString = valueToStore;
-          try {
-            const parsedValue = JSON.parse(originalString);
-            valueToStore = parsedValue;
-          } catch (parseError) {
-            console.error(`Failed to parse string as array for ${parsed.data.key}: ${parseError}`);
-            // If parsing failed and it's a single value, convert to an array with one item
-            if (!originalString.includes('[')) {
-              valueToStore = [originalString];
-            }
-          }
-        } else if (valueToStore !== null) {
-          // If not a string or array (and not null), convert to an array with one item
-          valueToStore = [String(valueToStore)];
-        }
-        
-        // Ensure the value is an array after all our conversions
-        if (!Array.isArray(valueToStore)) {
-          console.error(`Value for ${parsed.data.key} is still not an array, converting to array`);
-          valueToStore = [String(valueToStore)];
-        }
-      }
+      if (parsed.data.key === 'allowedDirectories' || parsed.data.key === 'blockedCommands') {
+        // Normalize strictly to string[]
+        if (valueToStore == null) {
+          valueToStore = [];
+        } else if (Array.isArray(valueToStore)) {
+          valueToStore = valueToStore.map(v => String(v));
+        } else if (typeof valueToStore === 'object') {
+          // Avoid leaking "[object Object]" into config
+          console.error(`Invalid object for ${parsed.data.key}; expected string or array. Coercing to empty array.`);
+          valueToStore = [];
+        } else if (typeof valueToStore === 'string') {
+          const s = valueToStore.trim();
+          if (s.startsWith('[')) {
+            try {
+              const parsedValue = JSON.parse(s);
+              valueToStore = Array.isArray(parsedValue) ? parsedValue.map(v => String(v)) : [s];
+            } catch {
+              valueToStore = [s];
+            }
+          } else {
+            valueToStore = [s];
+          }
+        } else {
+          valueToStore = [String(valueToStore)];
+        }
+      }
🧹 Nitpick comments (2)
src/tools/config.ts (2)

89-93: Redundant re-parse and lost original input

JSON.parse may already have run earlier (Lines 75–83). Re-parsing here using originalString only happens if the value is still a string; if it was already parsed to an object, you’ve lost the raw string. Capture the raw input once before any parsing and reuse it, or trim and parse in one place.

Example:

-      let valueToStore = parsed.data.value;
+      let valueToStore = parsed.data.value;
+      const rawInput = typeof parsed.data.value === 'string' ? parsed.data.value : undefined;

Then prefer rawInput?.trim() when parsing.


115-121: Avoid echoing full config (PII/paths) in success response

Returning updatedConfig verbatim can leak sensitive paths/client info to tool logs. Prefer echoing only the changed key or redact sensitive fields.

-          text: `Successfully set ${parsed.data.key} to ${JSON.stringify(valueToStore, null, 2)}\n\nUpdated configuration:\n${JSON.stringify(updatedConfig, null, 2)}`
+          text: `Successfully set ${parsed.data.key} to ${JSON.stringify(valueToStore, null, 2)}`
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e0c91f5 and 5a8908b.

📒 Files selected for processing (2)
  • src/tools/config.ts (1 hunks)
  • src/tools/schemas.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/tools/config.ts (3)
test/test-allowed-directories.js (2)
  • testSpecificAllowedDirectory (139-167)
  • testAllowedDirectories (364-386)
test/test-blocked-commands.js (3)
  • testNonBlockedCommands (144-171)
  • testEmptyBlockedCommands (231-250)
  • runBlockedCommandsTests (255-271)
src/config-manager.ts (1)
  • ServerConfig (9-19)
🔇 Additional comments (1)
src/tools/schemas.ts (1)

8-14: Validate external callers for new schema restrictions. No internal usages of setConfigValue or "set_config_value" passing complex objects or non-string arrays were found; confirm whether external clients rely on objects or other array types before narrowing this schema. Consider per-key schemas or expanding the union to include objects/non-string arrays.

@wonderwhy-er wonderwhy-er merged commit 9c40b47 into main Sep 9, 2025
2 checks passed
@wonderwhy-er wonderwhy-er deleted the fix-set-config-schema branch September 10, 2025 08:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants