Skip to content

Conversation

@cfdude
Copy link
Contributor

@cfdude cfdude commented Aug 10, 2025

Summary

This PR enhances the MCP server with comprehensive error handling for Google Drive image insertion and completes architectural consistency by migrating all API request construction to helper functions.

Key Changes

🔧 Error Handling for Drive Image Insertion

  • New Permission Checking Tools: Added comprehensive Drive file permission detection in
  • Enhanced User Experience: now checks permissions first and provides detailed, actionable error messages
  • Self-Contained Function: The function automatically handles permission validation without requiring separate tool calls

🏗️ Helper Function Architecture Migration

  • Consistent API Construction: Migrated all inline dictionary approaches to centralized helper functions
  • Improved Maintainability: API request logic is now centralized and reusable across functions
  • Enhanced Code Quality: Reduced duplication and improved consistency in API interactions

🔬 Technical Improvements

  • Google Docs API Compatibility: Fixed font handling with proper structure
  • MCP Integration: Maintained full compatibility with MCP protocol requirements
  • Comprehensive Testing: All functions validated with real Google Drive and Docs operations

Benefits of Helper Function Approach

The helper functions provide several key advantages:

  1. Centralized Logic: API request construction is consolidated, making changes easier to implement and maintain
  2. Consistency: All functions use the same patterns for similar operations, reducing cognitive overhead
  3. Testability: Helper functions can be unit tested independently, improving reliability
  4. Documentation: Each helper function serves as clear documentation of API requirements
  5. Extensibility: New features can leverage existing helpers, accelerating development

Files Modified

  • (NEW): Permission checking tools with detailed error messaging
  • : Enhanced with permission validation and migrated to helper functions
  • : Added new helpers and fixed font API compatibility
  • : Added development files to ignore list

Testing Completed

  • ✅ Permission error handling with restricted Drive files
  • ✅ Successful image insertion with shared Drive files
  • ✅ Document creation with helper functions
  • ✅ Header/footer updates with segmented insertion helpers
  • ✅ Font formatting with corrected API structure
  • ✅ All existing functionality verified working

This change maintains backward compatibility while significantly improving the codebase architecture and user experience.

@taylorwilsdon
Copy link
Owner

Love it, I know #109 was looking at something similar and have wanted to get more granular with editing. Will give it a run through tomorrow!

@taylorwilsdon taylorwilsdon requested review from Copilot and taylorwilsdon and removed request for Copilot August 10, 2025 02:15
@taylorwilsdon taylorwilsdon self-assigned this Aug 10, 2025
@taylorwilsdon taylorwilsdon added the enhancement New feature or request label Aug 10, 2025
@taylorwilsdon taylorwilsdon requested a review from Copilot August 10, 2025 09:17

This comment was marked as outdated.

@taylorwilsdon
Copy link
Owner

Will push up to branch with the personal files added to gitignore, in general looks like a good contribution thank you @cfdude! Few notes:

  • I think the import for docs_helpers got missed in docs_tools?
  • appears both calculate_text_indices & extract_document_text_simple doesn't actually seem to get called anywhere. Was there a goal to use these in future operations or just an experiment that we can clean up?

I'll take a run at fixes and test.

@taylorwilsdon
Copy link
Owner

I like the idea but this isn't working well at all - you've inspired me with the idea, will see what we can get cooking

editing_demo.mp4

@cfdude
Copy link
Contributor Author

cfdude commented Aug 10, 2025

Hey Taylor, sorry about that, was a late night last night. I'm fixing all the bugs and testing.. should have an updated commit in a few minutes.

@taylorwilsdon
Copy link
Owner

Hey Taylor, sorry about that, was a late night last night. I'm fixing all the bugs and testing.. should have an updated commit in a few minutes.

I've gotten a little further along but still finding some issues with tables specifically - that's a tough spec for the LLM to wrap its head around when making the request, it seems. Would love to see your update and will share my progress shortly as well!

@cfdude
Copy link
Contributor Author

cfdude commented Aug 10, 2025

@taylorwilsdon these commits fix the prior problems and also improve with helper functions. The insert image by URL or drive is working well now too.

@cfdude
Copy link
Contributor Author

cfdude commented Aug 10, 2025

all thoroughly tested this time as well.

@taylorwilsdon
Copy link
Owner

Awesome, will give it a try! I've got my own version working really well with sophisticated table operations -
image

@taylorwilsdon
Copy link
Owner

taylorwilsdon commented Aug 10, 2025

What I'm going to do since my branch is based off your original but so divergent now is split it off to cover the table logic stuff which is still not possible with your branch, I found myself on a little side quest while testing - then I'll pull this up to main and we can get the rest of the features pulled in. All your commits are still in so it'll be a coauthor on the new PR. Thanks for the contributions!

I love the idea of this being the most capable/sophisticated control of this type of stuff down to the tiniest nuance, but I also do wonder if we eventually need to make certain "classes" of tools (ie degree of sophistication) optional because small models may start to struggle with this much tool usage context.

@taylorwilsdon
Copy link
Owner

taylorwilsdon commented Aug 11, 2025

