Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/mcp_components/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,10 @@ def fetch_search_data(params: dict[str, Any] | None) -> dict[str, Any]:
if not api_key:
raise RuntimeError("Error: Unable to access API key from request context")

# api_key set last so caller params can never override the trusted key.
search_params = {
"api_key": api_key,
"engine": "google_light",
**(params or {}),
"api_key": api_key,
}
return serpapi.search(search_params).as_dict()
3 changes: 1 addition & 2 deletions src/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,5 +137,4 @@ async def healthcheck_handler(request):
host = os.getenv("MCP_HOST", "0.0.0.0")
port = int(os.getenv("MCP_PORT", "8000"))

workers = int(os.getenv("WEB_CONCURRENCY", "4"))
Comment thread
vm-serpapi marked this conversation as resolved.
uvicorn.run(starlette_app, host=host, port=port, ws="none", workers=workers)
uvicorn.run(starlette_app, host=host, port=port, ws="none")
29 changes: 29 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,35 @@ def capture(params):
assert captured["engine"] == "google_news"


async def test_search_ignores_caller_supplied_api_key(monkeypatch):
# Caller-supplied api_key must never override the authenticated key.
captured = {}

def capture(params):
captured.update(params)
return serp_results({})

use_request(monkeypatch, real_request(state={"api_key": "TRUSTED"}))
use_search(monkeypatch, capture)
await mcp_tools.search(params={"q": "x", "api_key": "CALLER_CONTROLLED"})
assert captured["api_key"] == "TRUSTED"
assert captured["q"] == "x"


async def test_search_apps_ignore_caller_supplied_api_key(monkeypatch):
# App variants share fetch_search_data, so the same guard must hold.
captured = {}

def capture(params):
captured.update(params)
return serp_results(_SAMPLE_PAYLOAD)

use_request(monkeypatch, real_request(state={"api_key": "TRUSTED"}))
use_search(monkeypatch, capture)
await mcp_apps.search_table(params={"q": "x", "api_key": "CALLER_CONTROLLED"})
assert captured["api_key"] == "TRUSTED"


@pytest.mark.parametrize(
"status, fragment",
[
Expand Down
Loading