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
5 changes: 5 additions & 0 deletions .sampo/changesets/gemini-tool-credentials.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: patch
---

`$ai_tools` masks the credentials in Gemini tool definitions with `[REDACTED]`, with or without privacy mode: every `api_key`, `api_auth`, `auth_config`, and `headers` inside a tool's config, such as `retrieval.external_api`, `google_maps`, `exa_ai_search`, `parallel_ai_search`, and `mcp_servers`. Function declarations are not masked. The tools you pass in are not modified.
86 changes: 83 additions & 3 deletions posthog/ai/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import asyncio
import copy
import functools
import logging
import re
import sys
import time
import uuid
from typing import Any, Callable, Dict, List, Optional, Tuple, cast
Expand Down Expand Up @@ -1108,8 +1110,77 @@ def _is_mcp_provider_tool(tool: Dict[str, Any]) -> bool:
)


# Credential keys in google-genai `Tool` configs, such as retrieval and Maps
# auth, search provider API keys, and MCP server headers. Function declarations
# hold the caller's own parameter schemas and are never masked.
_GEMINI_CREDENTIAL_KEYS = frozenset(
{"api_auth", "apiAuth", "auth_config", "authConfig", "api_key", "apiKey", "headers"}
)
_GEMINI_SCHEMA_FIELDS = frozenset({"function_declarations", "functionDeclarations"})


def _gemini_tool_class() -> Optional[type]:
# Gemini tools only exist once the caller has loaded google-genai, so look it
# up instead of importing it on every provider's capture path.
return getattr(sys.modules.get("google.genai.types"), "Tool", None)


@functools.lru_cache(maxsize=4)
def _model_field_names(model_class: type) -> frozenset:
fields = model_class.model_fields # type: ignore[attr-defined]
return frozenset({*fields, *(f.alias for f in fields.values() if f.alias)})


def _gemini_tool_fields() -> frozenset:
# Read from the SDK so tools Google adds later are covered too.
tool_class = _gemini_tool_class()
return _model_field_names(tool_class) if tool_class else frozenset()


def _without_gemini_credentials(value: Any) -> Any:
model_dump = getattr(value, "model_dump", None)
if callable(model_dump):
dumped = model_dump()
if isinstance(dumped, dict):
return _without_gemini_credentials(dumped)
if isinstance(value, dict):
return {
key: (
_REDACTED_MCP_CREDENTIAL
if key in _GEMINI_CREDENTIAL_KEYS and item is not None
else _without_gemini_credentials(item)
)
for key, item in value.items()
}
if isinstance(value, (list, tuple)):
return [_without_gemini_credentials(item) for item in value]
return value
Comment thread
bernatixer marked this conversation as resolved.
Resolved


def _is_gemini_tool_with_config(tool: Any) -> bool:
tool_class = _gemini_tool_class()
return (
tool_class is not None
and isinstance(tool, tool_class)
and any(
getattr(tool, name, None) is not None
for name in tool_class.model_fields # type: ignore[attr-defined]
if name not in _GEMINI_SCHEMA_FIELDS
)
)


def _is_gemini_tool_dict(tool: Dict[str, Any]) -> bool:
return any(
key in _gemini_tool_fields() and key not in _GEMINI_SCHEMA_FIELDS
for key in tool
)


def _redact_mcp_tool(tool: Any) -> Any:
if not isinstance(tool, dict):
if _is_gemini_tool_with_config(tool):
return _redact_mcp_tool(tool.model_dump())
if getattr(tool, "type", None) != "mcp":
return tool
model_dump = getattr(tool, "model_dump", None)
Expand All @@ -1127,14 +1198,23 @@ def _redact_mcp_tool(tool: Any) -> Any:
return _without_mcp_credentials(tool)
if _is_mcp_provider_tool(tool):
return {**tool, "args": _without_mcp_credentials(tool["args"])}
if _is_gemini_tool_dict(tool):
return {
key: (
value
if key in _GEMINI_SCHEMA_FIELDS
else _without_gemini_credentials(value)
)
for key, value in tool.items()
}
return tool