Merged in main and fixed stuff, kept all your adds. Will take a second pass at quality review, still needs some attention but we will get this in. As we get more granular we need to figure out a way to gate certain features on startup because this is getting to be too large a prompt for small models.

@taylorwilsdon
Copy link
Owner

Can you define tool tiers for these and pull in main/resolve conflicts? Love to get it released in the next

@cfdude
Copy link
Contributor Author

cfdude commented Aug 17, 2025

@taylorwilsdon I fixed the merge conflicts and added the tool tiers

@taylorwilsdon taylorwilsdon requested a review from Copilot August 19, 2025 18:16
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR enhances the MCP server by adding comprehensive error handling for Google Drive image insertion and migrating all API request construction to centralized helper functions, improving maintainability and user experience.

  • Added new Google Drive permission checking tools with detailed error messaging
  • Enhanced image insertion with permission validation and better error handling
  • Migrated inline API request construction to reusable helper functions

Reviewed Changes

Copilot reviewed 10 out of 12 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
pyproject.toml Added package data configuration for core module
main.py Added import for new drive file permissions module
gdrive/drive_helpers.py New helper functions for Drive permissions and URL handling
gdrive/drive_file_permissions.py New tools for checking Drive file permissions and sharing status
gdocs/docs_tools.py Enhanced image insertion tools with Drive integration and permission validation
gdocs/docs_helpers.py Added helper function for segmented text insertion
core/utils.py Improved error handling to avoid suggesting re-auth for non-auth errors
core/tool_tiers.yaml Added new image insertion tools to complete tier
auth/service_decorator.py Fixed signature handling for multi-service decorator
CLAUDE.md Added comprehensive documentation for the codebase

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

logger.info(f"[check_drive_file_public_access] Searching for {file_name}")

# Search for the file
escaped_name = file_name.replace("'", "\\'")
Copy link

Copilot AI Aug 19, 2025

Choose a reason for hiding this comment

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

The query construction is vulnerable to injection if the file name contains SQL-like metacharacters. While the name is escaped for single quotes, other Drive query metacharacters like parentheses or operators could cause issues. Consider using a more robust escaping approach or parameterized queries if available.

Suggested change
escaped_name = file_name.replace("'", "\\'")
def escape_drive_query_value(value: str) -> str:
# Escape backslashes first, then single quotes, as per Drive API docs
return value.replace("\\", "\\\\").replace("'", "\\'")
escaped_name = escape_drive_query_value(file_name)

Copilot uses AI. Check for mistakes.
logger.info(f"[insert_doc_image_from_drive] Doc={document_id}, file={drive_file_name}, index={index}")

# Build search query for the specific file name
escaped_name = drive_file_name.replace("'", "\\'")
Copy link

Copilot AI Aug 19, 2025

Choose a reason for hiding this comment

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

Similar to the other occurrence, this query construction could be vulnerable to Drive query injection if the file name contains metacharacters beyond single quotes. Consider implementing more comprehensive escaping.

Suggested change
escaped_name = drive_file_name.replace("'", "\\'")
# Escape single quotes for Drive API query by doubling them
escaped_name = drive_file_name.replace("'", "''")

Copilot uses AI. Check for mistakes.
return f"❌ API Error: Drive image '{file_name}' access denied despite public sharing. May need propagation time or use insert_doc_image_url with: {get_drive_image_url(file_id)}"
else:
# Some other error occurred
return f"❌ Error inserting image '{file_name}': {e}"
Copy link

Copilot AI Aug 19, 2025

Choose a reason for hiding this comment

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

String-based error detection is fragile and may not catch all permission-related errors reliably. Consider checking for specific HTTP status codes (403, 401) or using more structured error detection based on error types rather than string matching.

Suggested change
return f"❌ Error inserting image '{file_name}': {e}"
except HttpError as e:
if e.resp.status in (401, 403):
return f"❌ API Error: Drive image '{file_name}' access denied despite public sharing. May need propagation time or use insert_doc_image_url with: {get_drive_image_url(file_id)}"
else:
# Some other HTTP error occurred
return f"❌ Error inserting image '{file_name}': {e}"
except Exception as e:
# Some other non-HTTP error occurred
return f"❌ Error inserting image '{file_name}': {e}"

Copilot uses AI. Check for mistakes.
except Exception as e:
error_str = str(e)
if "publicly accessible" in error_str or "forbidden" in error_str.lower():
return f"❌ API Error: Drive image '{file_name}' access denied despite public sharing. May need propagation time or use insert_doc_image_url with: {get_drive_image_url(file_id)}"
Copy link

Copilot AI Aug 19, 2025

Choose a reason for hiding this comment

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

[nitpick] This error message contains a magic assumption about 'propagation time' that may confuse users. Consider making this more specific or removing the speculation about timing.

Suggested change
return f"❌ API Error: Drive image '{file_name}' access denied despite public sharing. May need propagation time or use insert_doc_image_url with: {get_drive_image_url(file_id)}"
return f"❌ API Error: Drive image '{file_name}' access denied despite public sharing. Try using insert_doc_image_url with: {get_drive_image_url(file_id)}"

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants