How grep-mcp Validates Input Parameters for the grep_query Tool
The grep_query tool in galprz/grep-mcp validates all arguments through explicit type and format checks in src/grep_mcp/server.py, returning user-friendly error strings instead of raising exceptions when constraints like maximum length or required formatting are violated.
The grep_query tool serves as the primary search interface for the galprz/grep-mcp project, enabling direct queries to the grep.app API through the Model Context Protocol (MCP). Before executing any network requests, the tool implements rigorous input validation to ensure data integrity and provide clear feedback to end users. Understanding how grep-mcp validates input parameters helps developers debug integration issues and ensures reliable search operations across code repositories.
Validation Logic in src/grep_mcp/server.py
Inside src/grep_mcp/server.py, the grep_query function implements a defensive validation block immediately after its docstring. This approach ensures that malformed inputs never reach the external API, with each parameter undergoing specific constraint checks before assembly into the request payload.
Query Parameter Validation (Required)
The query parameter is the only required argument and faces the strictest validation rules. The function first verifies that query exists and is a string instance, then checks that it contains non-whitespace content, and finally enforces a maximum length of 1000 characters.
if not query or not isinstance(query, str):
return "❌ Error: 'query' parameter is required and must be a non‑empty string"
if len(query.strip()) == 0:
return "❌ Error: 'query' cannot be empty or only whitespace"
if len(query) > 1000:
return "❌ Error: 'query' is too long (max 1000 characters). Please use a shorter query."
Language Parameter Validation (Optional)
When provided, the language filter must be a non-empty string no longer than 50 characters. The validation ensures that empty strings or whitespace-only values are rejected while allowing valid language identifiers like "python" or "javascript".
if language is not None:
if not isinstance(language, str) or len(language.strip()) == 0:
return "❌ Error: 'language' parameter must be a non‑empty string when provided"
if len(language) > 50:
return "❌ Error: 'language' parameter is too long (max 50 characters)"
Repository Parameter Validation (Optional)
The repo parameter requires precise formatting to match the owner/repository structure used by GitHub and similar platforms. Validation confirms the presence of exactly one forward slash and caps the total length at 100 characters.
if repo is not None:
if not isinstance(repo, str) or len(repo.strip()) == 0:
return "❌ Error: 'repo' parameter must be a non‑empty string when provided"
if "/" not in repo or repo.count("/") != 1:
return "❌ Error: 'repo' parameter must be in format 'owner/repository' (e.g., 'fastapi/fastapi')"
if len(repo) > 100:
return "❌ Error: 'repo' parameter is too long (max 100 characters)"
Path Parameter Validation (Optional)
For the path parameter, the validation ensures that directory or file path filters are non-empty strings with a maximum length of 200 characters, preventing excessively deep or malformed path specifications.
if path is not None:
if not isinstance(path, str) or len(path.strip()) == 0:
return "❌ Error: 'path' parameter must be a non‑empty string when provided"
if len(path) > 200:
return "❌ Error: 'path' parameter is too long (max 200 characters)"
Error Handling Strategy
Rather than raising exceptions that might interrupt the MCP runtime, grep_query returns descriptive error strings prefixed with "❌ Error". This design choice allows the Model Context Protocol to surface validation failures directly to end users without crashing the server process. Each validation check operates independently, with the function returning immediately upon encountering the first constraint violation, ensuring predictable error messaging.
Practical Usage Examples
The following examples demonstrate both successful parameter passing and common validation failures.
Valid search with all optional parameters:
result = await grep_query(
query="async def read(*",
language="python",
repo="galprz/grep-mcp",
path="src/"
)
print(result) # Returns JSON string with formatted search results
Invalid repository format triggers specific validation:
result = await grep_query(
query="socket",
repo="invalid-repo-format"
)
print(result)
# Output:
# ❌ Error: 'repo' parameter must be in format 'owner/repository' (e.g., 'fastapi/fastapi')
Missing required query parameter:
result = await grep_query(query="")
print(result)
# Output:
# ❌ Error: 'query' parameter is required and must be a non‑empty string
Summary
- Explicit type checking ensures all parameters are strings before processing begins in
src/grep_mcp/server.py. - Length constraints protect against buffer overflow issues: 1000 characters for queries, 100 for repositories, 200 for paths, and 50 for languages.
- Format validation on the
repoparameter enforces theowner/repositorystructure with exactly one forward slash. - Graceful error handling returns user-friendly strings rather than raising exceptions, maintaining MCP server stability.
- Whitespace trimming prevents empty or invisible character submissions across all string parameters.
Frequently Asked Questions
What happens if I exceed the maximum character limits in grep_query?
If any parameter exceeds its defined length constraint—such as a query longer than 1000 characters or a repository string over 100 characters—the function immediately returns a specific error message indicating the maximum allowed length and terminates before making any API request.
Why does grep-mcp return error strings instead of raising Python exceptions?
The tool returns formatted error strings to comply with the Model Context Protocol specification, allowing client applications to receive and display validation feedback without handling server-side crashes or stack traces that would disrupt the conversational AI workflow.
How does the repository format validation work?
The validation logic checks that the repo string contains exactly one forward slash character, ensuring it follows the standard owner/repository format used by GitHub and similar platforms, while rejecting strings with zero or multiple slashes.
Are there any restrictions on the language parameter values?
While the code validates that language is a non-empty string under 50 characters, it does not maintain a whitelist of valid programming languages; any string meeting the length and content requirements is accepted and passed directly to the grep.app API.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →