A FastAPI-based MCP (Model Context Protocol) server that provides a keyword search tool for searching within files.
- Keyword Search: Search for keywords in text files with line numbers and occurrence counts
- Case Sensitivity: Toggle between case-sensitive and case-insensitive searches
- RESTful API: Simple HTTP endpoints for easy integration
- Error Handling: Handles missing files, non-text files, and invalid paths
- Interactive Docs: Built-in Swagger UI for testing
# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtStart the server:
python server.pyServer runs at http://127.0.0.1:8000
Test the server (in another terminal):
python test_client.pySearch for a keyword in a file and get all matching lines.
Request Body:
{
"file_path": "example.txt",
"keyword": "python",
"case_sensitive": false
}Response:
{
"file_path": "example.txt",
"keyword": "python",
"total_matches": 5,
"matches": [
{
"line_number": 2,
"content": "Python is a popular programming language.",
"occurrences": 1
}
]
}Parameters:
file_path(string, required): Path to the file to searchkeyword(string, required): Keyword to search forcase_sensitive(boolean, optional): Enable case-sensitive search (default: false)
Response Fields:
file_path: The searched file pathkeyword: The keyword that was searchedtotal_matches: Number of lines containing the keywordmatches: Array of matching lines with line numbers, content, and occurrence count
Health check endpoint to verify server status.
Response:
{
"status": "healthy"
}Root endpoint with server information.
curl -X POST http://127.0.0.1:8000/search \
-H "Content-Type: application/json" \
-d '{"file_path": "example.txt", "keyword": "python", "case_sensitive": false}'import requests
response = requests.post(
"http://127.0.0.1:8000/search",
json={
"file_path": "example.txt",
"keyword": "python",
"case_sensitive": False
}
)
result = response.json()
print(f"Found {result['total_matches']} matches")The test_client.py script demonstrates various search scenarios:
- Case-insensitive searches
- Case-sensitive searches
- Different keywords
- Error handling for missing files
Run it while the server is running to see example outputs.
- 404: File not found at the specified path
- 400: Invalid file path or file is not readable as text
- 500: Internal server error while processing the file
Interactive API documentation is available at:
- Swagger UI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
mcp-keyword-search/
├── server.py # Main FastAPI server
├── test_client.py # Test script with examples
├── example.txt # Sample file for testing
├── requirements.txt # Python dependencies
└── README.md # This file