Skip to content

feat: Add pagination support to console logs to prevent LLM token limits #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

Saqoosha
Copy link
Contributor

@Saqoosha Saqoosha commented Jun 1, 2025

🚨 Problem

When Unity console logs accumulate in large quantities (hundreds to thousands of entries), the get_console_logs function fails due to LLM token limit exceeded errors.

  • Actual Error: "response (27806 tokens) exceeds maximum allowed tokens (25000)"
  • Impact: MCP Unity debugging functionality becomes completely unusable
  • Occurrence: During extended Unity development sessions

⚡ Solution

Pagination Implementation

  • Added offset and limit parameters for chunked log retrieval
  • Newest-first chronological sorting for optimal debugging workflow
  • Detailed pagination metadata (totalCount, hasMore, etc.)

Memory Management Enhancement

  • Automatic cleanup functionality (max 1000 entries, remove 200 at a time)
  • Memory-efficient log management

Consistent Implementation Across Both Sides

  • Unity Side (C#): Added GetLogsAsJson(logType, offset, limit) method
  • Node.js Side (TypeScript): Extended parameter handling and URL templates

📊 Results

Dramatic Token Usage Reduction

  • Before: 27,806 tokens → Error
  • After: ~1,000 tokens (96% reduction)

Recommended Usage Examples

// Check latest 5 errors
get_console_logs({ limit: 5 })

// Retrieve specific page
get_console_logs({ offset: 10, limit: 20 })

// Paginated error log retrieval
get_console_logs({ logType: "error", limit: 10 })

Performance Improvements

  • Dramatically reduced response times
  • Stable operation in large log environments
  • Significantly improved debugging efficiency

🧪 Testing

Thoroughly tested with large volumes of test logs (Error/Exception/Assert/Warning/Info):

  • Pagination functionality accuracy
  • Stability under boundary conditions
  • Memory management effectiveness

📋 Technical Details

Unity Side Changes

  • Editor/Services/ConsoleLogsService.cs: Added paginated GetLogsAsJson method
  • Editor/Services/IConsoleLogsService.cs: Extended interface with pagination support
  • Editor/Resources/GetConsoleLogsResource.cs: Added parameter extraction and processing

Node.js Side Changes

  • Server~/src/tools/getConsoleLogsTool.ts: Added offset/limit parameters to Zod schema
  • Server~/src/resources/getConsoleLogsResource.ts: Extended URL template to support pagination

Key Features

  • Newest-first ordering: Most recent logs appear first for optimal debugging
  • Automatic memory cleanup: Prevents memory bloat during long sessions
  • Detailed pagination info: Provides comprehensive metadata for navigation
  • Backward compatibility: Existing get_console_logs calls continue to work unchanged

Breaking Changes: None (fully backward compatible)

🔍 Additional Implementation Details

Pagination Metadata Structure

The response now includes a detailed pagination object with:

"pagination": {
  "offset": 0,
  "limit": 50,
  "totalCount": 1000,
  "filteredCount": 200,
  "returnedCount": 50,
  "hasMore": true
}

Memory Management Constants

  • MaxLogEntries: 1000 (maximum logs stored in memory)
  • CleanupThreshold: 200 (number of oldest entries removed when exceeding max)

Resource URI Updates

Updated resource URI template to support pagination parameters:

unity://logs/{logType}?offset={offset}&limit={limit}

Enhanced Documentation

  • Updated all resource descriptions with pagination usage recommendations
  • Added parameter documentation with suggested limits (20-50 entries)
  • Included warnings about potential token limit issues

Created with Palmier

Summary by CodeRabbit

  • New Features

    • Added pagination support when retrieving Unity console logs, allowing users to specify the starting index and number of logs returned.
    • Console logs are now returned in newest-first order, including detailed metadata about total, filtered, and returned log counts.
    • Users can manually clean up old logs and view the current log count.
  • Improvements

    • Enhanced descriptions and documentation for console log retrieval tools and resources to clarify pagination usage and recommended parameters.
    • Default pagination parameters are set to prevent exceeding token or context limits.

- Add offset and limit parameters to GetConsoleLogsResource and GetConsoleLogsTool
- Implement GetLogsAsJson method with pagination in ConsoleLogsService
- Return logs in newest-first order for better debugging workflow
- Add automatic memory management with configurable cleanup thresholds
- Update resource descriptions with pagination usage recommendations
- Enhance Unity-side and Node.js-side implementations consistently

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Copy link
Contributor

coderabbitai bot commented Jun 1, 2025

📝 Walkthrough

Walkthrough

Pagination support was added to the Unity console logs retrieval pipeline across both the editor (C#) and server (JavaScript/TypeScript) layers. New methods and parameters enable clients to specify offset and limit, returning logs in newest-first order with metadata. Log retention is now capped with automatic cleanup, and interface contracts were updated accordingly.

Changes

File(s) Change Summary
Editor/Resources/GetConsoleLogsResource.cs Added pagination support (offset, limit) to log fetching; enhanced response structure and resource description.
Editor/Services/ConsoleLogsService.cs Added log retention limit, cleanup logic, paginated log retrieval, and log count methods.
Editor/Services/IConsoleLogsService.cs Extended interface with paginated retrieval, cleanup, and log count methods.
Server~/build/resources/getConsoleLogsResource.js
Server~/src/resources/getConsoleLogsResource.ts
Updated resource URI, handler, and descriptions to support and document pagination parameters.
Server~/build/tools/getConsoleLogsTool.js
Server~/src/tools/getConsoleLogsTool.ts
Extended tool parameter schema and handler to support offset and limit for pagination.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server (Resource/Tool)
    participant Unity Editor (ConsoleLogsService)

    Client->>Server (Resource/Tool): Request console logs (with offset, limit)
    Server->>Unity Editor: Fetch logs (offset, limit, logType)
    Unity Editor->>Unity Editor: Apply logType filter, offset, limit
    Unity Editor-->>Server (Resource/Tool): Paginated logs + metadata
    Server-->>Client: Paginated logs + metadata
Loading

Possibly related PRs

Poem

In the console’s warren, logs once ran free,
But now they hop in pages—one, two, three!
With offset and limit, the rabbit keeps count,
No more log avalanches, just a neat amount.
The warren is tidy, the carrots are bright—
Paginated logs make debugging light!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ca51d7 and 5e35e08.

📒 Files selected for processing (4)
  • Editor/Resources/GetConsoleLogsResource.cs (2 hunks)
  • Editor/Services/ConsoleLogsService.cs (5 hunks)
  • Editor/Services/IConsoleLogsService.cs (2 hunks)
  • Server~/src/resources/getConsoleLogsResource.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • Editor/Services/IConsoleLogsService.cs
  • Editor/Resources/GetConsoleLogsResource.cs
🧰 Additional context used
🧬 Code Graph Analysis (1)
Server~/src/resources/getConsoleLogsResource.ts (2)
Server~/build/utils/errors.js (1)
  • McpUnityError (10-26)
Server~/build/tools/getConsoleLogsTool.js (1)
  • response (61-68)
🔇 Additional comments (9)
Editor/Services/ConsoleLogsService.cs (6)

32-34: LGTM! Well-designed memory management constants.

The constants provide a good balance between keeping sufficient logs for debugging and preventing memory bloat. The 20% cleanup threshold (200 out of 1000) is efficient for batch removal.


81-87: Excellent pagination support with backward compatibility.

The method signature properly supports pagination while maintaining backward compatibility through default parameters. The default limit of 100 strikes a good balance between usefulness and token limits.


166-180: Well-implemented manual cleanup method.

The method provides good flexibility for manual log management with sensible defaults and efficient batch removal. Thread safety is properly maintained.


182-192: Simple and correct log count implementation.

Thread-safe getter method with proper locking. No issues detected.


242-247: Effective automatic memory management.

The automatic cleanup logic properly maintains memory limits by removing the oldest entries when the threshold is exceeded. Well-positioned in the log receiving callback.


115-143: ⚠️ Potential issue

Fix pagination logic: currentIndex should only increment for filtered entries.

The pagination logic has an issue where currentIndex is incremented for all filtered entries, but it should represent the position within the filtered results for correct offset handling.

                    // Count filtered entries
                    filteredCount++;
                    
-                    // Check if we're in the offset range and haven't reached the limit yet
-                    if (currentIndex >= offset && logsArray.Count < limit)
+                    // Check if we're in the offset range and haven't reached the limit yet  
+                    if (filteredCount - 1 >= offset && logsArray.Count < limit)
                    {
                        logsArray.Add(new JObject
                        {
                            ["message"] = entry.Message,
                            ["stackTrace"] = entry.StackTrace,
                            ["type"] = entry.Type.ToString(),
                            ["timestamp"] = entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
                        });
                    }
                    
-                    currentIndex++;
-                    
                    // Early exit if we've collected enough logs
-                    if (currentIndex >= offset + limit) break;
+                    if (filteredCount >= offset + limit) break;

Likely an incorrect or invalid review comment.

Server~/src/resources/getConsoleLogsResource.ts (3)

11-11: Proper URI template with pagination parameters.

The URI template correctly follows REST conventions by including pagination parameters as query parameters.


20-42: Well-designed resource list with thoughtful pagination defaults.

The resource list properly includes pagination parameters with sensible type-specific defaults. The descriptions clearly communicate the newest-first ordering and pagination behavior to users.


110-110: Response URI correctly reflects request parameters.

The response URI properly includes the pagination parameters used in the request, providing transparency and enabling proper debugging/logging.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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: 2

🧹 Nitpick comments (2)
Editor/Resources/GetConsoleLogsResource.cs (2)

29-55: Consider simplifying parameter extraction and adding validation.

While the current implementation works, it could be improved for maintainability and robustness:

-            string logType = null;
-            int offset = 0;
-            int limit = 100;
-            
-            if (parameters != null)
-            {
-                // Extract logType
-                if (parameters.ContainsKey("logType") && parameters["logType"] != null)
-                {
-                    logType = parameters["logType"].ToString()?.ToLowerInvariant();
-                    if (string.IsNullOrWhiteSpace(logType))
-                    {
-                        logType = null;
-                    }
-                }
-                
-                // Extract pagination parameters
-                if (parameters.ContainsKey("offset") && parameters["offset"] != null)
-                {
-                    int.TryParse(parameters["offset"].ToString(), out offset);
-                }
-                
-                if (parameters.ContainsKey("limit") && parameters["limit"] != null)
-                {
-                    int.TryParse(parameters["limit"].ToString(), out limit);
-                }
-            }
+            string logType = parameters?["logType"]?.ToString();
+            if (string.IsNullOrWhiteSpace(logType)) logType = null;
+            
+            int offset = Math.Max(0, GetIntParameter(parameters, "offset", 0));
+            int limit = Math.Max(1, Math.Min(1000, GetIntParameter(parameters, "limit", 100)));
+            
+        }
+        
+        private static int GetIntParameter(JObject parameters, string key, int defaultValue)
+        {
+            if (parameters?[key] != null && int.TryParse(parameters[key].ToString(), out int value))
+                return value;
+            return defaultValue;

This approach:

  • Simplifies logType extraction
  • Adds bounds validation for offset (≥0) and limit (1-1000)
  • Reduces code duplication with a helper method
  • Maintains the same functionality with better error handling

57-67: Consider safer pagination metadata access.

The response construction is well-designed, but the pagination object access could be more defensive:

-            var pagination = result["pagination"] as JObject;
-            string typeFilter = logType != null ? $" of type '{logType}'" : "";
-            result["message"] = $"Retrieved {pagination["returnedCount"]} of {pagination["filteredCount"]} log entries{typeFilter} (offset: {offset}, limit: {limit})";
+            var pagination = result["pagination"] as JObject;
+            string typeFilter = logType != null ? $" of type '{logType}'" : "";
+            int returnedCount = pagination?["returnedCount"]?.Value<int>() ?? 0;
+            int filteredCount = pagination?["filteredCount"]?.Value<int>() ?? 0;
+            result["message"] = $"Retrieved {returnedCount} of {filteredCount} log entries{typeFilter} (offset: {offset}, limit: {limit})";

This protects against potential null reference exceptions if the pagination object structure changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb4b03c and 925431d.

📒 Files selected for processing (7)
  • Editor/Resources/GetConsoleLogsResource.cs (1 hunks)
  • Editor/Services/ConsoleLogsService.cs (4 hunks)
  • Editor/Services/IConsoleLogsService.cs (2 hunks)
  • Server~/build/resources/getConsoleLogsResource.js (4 hunks)
  • Server~/build/tools/getConsoleLogsTool.js (2 hunks)
  • Server~/src/resources/getConsoleLogsResource.ts (5 hunks)
  • Server~/src/tools/getConsoleLogsTool.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
Server~/build/tools/getConsoleLogsTool.js (2)
Server~/build/resources/getConsoleLogsResource.js (4)
  • response (70-77)
  • logType (63-63)
  • offset (67-67)
  • limit (68-68)
Server~/build/index.js (1)
  • mcpUnity (40-40)
Editor/Services/IConsoleLogsService.cs (2)
Server~/build/resources/getConsoleLogsResource.js (3)
  • logType (63-63)
  • offset (67-67)
  • limit (68-68)
Editor/Services/ConsoleLogsService.cs (2)
  • CleanupOldLogs (164-174)
  • GetLogCount (180-186)
Server~/build/resources/getConsoleLogsResource.js (2)
Server~/build/tools/getConsoleLogsTool.js (1)
  • response (61-68)
Server~/build/utils/errors.js (1)
  • McpUnityError (10-26)
Server~/src/tools/getConsoleLogsTool.ts (3)
Server~/build/tools/getConsoleLogsTool.js (4)
  • toolDescription (5-5)
  • paramsSchema (6-24)
  • params (58-58)
  • response (61-68)
Server~/build/resources/getConsoleLogsResource.js (4)
  • response (70-77)
  • logType (63-63)
  • offset (67-67)
  • limit (68-68)
Server~/build/index.js (1)
  • mcpUnity (40-40)
Server~/src/resources/getConsoleLogsResource.ts (3)
Server~/build/resources/getConsoleLogsResource.js (6)
  • resourceUri (6-6)
  • offset (67-67)
  • limit (68-68)
  • response (70-77)
  • resourceName (4-4)
  • logType (63-63)
Server~/build/tools/getConsoleLogsTool.js (1)
  • response (61-68)
Server~/build/index.js (1)
  • mcpUnity (40-40)
🔇 Additional comments (23)
Server~/build/tools/getConsoleLogsTool.js (2)

5-24: LGTM! Well-designed pagination schema with appropriate constraints.

The updated tool description clearly communicates the pagination support, and the parameter schema is well-structured with:

  • Proper type validation and constraints (min/max values)
  • Sensible defaults (offset=0, limit=50)
  • Token limit protection (max 500)
  • Clear documentation for each parameter

58-67: LGTM! Clean parameter handling with consistent defaults.

The destructuring assignment properly extracts the new pagination parameters with appropriate defaults that match the schema definition. The parameter passing to Unity maintains consistency with the existing pattern.

Server~/src/tools/getConsoleLogsTool.ts (2)

10-31: LGTM! Excellent TypeScript implementation with proper type safety.

The parameter schema follows the same pattern as the JavaScript version with correct Zod validation. The type constraints and documentation are well-defined, maintaining consistency across the TypeScript and JavaScript implementations.


79-89: LGTM! Type-safe parameter handling with consistent implementation.

The function maintains proper TypeScript typing while implementing the pagination parameters correctly. The destructuring with defaults and parameter passing aligns perfectly with the schema definition and the compiled JavaScript version.

Editor/Services/IConsoleLogsService.cs (1)

20-49: LGTM! Well-designed interface extension for pagination and memory management.

The new method declarations properly support the pagination requirements:

  • GetLogsAsJson provides clean pagination with sensible defaults
  • CleanupOldLogs enables memory management as mentioned in PR objectives
  • GetLogCount supports monitoring of log storage
  • Comprehensive XML documentation for all methods
  • Consistent parameter naming and types

The slightly different default limit (100 vs 50 in tools) is acceptable as different layers can have different optimization strategies.

Editor/Resources/GetConsoleLogsResource.cs (1)

16-16: LGTM! Clear description with helpful performance guidance.

The updated description effectively communicates the pagination support and provides practical guidance on optimal limit values for LLM token management.

Server~/build/resources/getConsoleLogsResource.js (5)

6-6: LGTM!

The URI template correctly includes the pagination query parameters using standard URL query syntax.


16-16: Excellent user guidance!

The updated descriptions provide clear, actionable advice about pagination parameters to avoid token limit issues. The varying recommended limits per log type (50/20/30/25) show thoughtful consideration of typical log volumes.

Also applies to: 22-22, 28-28, 34-34


46-46: Good emphasis on pagination importance.

The "IMPORTANT" prefix and explicit warning about the default limit effectively communicates the necessity of using pagination parameters.


73-75: Parameters correctly passed to Unity request.

The pagination parameters are properly included in the request object alongside the existing logType parameter.


83-83: Response URI correctly reflects pagination parameters.

Including the actual pagination parameters in the response URI is good practice for transparency and debugging.

Server~/src/resources/getConsoleLogsResource.ts (5)

11-11: LGTM!

URI template correctly includes pagination query parameters.


22-22: Clear pagination guidance provided.

Descriptions effectively communicate pagination best practices and token limit concerns.

Also applies to: 28-28, 33-34, 40-40


57-57: Effective emphasis on pagination importance.

Clear warning about default limit and token constraints.


87-89: Parameters correctly structured.

Pagination parameters properly included in the request.


102-102: Response URI properly constructed.

Correctly includes actual pagination parameters used in the request.

Editor/Services/ConsoleLogsService.cs (7)

25-26: Good memory management strategy.

The constants provide reasonable limits for log retention, and the cleanup threshold approach (removing 200 entries at once) efficiently reduces cleanup frequency.


77-81: Clean refactoring to use paginated method.

Good approach to maintain backward compatibility while leveraging the new paginated implementation.


83-97: Well-designed pagination API.

The method signature provides sensible defaults and returns comprehensive pagination metadata.


101-146: Robust pagination implementation.

The two-pass approach efficiently provides accurate counts while maintaining thread safety. The newest-first ordering aligns well with debugging workflows.


164-174: Useful manual cleanup method.

Provides flexibility for users to manage log retention with an efficient bulk removal approach.


180-186: Helpful monitoring method.

Simple and thread-safe way to check current log storage.


237-241: Effective automatic memory management.

The cleanup logic correctly maintains the log buffer size by removing the oldest entries when the limit is exceeded.

Comment on lines +67 to +68
const offset = variables["offset"] ? parseInt(variables["offset"], 10) : 0;
const limit = variables["limit"] ? parseInt(variables["limit"], 10) : 100;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for pagination parameters.

The code should validate that parsed values are valid non-negative integers to prevent potential issues with NaN or negative values.

Apply this validation after parsing:

 const offset = variables["offset"] ? parseInt(variables["offset"], 10) : 0;
 const limit = variables["limit"] ? parseInt(variables["limit"], 10) : 100;
+
+// Validate pagination parameters
+if (isNaN(offset) || offset < 0) {
+    throw new McpUnityError(ErrorType.INVALID_PARAMS, 'Invalid offset parameter: must be a non-negative integer');
+}
+if (isNaN(limit) || limit <= 0) {
+    throw new McpUnityError(ErrorType.INVALID_PARAMS, 'Invalid limit parameter: must be a positive integer');
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const offset = variables["offset"] ? parseInt(variables["offset"], 10) : 0;
const limit = variables["limit"] ? parseInt(variables["limit"], 10) : 100;
const offset = variables["offset"] ? parseInt(variables["offset"], 10) : 0;
const limit = variables["limit"] ? parseInt(variables["limit"], 10) : 100;
// Validate pagination parameters
if (isNaN(offset) || offset < 0) {
throw new McpUnityError(ErrorType.INVALID_PARAMS, 'Invalid offset parameter: must be a non-negative integer');
}
if (isNaN(limit) || limit <= 0) {
throw new McpUnityError(ErrorType.INVALID_PARAMS, 'Invalid limit parameter: must be a positive integer');
}
🤖 Prompt for AI Agents
In Server~/build/resources/getConsoleLogsResource.js around lines 67 to 68, the
pagination parameters offset and limit are parsed without validation, which can
lead to NaN or negative values. After parsing, add checks to ensure offset and
limit are non-negative integers; if not, set them to default values (0 for
offset, 100 for limit). This validation will prevent invalid pagination inputs
from causing errors.

…source

- Add bounds validation for offset (≥0) and limit (1-1000) parameters
- Simplify parameter extraction with helper method
- Add defensive programming for pagination metadata access
- Reduce code duplication and improve maintainability

Addresses CodeRabbit review feedback for better error handling and robustness.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
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

🧹 Nitpick comments (1)
Editor/Resources/GetConsoleLogsResource.cs (1)

38-47: Consider adding null-safety for pagination metadata access.

The response enhancement logic is comprehensive, but the pagination metadata access could be made more robust.

Consider adding explicit null checks for the pagination structure:

 var pagination = result["pagination"] as JObject;
 string typeFilter = logType != null ? $" of type '{logType}'" : "";
-int returnedCount = pagination?["returnedCount"]?.Value<int>() ?? 0;
-int filteredCount = pagination?["filteredCount"]?.Value<int>() ?? 0;
+int returnedCount = pagination?["returnedCount"]?.Value<int>() ?? 0;
+int filteredCount = pagination?["filteredCount"]?.Value<int>() ?? 0;
+
+// Additional safety check
+if (pagination == null)
+{
+    result["message"] = $"Retrieved logs{typeFilter} (offset: {offset}, limit: {limit}) - pagination data unavailable";
+    return result;
+}

This would handle cases where the service implementation might change or return unexpected pagination structure.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 925431d and 6f1ddc0.

📒 Files selected for processing (1)
  • Editor/Resources/GetConsoleLogsResource.cs (1 hunks)
🔇 Additional comments (5)
Editor/Resources/GetConsoleLogsResource.cs (5)

16-16: Well-crafted resource description with clear guidance.

The updated description effectively communicates the newest-first ordering, pagination support, and provides practical recommendations for optimal performance. The suggested limit range of 20-50 aligns well with the token limit objectives mentioned in the PR.


23-26: Documentation accurately reflects the new pagination capabilities.

The method documentation has been appropriately updated to describe the pagination support and parameter expectations.


29-33: Robust parameter extraction with appropriate bounds checking.

The parameter extraction logic is well-implemented:

  • logType handling correctly treats empty/whitespace strings as null
  • offset bounds ensure non-negative values with Math.Max(0, ...)
  • limit bounds ensure values between 1-1000 with nested Math.Max/Min calls
  • Default values (offset=0, limit=100) are sensible for the use case

36-36: Method call correctly updated to support pagination.

The change from GetAllLogsAsJson(logType) to GetLogsAsJson(logType, offset, limit) appropriately utilizes the new paginated service method.


50-62: Excellent helper method implementation with proper safety measures.

The GetIntParameter helper method demonstrates good practices:

  • Uses TryParse for safe integer conversion
  • Includes proper null checking with the null-conditional operator
  • Returns sensible defaults on parsing failures
  • private static modifier provides appropriate encapsulation

Resolved conflict by combining pagination functionality with the new log type mapping feature from upstream.
Copy link
Owner

@CoderGamester CoderGamester left a comment

Choose a reason for hiding this comment

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

Very good PR suggestion

I made some comments that require changes to properly work

string typeFilter = logType != null ? $" of type '{logType}'" : "";
int returnedCount = pagination?["returnedCount"]?.Value<int>() ?? 0;
int filteredCount = pagination?["filteredCount"]?.Value<int>() ?? 0;
result["message"] = $"Retrieved {returnedCount} of {filteredCount} log entries{typeFilter} (offset: {offset}, limit: {limit})";
Copy link
Owner

Choose a reason for hiding this comment

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

change the return to be the same JObject format as before
is a more readable and direct text for the AI agent to process

@@ -79,10 +83,26 @@ public void StopListening()
/// </summary>
/// <returns>JArray containing all logs</returns>
public JArray GetAllLogsAsJson(string logType = "")
Copy link
Owner

Choose a reason for hiding this comment

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

remove old method

@@ -101,21 +121,52 @@ public JArray GetAllLogsAsJson(string logType = "")

lock (_logEntries)
{
// First pass: count total and filtered entries
foreach (var entry in _logEntries)
Copy link
Owner

Choose a reason for hiding this comment

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

change to one single for loop for efficiency
if there is a limit and offset, that can be counted in the for loop variables

return new JObject
{
["logs"] = logsArray,
["pagination"] = new JObject
Copy link
Owner

Choose a reason for hiding this comment

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

pagination is unecessary
the message log above is already complete to be fullfiled with the total logs count

@@ -19,25 +19,25 @@ function listLogTypes(resourceMimeType: string) {
{
uri: `unity://logs/`,
Copy link
Owner

Choose a reason for hiding this comment

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

for the resource update the template with default offset and limit values
use max values that can be accepted

do this to all template commands

@CoderGamester
Copy link
Owner

@Saqoosha PR reviewed

- Remove pagination object and consolidate info into message field
- Delete deprecated GetAllLogsAsJson method
- Optimize log counting with single loop for better performance
- Add default offset/limit values to resource templates
- Simplify response to only include logs, message, and success fields
- Move count information (total, filtered, returned) into message text
- Add parameter validation for offset/limit in TypeScript

This addresses all review comments from PR CoderGamester#42 to make the response
format more concise and easier for AI agents to process.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@Saqoosha
Copy link
Contributor Author

Saqoosha commented Jun 2, 2025

Hi @CoderGamester,

Thanks for the review! I've addressed all your requested changes:

  1. Removed old method - Deleted GetAllLogsAsJson() method and updated the interface
  2. Optimized log counting loop - Consolidated into a single efficient for loop with early termination
  3. Removed pagination metadata - Simplified response format, moved count info to message field
  4. Added default values - Set appropriate defaults in resource templates for each log type (error: 20, warning: 30, info: 25, all: 50)

The latest commit (5e35e08) contains all these changes. The pagination feature has been tested and is working properly with all log types.

Ready for your review!

@Saqoosha Saqoosha requested a review from CoderGamester June 2, 2025 22:00
Copy link
Owner

@CoderGamester CoderGamester left a comment

Choose a reason for hiding this comment

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

LGTM

@CoderGamester
Copy link
Owner

@Saqoosha thank you very much for the PR

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