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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and

## [Unreleased]

### Security

- The SDK now masks sensitive values in every event before the event leaves your server. It tests
each key in `parameters`, `response` and `error`, at any depth. When the key names a secret, the
SDK keeps the key and replaces the value with `[redacted]`. A key names a secret when it is a
known credential header (`authorization`, `cookie`, `x-api-key` and others) or has a word such
as `token`, `secret`, `password`, `signature` or `api-key`, in any spelling (`X-Api-Key`,
`HTTP_X_API_KEY`, `xApiKey`). Before, the SDK sent the HTTP headers of each MCP request as
received, in `parameters.extra.requestInfo.headers`. Tool arguments and results under such key
names lose their values too, for example `pageToken` and `auth_type`. `null`, `true` and
`false` stay. No option turns the mask off (#62).

## [2.2.0] - 2026-11-17

### Added
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ agentcat.track(server, "proj_0000000", AgentCatOptions(identify=identify))

AgentCat redacts all data sent to its servers and encrypts at rest, but for additional security, it offers a hook to do your own redaction on all text data returned back to our servers.

Before an event leaves your server, the SDK replaces the value of each key that names a secret (such as the `authorization`, `cookie` and `x-api-key` request headers, or any key with `token`, `secret` or `password` in its name) with `[redacted]`. Your hooks run first and still see the raw values.

```python
from agentcat import AgentCatOptions

Expand Down
27 changes: 27 additions & 0 deletions src/agentcat/modules/event_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from datetime import datetime, timezone
from typing import Any, Optional, TYPE_CHECKING

import pydantic_core

if TYPE_CHECKING:
from .telemetry import TelemetryManager

Expand All @@ -36,6 +38,7 @@
from .logging import write_to_log
from .redaction import apply_event_redaction, redact_event
from .sanitization import sanitize_event
from .sensitive_keys import mask_sensitive_keys
from .truncation import truncate_event

# Stamped on every event. Same value 1.x reported, resolved once at import
Expand Down Expand Up @@ -68,6 +71,29 @@ def __init__(self, run: Callable[[], None]) -> None:
self.run = run


def _mask_event(event: UnredactedEvent) -> None:
"""Mask the values of sensitive keys in the payload fields of `event`.

Each field is first turned into plain data, as truncation does, so the
mask sees what is sent. The mask builds new values and never changes the
objects it reads. A field that fails is dropped, so the event goes out
without it.
"""
for field in ("parameters", "response", "error"):
value = getattr(event, field)
if value is None:
continue
try:
plain = pydantic_core.to_jsonable_python(value, fallback=str)
setattr(event, field, mask_sensitive_keys(plain))
except Exception as error:
setattr(event, field, None)
write_to_log(
f"WARNING: Masking failed for {field} of event "
f"{event.id or 'unknown'}, sending it without {field}: {error}"
)


def _ensure_event_id(event: UnredactedEvent) -> None:
"""Assign a ksuid if the event doesn't already have one."""
if not event.id:
Expand Down Expand Up @@ -280,6 +306,7 @@ def _process_event(self, event: UnredactedEvent) -> None:
write_to_log(
f"WARNING: Sanitization failed for event {event.id or 'unknown'}, sending unsanitized: {error}"
)
_mask_event(event)
try:
event = truncate_event(event)
except Exception as error:
Expand Down
3 changes: 3 additions & 0 deletions src/agentcat/modules/request_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
HTTP / SSE / Streamable HTTP transports populate `requestInfo.headers` from the
Starlette `Request`. stdio transports omit `requestInfo` entirely (parity with
the TS SDK, which only sets `requestInfo` on HTTP-based transports).

The headers are captured as received; the event queue masks the values of
secret headers such as `authorization` and `cookie` before the event is sent.
"""

from __future__ import annotations
Expand Down
131 changes: 131 additions & 0 deletions src/agentcat/modules/sensitive_keys.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Masks the values of keys that name a secret, such as `authorization` or `x-api-key`.

A port of the shared AgentCat reference implementation. Every SDK passes the same cases
in `tests/sensitive_keys_vectors.json`.
"""

from typing import Any

MASK = "[redacted]"

# A key matches a name when its canonical form equals the name or ends with "-" + name.
EXACT = [
"accesskey", "cb-access-sign", "cf-access-client-id", "dpop", "fastly-key",
"jenkins-crumb", "paypal-transmission-sig", "plaid-verification",
"sec-websocket-protocol", "x-airtable-content-mac", "x-amzn-ava-user-context",
"x-amzn-oidc-data", "x-firebase-appcheck", "x-forge-oauth-system",
"x-forge-oauth-user", "x-honeycomb-team", "x-insert-key", "x-jfrog-art-api",
"x-nf-sign", "x-registry-config", "x-requestdigest", "x-sfdc-session",
"x-trello-webhook", "x-vault-mfa", "x-vercel-protection-bypass", "x-wp-nonce",
] # fmt: skip
# A key matches when its canonical form contains the word.
CONTAINS = [
"authorization", "secret", "password", "passwd", "passphrase", "cookie",
"signature", "credential", "jwt", "assertion", "bearer", "csrf", "xsrf", "hmac",
"saml",
"api-key", "apikey", "access-key", "private-key", "privatekey", "subscription-key",
"encryption-key", "signing-key", "shared-key", "sharedkey", "master-key",
"account-key", "app-key", "appkey", "application-key", "functions-key", "sas-key",
"license-key", "consumer-key", "client-key", "customer-key",
] # fmt: skip
# A key matches when one hyphen-separated part of its canonical form equals the word.
SEGMENT = ["auth", "token", "otp"]
# A key matches when its canonical form ends with the word.
SUFFIX = ["token"]

# The pair rule: a map that names a key in one entry and holds its value in another.
PAIR_NAME_KEYS = ["name", "key", "header"]
PAIR_VALUE_KEYS = ["value", "values"]
# The children of a map stored under this exact key are JSON Schema property names.
SCHEMA_PROPERTIES_KEY = "properties"


def camel_split(text: str) -> str:
out = []
for i, ch in enumerate(text):
if i > 0 and "A" <= ch <= "Z":
prev = text[i - 1]
nxt = text[i + 1] if i + 1 < len(text) else ""
if ("a" <= prev <= "z") or ("0" <= prev <= "9"):
out.append("-")
elif ("A" <= prev <= "Z") and ("a" <= nxt <= "z"):
out.append("-")
out.append(ch)
return "".join(out)


def canonical_parts(text: str) -> list[str]:
out = []
for ch in text:
if "A" <= ch <= "Z":
out.append(chr(ord(ch) + 32))
elif ("a" <= ch <= "z") or ("0" <= ch <= "9"):
out.append(ch)
else:
out.append("-")
parts = [p for p in "".join(out).split("-") if p]
while parts and all("0" <= c <= "9" for c in parts[-1]):
parts.pop()
return parts


def parts_match(parts: list[str]) -> bool:
if not parts:
return False
joined = "-".join(parts)
for name in EXACT:
if joined == name or joined.endswith("-" + name):
return True
for word in CONTAINS:
if word in joined:
return True
for part in parts:
if part in SEGMENT:
return True
for word in SUFFIX:
if joined.endswith(word):
return True
return False


def is_sensitive_key(key: str) -> bool:
return parts_match(canonical_parts(key)) or parts_match(
canonical_parts(camel_split(key))
)


def canonical(key: str) -> str:
return "-".join(canonical_parts(key))


def mask_value(value: Any, under_properties: bool) -> Any:
if value is None or isinstance(value, bool):
return value
if isinstance(value, dict) and under_properties:
return mask_sensitive_keys(value, False)
return MASK


def mask_sensitive_keys(value: Any, under_properties: bool = False) -> Any:
"""A masked copy of `value`. `under_properties` is true when `value` is the map
stored under the key "properties"."""
if isinstance(value, list):
return [mask_sensitive_keys(item, False) for item in value]
if not isinstance(value, dict):
return value
out = {}
for key, child in value.items():
if isinstance(key, str) and is_sensitive_key(key):
out[key] = mask_value(child, under_properties)
else:
out[key] = mask_sensitive_keys(child, key == SCHEMA_PROPERTIES_KEY)
names_a_sensitive_key = False
for key, child in value.items():
if isinstance(key, str) and canonical(key) in PAIR_NAME_KEYS:
if isinstance(child, str) and is_sensitive_key(child):
names_a_sensitive_key = True
if names_a_sensitive_key:
for key, child in value.items():
if isinstance(key, str) and canonical(key) in PAIR_VALUE_KEYS:
out[key] = mask_value(child, False)
return out
3 changes: 2 additions & 1 deletion tests/e2e/official/test_redaction_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ def redact(s: str) -> str:
auth = headers.get("authorization")
assert auth is not None
assert "super-secret-token-xyz" not in auth
assert auth == "Bearer [REDACTED]"
# The hook runs first; the event queue then masks the whole value.
assert auth == "[redacted]"
finally:
_set_redact(server, None)

Expand Down
Loading
Loading