Skip to content
Draft
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: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ For each release we list user-facing changes grouped as **Added**, **Changed**,

### Fixed

- **Stored API keys no longer reach the browser in clear text.** A key kept in `config.json`, whether typed in Settings or written by hand, used to come back in the capabilities response and fill a plain text input. The OpenAI-compatible and LiteLLM-compatible `api_key` properties (in the model lists and in the stored `chat_model` and `inline_completion_model` entries), `claude_settings.api_key`, and `acp_settings.api_key` are now sent as `********`, and the Settings inputs are password fields. Saving the panel with the mask untouched keeps the stored key; typing a new value replaces it and clearing the field removes it. Extension providers can opt a property in with `LLMProviderProperty(..., secret=True)`. Keys supplied through environment variables were already withheld.
- **MCP credentials no longer reach the browser or the workspace in clear text.** The Claude MCP panel's server list now masks every `env` and `headers` value, which it never displayed. The MCP config editor writes a temporary copy of `mcp.json` into the workspace; `env` and `headers` values whose names look like credentials (`Authorization`, `*_TOKEN`, `X-Api-Key`, and similar) are now masked in that copy, and a mask saved back keeps the stored value. A mask with no stored value behind it, such as a renamed server, is refused with a 400 instead of being saved. Values in `args` and `url` are not masked.
- **Claude CLI and Claude-mode error text no longer echoes credentials.** `claude mcp add` takes `env` and header values only as command-line flags, and the CLI's error output is forwarded to the browser, so those values are now scrubbed from it. The same scrub applies to Claude-mode stream errors shown in chat and in the inline editor. Passing a token to `claude mcp add` still exposes it in the process list while the CLI runs; the admin guide's new MCP server credentials section describes the trade-off.
- **Chat Markdown images no longer load automatically** (#533). Images in user, model, and tool Markdown now display a visible, translatable blocked-image notice, preserving safe image descriptions. Both local and remote image URLs are blocked to prevent requests that could disclose chat context without a click. Links containing images become non-clickable content so the notice cannot act as a load-image link. Dedicated image results still render; notebook Markdown cells use a separate renderer. See [Chat Markdown images](docs/admin-guide.md#chat-markdown-images).

## [6.3.0] - 2026-10-28
Expand Down
8 changes: 7 additions & 1 deletion docs/admin-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ Dedicated image results, such as figures delivered through image response events

## API-key handling

By default, custom-provider API keys (Anthropic, OpenAI-compatible, LiteLLM-compatible) are stored plaintext in `~/.jupyter/nbi/config.json`. This is acceptable for single-tenant developer workstations and unacceptable for multi-tenant clusters.
By default, custom-provider API keys (Anthropic, OpenAI-compatible, LiteLLM-compatible) are stored plaintext in `~/.jupyter/nbi/config.json`. The Settings dialog never receives a stored key: the server sends `********` in its place and keeps the stored key when the mask is saved back unchanged. This is acceptable for single-tenant developer workstations and unacceptable for multi-tenant clusters.

Recommended approach for clusters:

Expand All @@ -200,6 +200,12 @@ Recommended approach for clusters:

`${ENV_VAR}`-style interpolation inside `config.json` is not currently supported. Tracked as a feature request.

### MCP server credentials

Tokens in an MCP server's `env` or `headers` are stored in plaintext: in `mcp.json` for NBI's own MCP Servers tab, and in Claude's own config (`~/.claude.json` or `.mcp.json`) for the Claude-mode MCP Servers tab. NBI never sends those values to the browser in clear text. The Claude-mode server list masks them, and the `mcp.json` editor masks credential-named values and keeps the stored value when the mask is saved back.

The Claude-mode **Add MCP server** form hands values to `claude mcp add` as command-line flags, because the CLI has no other input for them. For the second or so the CLI runs, another local user on the same machine can read them from the process list. NBI scrubs those values from the CLI's error output. On a shared machine, avoid typing a real token into that form. Instead, add the server without the secret and supply it another way, for example with a `${VAR}` reference in the value. Check that your Claude CLI version expands `${VAR}` in MCP `env` and `headers` before relying on it.

---

## Self-hosted LLM endpoints
Expand Down
30 changes: 27 additions & 3 deletions notebook_intelligence/_claude_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@
import asyncio
import logging
import os
from typing import Optional
from typing import Iterable, Optional

from notebook_intelligence.util import resolve_claude_cli_path
from notebook_intelligence.util import (
_replace_values,
redact_env_secrets,
resolve_claude_cli_path,
)

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -102,6 +106,7 @@ async def run_claude_cli(
timeout: float = CLI_TIMEOUT_DEFAULT_SECONDS,
label: str = "claude",
env_overrides: Optional[dict[str, str]] = None,
secret_args: Optional[Iterable[str]] = None,
) -> str:
"""Run ``claude <tail...>`` and return its stdout.

Expand All @@ -111,6 +116,11 @@ async def run_claude_cli(
Values pass via env, not argv, so they don't appear in the redacted
DEBUG log.

``secret_args`` are values that have to travel in argv (``claude mcp add``
takes env and header values only as flags). The CLI's error text is
scrubbed of them before it is raised, since the handlers forward it to the
browser.

Raises:
FileNotFoundError: when the CLI can't be resolved.
TimeoutError: when the call exceeds ``timeout``.
Expand Down Expand Up @@ -148,10 +158,24 @@ async def run_claude_cli(
# The CLI's stderr is forwarded to the browser via the handlers'
# `_error()`; scrub any injected secret that the underlying tool
# might have echoed (git in verbose mode, curl 401 challenges, etc.).
raise ValueError(_scrub_env_overrides(raw, env_overrides))
raise ValueError(_scrub_error_text(raw, env_overrides, secret_args))
return out


def _scrub_error_text(
text: str,
env_overrides: Optional[dict[str, str]],
secret_args: Optional[Iterable[str]],
) -> str:
"""Scrub CLI error text of every credential this module knows about:
injected env values, secret argv values, then the shared redactor (process
env, stored credentials, known token prefixes)."""
out = _scrub_env_overrides(text, env_overrides)
if secret_args:
out = _replace_values(out, secret_args)
return redact_env_secrets(out)


def _scrub_env_overrides(text: str, env_overrides: Optional[dict[str, str]]) -> str:
"""Replace any env_overrides values that appear in `text` with `<redacted>`.

Expand Down
3 changes: 3 additions & 0 deletions notebook_intelligence/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,9 @@ class LLMProviderProperty:
description: str
value: str
optional: bool = False
# A credential: the capabilities response masks it and the settings panel
# renders it as a password field.
secret: bool = False

def to_dict(self):
return asdict(self)
Expand Down
23 changes: 13 additions & 10 deletions notebook_intelligence/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import logging
from claude_agent_sdk import AssistantMessage, PermissionResultAllow, PermissionResultDeny, ResultMessage, SdkMcpTool, TextBlock, ToolResultBlock, ToolUseBlock, UserMessage, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient, tool

from notebook_intelligence.util import ThreadSafeWebSocketConnector, _emit, get_jupyter_root_dir, import_litellm, resolve_claude_cli_path, safe_jupyter_path, terminate_process_tree
from notebook_intelligence.util import ThreadSafeWebSocketConnector, _emit, get_jupyter_root_dir, import_litellm, redact_env_secrets, resolve_claude_cli_path, safe_jupyter_path, terminate_process_tree
from notebook_intelligence.inline_completion import (
extract_inline_completion,
inline_completion_system_prompt,
Expand Down Expand Up @@ -1343,14 +1343,17 @@ def completions(self, messages: list[dict], tools: list[dict] = None, response:
# detect the failure and skip writing the partial buffer to the
# user's cell. Re-raise so the caller logs and runs finish().
if response is not None:
# Scrubbed: the text goes to the browser, and SDK and proxy
# errors can echo part of the credential they rejected.
error_text = redact_env_secrets(str(e))
response.stream({
"choices": [{
"delta": {
"role": "assistant",
"content": f"\n\n[Stream interrupted: {e}]"
"content": f"\n\n[Stream interrupted: {error_text}]"
}
}],
"nbi_stream_error": str(e)
"nbi_stream_error": error_text
})
raise

Expand Down Expand Up @@ -1563,7 +1566,7 @@ def _start_worker_thread(self) -> bool:
return True
except Exception as e:
self._client_thread = None
log.error(f"Error occurred while connecting to Claude agent client: {str(e)}")
log.error(f"Error occurred while connecting to Claude agent client: {redact_env_secrets(str(e))}")
self._set_status(ClaudeAgentClientStatus.FailedToConnect)
self._connect_resolved.set()
return False
Expand Down Expand Up @@ -1879,12 +1882,12 @@ def _tok(key: str) -> int:
))
in_flight_tools.clear()
except Exception as e:
err_msg = f"Error communicating with Claude agent: {str(e)}"
log.error(err_msg)
error_text = redact_env_secrets(str(e))
log.error(f"Error communicating with Claude agent: {error_text}")
if not self._reconnect_required:
trans = i18n.response_bundle(response)
response.stream(MarkdownData(
trans.__("Error communicating with Claude agent: %1", str(e))
trans.__("Error communicating with Claude agent: %1", error_text)
))
finally:
_emit(signal, {"id": event_id, "data": "query completed"})
Expand Down Expand Up @@ -2910,11 +2913,11 @@ async def handle_chat_request(self, request: ChatRequest, response: ChatResponse
# worker thread died. Surface it so the user sees why instead of a
# silent spinner stop.
if isinstance(result, str) and result:
response.stream(MarkdownData(trans.__("**Claude agent error:** %1", result)))
response.stream(MarkdownData(trans.__("**Claude agent error:** %1", redact_env_secrets(result))))
except Exception as e:
log.error(f"Error while handling Claude chat request: {e}", exc_info=True)
log.error(f"Error while handling Claude chat request: {redact_env_secrets(str(e))}", exc_info=True)
try:
response.stream(MarkdownData(trans.__("**Error:** %1", e)))
response.stream(MarkdownData(trans.__("**Error:** %1", redact_env_secrets(str(e)))))
except Exception as stream_err:
log.debug(f"Could not stream error to client (likely closed websocket): {stream_err}")
finally:
Expand Down
24 changes: 22 additions & 2 deletions notebook_intelligence/claude_mcp_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
from pathlib import Path
from typing import Iterable, Literal, Optional

from notebook_intelligence.credential_mask import (
credential_parts,
mask_mcp_server_credentials,
)

from notebook_intelligence._claude_cli import (
CLAUDE_SCOPES,
reject_flag_smuggling,
Expand Down Expand Up @@ -78,6 +83,11 @@ def to_dict(self) -> dict:
"disabled_for_workspace": self.disabled_for_workspace,
}

def to_wire_dict(self) -> dict:
"""``to_dict`` for the browser: ``env`` and ``headers`` values are
masked, since they hold tokens and the panel never shows them."""
return mask_mcp_server_credentials(self.to_dict())


def _read_json(path: Path) -> Optional[dict]:
try:
Expand Down Expand Up @@ -277,8 +287,15 @@ async def add_server(
tail.append("--")
tail.extend(args)

# env and header values can only travel as flags, so the CLI's error
# text, which the handlers forward to the browser, is scrubbed of them.
secret_args = [
part
for value in [*(env or {}).values(), *(headers or {}).values()]
for part in credential_parts(value)
]
async with self._write_lock:
await self._run_cli(tail)
await self._run_cli(tail, secret_args=secret_args)
srv = self.get_server(name, scope)
if srv is None:
# Surfaced if Claude wrote elsewhere or our reads missed it. The CLI
Expand Down Expand Up @@ -383,10 +400,13 @@ async def remove_server(self, name: str, scope: ClaudeMCPScope) -> None:

# --- internals -----------------------------------------------------

async def _run_cli(self, tail: list[str]) -> str:
async def _run_cli(
self, tail: list[str], secret_args: Optional[list[str]] = None
) -> str:
return await run_claude_cli(
tail,
cwd=str(self._working_dir),
timeout=CLI_TIMEOUT_SECONDS,
label="claude mcp",
secret_args=secret_args,
)
Loading
Loading