-
Notifications
You must be signed in to change notification settings - Fork 231
feat(mcp): add basic_memory_diagnostics tool for version and system info #963
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6382901
feat(mcp): add basic_memory_diagnostics tool for version and system info
groksrc a1e8a2c
fix(mcp): redact database_url credentials in diagnostics output
groksrc 7a957f5
test(mcp): use exact-equality assertions for redacted URLs
groksrc a801e2f
fix(mcp): drop stale API version from diagnostics, suppress duplicate…
groksrc 7be4f1d
fix(mcp): harden diagnostics output
phernandez cef13fa
fix(mcp): redact database URL query secrets
phernandez ef69298
fix(mcp): handle invalid diagnostics config encoding
phernandez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| """Diagnostic tool for Basic Memory version and system information.""" | ||
|
|
||
| import json | ||
| import platform | ||
| import sys | ||
| from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse | ||
|
|
||
| import basic_memory | ||
| from basic_memory.config import CONFIG_FILE_NAME, resolve_data_dir | ||
| from basic_memory.mcp.server import mcp | ||
|
|
||
| # Fields in BasicMemoryConfig that contain secrets and must never be surfaced. | ||
| _SECRET_FIELDS = frozenset({"cloud_api_key"}) | ||
|
|
||
| # Fields whose values are URLs that may embed user:password credentials. | ||
| # The userinfo component is stripped before surfacing. | ||
| _URL_FIELDS = frozenset({"database_url"}) | ||
|
|
||
| _SECRET_QUERY_KEYS = frozenset( | ||
| { | ||
| "api_key", | ||
| "apikey", | ||
| "credential", | ||
| "password", | ||
| "passwd", | ||
| "pwd", | ||
| "secret", | ||
| "secret_key", | ||
| "sslpassword", | ||
| "token", | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def _query_key_is_secret(key: str) -> bool: | ||
| normalized = key.strip().lower().replace("-", "_") | ||
| return normalized in _SECRET_QUERY_KEYS or normalized.endswith( | ||
| ("_password", "_secret", "_token", "_key") | ||
| ) | ||
|
|
||
|
|
||
| def _redact_query_secrets(query: str) -> str: | ||
| """Mask credential-bearing query values while preserving diagnostic options.""" | ||
| pairs = parse_qsl(query, keep_blank_values=True) | ||
| if not any(_query_key_is_secret(key) for key, _ in pairs): | ||
| return query | ||
| return urlencode([(key, "***" if _query_key_is_secret(key) else value) for key, value in pairs]) | ||
|
|
||
|
|
||
| def _redact_url(url: str) -> str: | ||
| """Strip userinfo and credential-bearing query values from a URL string. | ||
|
|
||
| Replaces any credentials with *** so the host/path remain visible for | ||
| diagnostics (e.g. ``postgresql://***@localhost/mydb``). If the value | ||
| cannot be parsed as a URL it is returned unchanged. | ||
| """ | ||
| try: | ||
| parsed = urlparse(url) | ||
| except ValueError: | ||
| # A malformed authority can still contain credentials. Redact the | ||
| # userinfo and query conservatively rather than returning a secret unchanged. | ||
| base, query_separator, query = url.partition("?") | ||
| safe_url = f"{base}?{_redact_query_secrets(query)}" if query_separator else base | ||
| scheme, separator, remainder = safe_url.partition("://") | ||
| if separator and "@" in remainder: | ||
| _, _, authority = remainder.rpartition("@") | ||
| return f"{scheme}://***@{authority}" | ||
| return safe_url | ||
|
|
||
| redacted_query = _redact_query_secrets(parsed.query) | ||
| if "@" not in parsed.netloc and redacted_query == parsed.query: | ||
| # Neither URL userinfo nor known secret query parameters are present. | ||
| return url | ||
|
|
||
| redacted_netloc = parsed.netloc | ||
| if "@" in parsed.netloc: | ||
| # Preserve the authority verbatim after the final @. In particular, using | ||
| # parsed.hostname here would discard the brackets required around IPv6 hosts. | ||
| _, _, authority = parsed.netloc.rpartition("@") | ||
| redacted_netloc = f"***@{authority}" | ||
|
|
||
| return urlunparse(parsed._replace(netloc=redacted_netloc, query=redacted_query)) | ||
|
|
||
|
|
||
| def _redact_config(raw: dict) -> dict: | ||
| """Return a copy of the raw config dict with secret fields removed. | ||
|
|
||
| - Keys in ``_SECRET_FIELDS`` are dropped entirely. | ||
| - Keys in ``_URL_FIELDS`` have userinfo and credential-bearing query values | ||
| stripped so that safe host, database, and connection options remain visible. | ||
|
|
||
| Only top-level keys are processed. Nested keys within project entries are | ||
| not currently credential-bearing, but the two sets make the pattern easy | ||
| to extend. | ||
| """ | ||
| result: dict = {} | ||
| for k, v in raw.items(): | ||
| if k in _SECRET_FIELDS: | ||
| # Drop entirely — value has no diagnostic value. | ||
| continue | ||
| if k in _URL_FIELDS and isinstance(v, str): | ||
| result[k] = _redact_url(v) | ||
| else: | ||
| result[k] = v | ||
| return result | ||
|
|
||
|
|
||
| @mcp.tool( | ||
| "basic_memory_diagnostics", | ||
| title="Basic Memory Diagnostics", | ||
| tags={"diagnostics"}, | ||
| annotations={ | ||
| "title": "Basic Memory Diagnostics", | ||
| "readOnlyHint": True, | ||
| "destructiveHint": False, | ||
| "openWorldHint": False, | ||
| }, | ||
| # The report is a markdown string; suppress FastMCP's wrap_result so the | ||
| # payload isn't duplicated into structuredContent. | ||
| output_schema=None, | ||
| ) | ||
| def basic_memory_diagnostics() -> str: | ||
| """Return version, system, and configuration diagnostics for Basic Memory. | ||
|
|
||
| Provides: | ||
| - Basic Memory package version | ||
| - Python version and platform details | ||
| - Config file path and its contents (secrets redacted) | ||
|
|
||
| Useful for troubleshooting installations and gathering information for | ||
| support requests. Read-only; never emits secrets or API keys. | ||
| """ | ||
| # --- Version information --- | ||
| bm_version = basic_memory.__version__ | ||
| api_version = basic_memory.__api_version__ | ||
|
|
||
| # --- System information --- | ||
| python_version = sys.version | ||
| platform_info = platform.platform() | ||
| machine = platform.machine() | ||
|
|
||
| # --- Configuration --- | ||
| # resolve_data_dir only computes the path. ConfigManager would create and | ||
| # chmod the directory, violating this tool's read-only contract. | ||
| config_file = resolve_data_dir() / CONFIG_FILE_NAME | ||
| config_exists = config_file.exists() | ||
|
phernandez marked this conversation as resolved.
|
||
|
|
||
| if config_exists: | ||
| try: | ||
| raw_config = json.loads(config_file.read_text(encoding="utf-8")) | ||
| except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: | ||
| config_dump = f"<error reading config: {exc}>" | ||
| else: | ||
| if isinstance(raw_config, dict): | ||
| safe_config = _redact_config(raw_config) | ||
| config_dump = json.dumps(safe_config, indent=2, default=str) | ||
| else: | ||
| config_dump = "<error reading config: expected a JSON object>" | ||
| else: | ||
| config_dump = "<config file not found>" | ||
|
|
||
| lines = [ | ||
| "# Basic Memory Diagnostics", | ||
| "", | ||
| "## Version", | ||
| f"- basic-memory: {bm_version}", | ||
| f"- API: {api_version}", | ||
| "", | ||
| "## System", | ||
| f"- Python: {python_version}", | ||
| f"- Platform: {platform_info}", | ||
| f"- Architecture: {machine}", | ||
| "", | ||
| "## Configuration", | ||
| f"- Config path: {config_file}", | ||
| f"- Config exists: {config_exists}", | ||
| "", | ||
| "```json", | ||
| config_dump, | ||
| "```", | ||
| ] | ||
| return "\n".join(lines) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.