Skip to content

fixes#10

Merged
T-rav merged 2 commits intomainfrom
fixes
May 30, 2025
Merged

fixes#10
T-rav merged 2 commits intomainfrom
fixes

Conversation

@T-rav
Copy link
Collaborator

@T-rav T-rav commented May 30, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling and clearer error messages for missing or invalid API keys during search requests.
  • Refactor
    • Simplified and unified API key authentication for search endpoints, removing special keyword handling and fallback logic.
    • Enhanced logging for better traceability of search requests and error conditions.
    • Removed optional API key field from search query requests for consistency.
  • New Features
    • Added a new test script for validating the Serper API with detailed result output.
  • Tests
    • Updated test scripts to require and use the WebCAT API key consistently, with improved argument handling and output messages.

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The authentication and API key usage for the /search/{api_key}/sse endpoint were refactored to require an exact match with the configured WEBCAT_API_KEY. The search service now always uses the server's internal SERPER_API_KEY. Error handling and logging were improved, and test scripts were updated to use the new API key handling. Additionally, a new test script for the Serper API was added, and the QueryRequest model was simplified by removing the optional API key field.

Changes

File(s) Summary
docker/mcp/app.py Simplified /search/{api_key}/sse authentication to require exact WEBCAT_API_KEY match; removed special keyword handling; updated error handling and logging.
docker/mcp/services.py Enhanced fetch_search_results with detailed logging, robust error handling, and response validation.
docker/test_sse.py Changed test function to accept/use webcat_api_key instead of a boolean; updated CLI and error messages; improved key handling and output.
docker/run_sse_test.sh Modified test script to use WEBCAT_API_KEY with --api-key instead of --server-key; updated messages.
docker/mcp/models.py Removed optional api_key field from QueryRequest model.
docker/test_serper.py Added new test script for Serper API with request, response handling, and output formatting.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant App
    participant Services
    participant SerperAPI

    Client->>App: GET /search/{api_key}/sse
    App->>App: Validate api_key == WEBCAT_API_KEY
    alt Invalid or missing key
        App-->>Client: Yield error event and terminate
    else Valid key
        App->>Services: fetch_search_results(query, SERPER_API_KEY)
        Services->>SerperAPI: Request search results
        SerperAPI-->>Services: Return results or error
        Services-->>App: Return results or []
        App-->>Client: Stream results or error
    end
Loading

Poem

In the warren, keys are neat,
Now WebCAT’s match is hard to beat.
No more “webcat” tricks to try,
Just server keys that never lie.
With logs and errors clear and bright,
The search stream hops along just right!
🐇🔑


📜 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 13b93a4 and 324f7a9.

📒 Files selected for processing (3)
  • docker/mcp/models.py (0 hunks)
  • docker/mcp/services.py (1 hunks)
  • docker/test_serper.py (1 hunks)
✨ 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

@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: 3

🧹 Nitpick comments (5)
docker/mcp/services.py (1)

64-64: Remove trailing whitespace.

Multiple lines have trailing whitespace that should be removed.

Also applies to: 69-69, 73-73

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 64-64: Trailing whitespace

(C0303)

docker/test_sse.py (2)

41-41: Fix line length issues.

Both lines exceed the 100-character limit.

Apply this diff to fix the line length:

-        print("Error: No WebCAT API key provided. Please provide a key with --api-key or set WEBCAT_API_KEY environment variable")
+        print("Error: No WebCAT API key provided. Please provide a key with --api-key "
+              "or set WEBCAT_API_KEY environment variable")
-    print(f"Using WebCAT API key: {webcat_api_key[:4]}...{webcat_api_key[-4:] if len(webcat_api_key) > 8 else '****'}")
+    masked_key = f"{webcat_api_key[:4]}...{webcat_api_key[-4:]}" if len(webcat_api_key) > 8 else "****"
+    print(f"Using WebCAT API key: {masked_key}")

Also applies to: 56-56

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 41-41: Line too long (130/100)

(C0301)


35-35: Remove trailing whitespace and add final newline.

Multiple lines have trailing whitespace, and the file is missing a final newline.

Also applies to: 39-39, 43-43, 78-78, 81-82

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 35-35: Trailing whitespace

(C0303)

docker/mcp/app.py (2)

189-189: Fix line length and use lazy % formatting.

These lines exceed the 100-character limit and should use lazy % formatting.

Apply this diff:

-                logging.error(f"Invalid WebCAT API key provided: {api_key[:4]}...{api_key[-4:] if len(api_key) > 8 else '****'}")
+                masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
+                logging.error("Invalid WebCAT API key provided: %s", masked_key)
-            logging.info(f"MCP search stream with provided key: [{query}]")
+            logging.info("MCP search stream with provided key: [%s]", query)

Also applies to: 201-201

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 189-189: Line too long (129/100)

(C0301)


[warning] 189-189: Use lazy % formatting in logging functions

(W1203)