def _redact_mcp_tool_credentials(tools: Any) -> Any:
"""
Mask the `headers` and `authorization` of MCP tool definitions, which carry
credentials for the remote server. Returns copies; the caller's tools are
left untouched.
Mask the credentials in tool definitions: the `headers` and `authorization`
of MCP tools, and the API keys, auth configs, and headers in Gemini tool
configs. Returns copies; the caller's tools are left untouched.
"""
if not isinstance(tools, (list, tuple)):
return tools
Expand Down
134 changes: 134 additions & 0 deletions posthog/test/ai/test_privacy_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,140 @@ def test_mcp_tool_credentials_are_masked_without_mutating_caller_tools(
assert mcp_object.headers == {"X-Api-Key": CANARY}


@pytest.mark.parametrize(
"tool",
[
pytest.param(
{
"retrieval": {
"external_api": {
"api_spec": "ELASTIC_SEARCH",
"endpoint": "https://es.example.com",
"api_auth": {"api_key_config": {"api_key_string": CANARY}},
}
}
},
id="retrieval-api-auth",
),
pytest.param(
{
"retrieval": {
"external_api": {
"endpoint": "https://es.example.com",
"auth_config": {"oauth_config": {"access_token": CANARY}},
}
}
},
id="retrieval-auth-config",
),
pytest.param(
{"google_maps": {"auth_config": {"api_key": CANARY}}},
id="google-maps-auth-config",
),
pytest.param(
{"googleMaps": {"authConfig": {"oauthConfig": {"accessToken": CANARY}}}},
id="camel-case-google-maps",
),
pytest.param(
{"exa_ai_search": {"api_key": CANARY}},
id="exa-ai-search-api-key",
),
pytest.param(
{"parallel_ai_search": {"api_key": CANARY}},
id="parallel-ai-search-api-key",
),
pytest.param(
{
"mcp_servers": [
{
"name": "docs",
"streamable_http_transport": {
"url": "https://mcp.example.com",
"headers": {"Authorization": f"Bearer {CANARY}"},
},
}
]
},
id="mcp-servers-headers",
),
],
)
@pytest.mark.parametrize("as_model", [True, False], ids=["model", "dict"])
def test_gemini_tool_credentials_are_masked(
tool: Dict[str, Any], as_model: bool
) -> None:
from google.genai import types

function_tool = types.Tool(
function_declarations=[
types.FunctionDeclaration(
name="call_api",
parameters_json_schema={
"type": "object",
"properties": {"api_key": {"type": "string"}},
},
)
]
)
credential_tool = types.Tool.model_validate(tool) if as_model else tool
tools = [credential_tool, function_tool]

captured = extract_available_tool_calls(
"gemini", {"config": SimpleNamespace(tools=tools)}
)

assert CANARY not in json.dumps(captured, default=str)
assert _REDACTED_MCP_CREDENTIAL in json.dumps(captured, default=str)
assert captured[0].keys() & {"google_maps", "googleMaps", *tool}
assert captured[1] is function_tool
assert CANARY in json.dumps(tool)


@pytest.mark.parametrize(
"make_tool",
[
pytest.param(
lambda types: {"exa_ai_search": {"api_key": CANARY}, "label": "search"},
id="extra-key",
),
pytest.param(
lambda types: {
"google_maps": types.GoogleMaps(
auth_config=types.AuthConfig(api_key=CANARY)
)
},
id="nested-model",
),
pytest.param(
lambda types: {
"mcp_servers": (
{
"streamable_http_transport": {
"headers": {"Authorization": CANARY}
}
},
)
},
id="tuple",
),
pytest.param(
lambda types: type("AppTool", (types.Tool,), {})(
exa_ai_search=types.ToolExaAiSearch(api_key=CANARY)
),
id="tool-subclass",
),
],
)
def test_gemini_tool_variants_are_masked(make_tool: Callable[[Any], Any]) -> None:
from google.genai import types

captured = extract_available_tool_calls(
"gemini", {"config": SimpleNamespace(tools=[make_tool(types)])}
)

assert CANARY not in json.dumps(captured, default=str)


@pytest.fixture
def private_client() -> Iterator[Client]:
client = Client(
Expand Down
Loading