180-180: Remove trailing whitespace.

Multiple lines have trailing whitespace that should be removed.

Also applies to: 186-186, 192-192, 194-194, 200-200, 202-202

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 180-180: Trailing whitespace

(C0303)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34dec95 and 13b93a4.

📒 Files selected for processing (4)
  • docker/mcp/app.py (2 hunks)
  • docker/mcp/services.py (1 hunks)
  • docker/run_sse_test.sh (1 hunks)
  • docker/test_sse.py (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
docker/mcp/app.py (1)
docker/mcp/services.py (1)
  • fetch_search_results (49-77)
🪛 Pylint (3.3.7)
docker/mcp/services.py

[convention] 56-56: Trailing whitespace

(C0303)


[convention] 57-57: Line too long (124/100)

(C0301)


[convention] 58-58: Trailing whitespace

(C0303)


[convention] 64-64: Trailing whitespace

(C0303)


[convention] 69-69: Trailing whitespace

(C0303)


[convention] 73-73: Trailing whitespace

(C0303)


[warning] 57-57: Use lazy % formatting in logging functions

(W1203)


[warning] 66-66: Missing timeout argument for method 'requests.post' can cause your program to hang indefinitely

(W3101)


[warning] 71-71: Use lazy % formatting in logging functions

(W1203)


[warning] 76-76: Use lazy % formatting in logging functions

(W1203)

docker/test_sse.py

[convention] 35-35: Trailing whitespace

(C0303)


[convention] 39-39: Trailing whitespace

(C0303)


[convention] 41-41: Line too long (130/100)

(C0301)


[convention] 43-43: Trailing whitespace

(C0303)


[convention] 56-56: Line too long (119/100)

(C0301)


[convention] 78-78: Trailing whitespace

(C0303)


[convention] 81-81: Trailing whitespace

(C0303)


[convention] 82-82: Final newline missing

(C0304)

docker/mcp/app.py

[convention] 180-180: Trailing whitespace

(C0303)


[convention] 186-186: Trailing whitespace

(C0303)


[convention] 189-189: Line too long (129/100)

(C0301)


[convention] 192-192: Trailing whitespace

(C0303)


[convention] 194-194: Trailing whitespace

(C0303)


[convention] 198-198: Line too long (110/100)

(C0301)


[convention] 200-200: Trailing whitespace

(C0303)


[convention] 202-202: Trailing whitespace

(C0303)


[warning] 189-189: Use lazy % formatting in logging functions

(W1203)


[warning] 193-193: Use lazy % formatting in logging functions

(W1203)


[warning] 193-193: Using an f-string that does not have any interpolated variables

(W1309)


[warning] 201-201: Use lazy % formatting in logging functions

(W1203)

🪛 Ruff (0.11.9)
docker/mcp/app.py

193-193: f-string without any placeholders

Remove extraneous f prefix

(F541)

🔇 Additional comments (6)
docker/run_sse_test.sh (1)

164-166: LGTM! Correctly updated to use WebCAT API key.

The script now correctly passes the WebCAT API key using the --api-key flag, which aligns with the authentication changes in the server code.

docker/test_sse.py (2)

26-32: Well-implemented API key parameter change.

The function signature and documentation clearly indicate that this is the WebCAT API key used for authentication.


36-42: Good API key validation logic.

The function properly checks for the API key from the parameter first, then falls back to the environment variable, and exits gracefully if neither is provided.

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 39-39: Trailing whitespace

(C0303)


[convention] 41-41: Line too long (130/100)

(C0301)

docker/mcp/app.py (3)

168-169: Clear documentation update.

The parameter documentation correctly clarifies that this is the WebCAT API key for authentication.


181-192: Excellent authentication implementation.

The validation logic is clear and secure:

  1. Checks for missing API key
  2. Validates against the configured WEBCAT_API_KEY
  3. Returns appropriate error messages
  4. Masks the API key in logs for security
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 186-186: Trailing whitespace

(C0303)


[convention] 189-189: Line too long (129/100)

(C0301)


[convention] 192-192: Trailing whitespace

(C0303)


[warning] 189-189: Use lazy % formatting in logging functions

(W1203)


195-199: Good separation of authentication and API usage.

The code correctly separates authentication (WebCAT key) from the internal API usage (SERPER key), providing better security and flexibility.

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 198-198: Line too long (110/100)

(C0301)

Comment on lines 56 to 58

logging.debug(f"Sending request to Serper API with key: {api_key[:4]}...{api_key[-4:] if len(api_key) > 8 else '****'}")

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix formatting issues and use lazy % formatting.

The logging statement has trailing whitespace and exceeds the line length limit. Also, use lazy % formatting for better performance.

Apply this diff to fix the formatting:

-    
-    logging.debug(f"Sending request to Serper API with key: {api_key[:4]}...{api_key[-4:] if len(api_key) > 8 else '****'}")
-    
+    masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
+    logging.debug("Sending request to Serper API with key: %s", masked_key)
📝 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
logging.debug(f"Sending request to Serper API with key: {api_key[:4]}...{api_key[-4:] if len(api_key) > 8 else '****'}")
masked_key = f"{api_key[:4]}...{api_key[-4:]}" if len(api_key) > 8 else "****"
logging.debug("Sending request to Serper API with key: %s", masked_key)
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 56-56: Trailing whitespace

(C0303)


[convention] 57-57: Line too long (124/100)

(C0301)


[convention] 58-58: Trailing whitespace

(C0303)


[warning] 57-57: Use lazy % formatting in logging functions

(W1203)

🤖 Prompt for AI Agents
In docker/mcp/services.py around lines 56 to 58, the logging.debug statement has
trailing whitespace and exceeds the line length limit, and it uses f-string
formatting which is not lazy. Replace the f-string with lazy % formatting by
passing the format string and arguments separately to logging.debug, remove any
trailing whitespace, and ensure the line length stays within the limit.

Comment on lines 65 to 77
try:
response = requests.post(serper_url, headers=headers, json=payload)
response.raise_for_status() # Raise exception for 4XX/5XX status codes
search_results = response.json()

return search_results['organic'][:3]
if 'organic' not in search_results or not search_results['organic']:
logging.warning(f"No organic results found in Serper API response for query: {query}")
return []

return search_results['organic'][:3]
except requests.exceptions.RequestException as e:
logging.error(f"Error calling Serper API: {str(e)}")
return []
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Excellent error handling implementation, but add a timeout.

The error handling with try-except block and response validation is well-implemented. However, the requests.post call is missing a timeout parameter, which could cause the program to hang indefinitely.

Add a timeout to prevent hanging:

-        response = requests.post(serper_url, headers=headers, json=payload)
+        response = requests.post(serper_url, headers=headers, json=payload, timeout=30)
📝 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
try:
response = requests.post(serper_url, headers=headers, json=payload)
response.raise_for_status() # Raise exception for 4XX/5XX status codes
search_results = response.json()
return search_results['organic'][:3]
if 'organic' not in search_results or not search_results['organic']:
logging.warning(f"No organic results found in Serper API response for query: {query}")
return []
return search_results['organic'][:3]
except requests.exceptions.RequestException as e:
logging.error(f"Error calling Serper API: {str(e)}")
return []
try:
response = requests.post(serper_url, headers=headers, json=payload, timeout=30)
response.raise_for_status() # Raise exception for 4XX/5XX status codes
search_results = response.json()
if 'organic' not in search_results or not search_results['organic']:
logging.warning(f"No organic results found in Serper API response for query: {query}")
return []
return search_results['organic'][:3]
except requests.exceptions.RequestException as e:
logging.error(f"Error calling Serper API: {str(e)}")
return []
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 69-69: Trailing whitespace

(C0303)


[convention] 73-73: Trailing whitespace

(C0303)


[warning] 66-66: Missing timeout argument for method 'requests.post' can cause your program to hang indefinitely

(W3101)


[warning] 71-71: Use lazy % formatting in logging functions

(W1203)


[warning] 76-76: Use lazy % formatting in logging functions

(W1203)

🤖 Prompt for AI Agents
In docker/mcp/services.py around lines 65 to 77, the requests.post call lacks a
timeout parameter, which can cause the program to hang indefinitely if the
server does not respond. Add a timeout argument to the requests.post call,
specifying a reasonable timeout duration (e.g., timeout=10) to ensure the
request fails gracefully if it takes too long.

yield {"event": "error", "data": "Authentication failed: Invalid API key."}
return

logging.debug(f"Using provided API key from URL path")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary f-string prefix.

The logging statement doesn't contain any placeholders.

Apply this diff:

-            logging.debug(f"Using provided API key from URL path")
+            logging.debug("Using provided API key from URL path")
📝 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
logging.debug(f"Using provided API key from URL path")
logging.debug("Using provided API key from URL path")
🧰 Tools
🪛 Ruff (0.11.9)

193-193: f-string without any placeholders

Remove extraneous f prefix

(F541)

🪛 Pylint (3.3.7)

[warning] 193-193: Use lazy % formatting in logging functions

(W1203)


[warning] 193-193: Using an f-string that does not have any interpolated variables

(W1309)

🤖 Prompt for AI Agents
In docker/mcp/app.py at line 193, the logging.debug statement uses an f-string
without any placeholders, which is unnecessary. Remove the f-string prefix by
changing the statement to a regular string literal without the leading 'f'.

@T-rav T-rav merged commit 64336cf into main May 30, 2025
3 checks passed
@T-rav T-rav deleted the fixes branch May 30, 2025 23:38
@coderabbitai coderabbitai bot mentioned this pull request May 31, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jun 13, 2025
T-rav added a commit that referenced this pull request Oct 10, 2025
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.

1 participant