Repository navigation
Write-only MCP secrets and server editor in settings (part of #185) - #542
rohantiwari9573 wants to merge 6 commits into
Conversation
MCP tool names are chosen by the MCP server and can contain any character, including quotes, backslashes and newlines. Build the generated handler source with repr() literals, so every server and tool name is kept exactly as a string, in the docstring as well as in the values the handler uses. Action names and calls are unchanged. Adds tests with names containing quotes, newlines, triple quotes and a line continuation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… for MCP
Adds the MCP Streamable HTTP transport ("transport": "http", with the
aliases streamable_http and streamable-http): JSON and SSE responses,
Mcp-Session-Id and MCP-Protocol-Version handling, renewing an expired
session once, resuming SSE streams, a size limit per message and
DELETE on close. Redirects are not followed.
Per-server "headers" and "timeout" are validated in mcp_config.json.
${NAME} references in header values resolve only from that server's
own "env", never from the process environment. Header values are
never listed or logged, and URLs are logged without credentials.
Also:
- reload reconnects changed or dead servers and keeps the last good
settings of a server whose new entry is invalid;
- invalid entries are kept on save and reported;
- tool listing is paginated;
- /mcp add --transport http and /mcp header;
- profile bundles validate entries with the same rules and keep local
credentials only for the same server;
- AGENT.md documents the http transport.
The settings payload for the existing editors is unchanged; header
values and stdio arguments are not sent.
Part of CraftOS-dev#185.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The settings payload now reports which env keys are set and how many stdio arguments are stored, never their values. Both editors are updated to match: - browser: a form editor for transport, URL, command and arguments, timeout, headers and env, where an empty secret field keeps the stored value; "Add from JSON" is kept; - terminal: the MCP tab writes only the keys that were changed. Adds the mcp_save_server handler, which validates with the same rules as mcp_config.json and refreshes the running servers. Ships together with its UI changes: the old editors would overwrite stored secrets with the new payload. Part of CraftOS-dev#185. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zfoong
left a comment
There was a problem hiding this comment.
Thanks. On my side the browser tsc and vite build, the terminal type-check and the terminal vitest suite (223 tests) all pass, and the full Python suite shows no new failures compared with dev. Three things to fix:
1. "Add Server" can wipe the whole config (app/ui_layer/settings/mcp_settings.py:290, with load_mcp_config at :44-50)
load_mcp_config() returns an empty MCPConfig() on any load error. If mcp_config.json has a syntax error (a trailing comma from hand-editing, say), save_mcp_server(create=True) sees no conflict and writes a file containing only the new server. Every other server and its env and header values are lost. I reproduced this. _add_entry already had the same flaw, but this PR makes it the main Add button. Please refuse to save when the config failed to load (ideally in _add_entry too).
2. A duplicate env key overwrites a stored secret with "" (MCPServerEditor.tsx:112, mcp_settings.py:367)
_merge_write_only doesn't reject duplicate keys, and the last row wins. If TOKEN is stored and the user adds another TOKEN row with an empty value (or renames an unset key to TOKEN), the new row isn't stored, so it sends "" and saves TOKEN="". Rejecting duplicate keys in both the form and the backend would fix it.
3. Switching away from http drops stored headers (mcp_settings.py:326-327)
Changing the transport from http to sse, websocket or stdio silently drops every stored header value, including literal ones like Authorization: Bearer .... The headers section just disappears from the form, and switching back doesn't restore them. A warning before saving, or keeping the headers, would avoid the surprise.
…dentials - Split SSE streams on CR, LF and CRLF only. httpx's aiter_lines also splits on U+2028, U+0085 and the other str.splitlines separators, which servers send unescaped inside JSON data. Both the Streamable HTTP transport and the legacy SSE transport use the new splitter. - Enforce the 16 MB limit while a line is being read, so an unterminated line is never held in memory in full. - Accept "headers" and "timeout" on stdio, sse and websocket entries again, as earlier versions did. They are ignored with a one-time warning and kept unchanged in the file. - Profile bundle import keeps a local entry that has saved credentials when the bundle's entry with the same name reaches a different server, and reports the name as skipped. - Clear the old Mcp-Session-Id when a renewed session comes back without one. - Never save over an MCP config file that exists but cannot be read when adding a server; report the error instead. Part of CraftOS-dev#185.
…-settings-ui Brings in the CraftOS-dev#185 review fixes from CraftOS-dev#541.
…ders - The server form never saves over an MCP config file that cannot be read; it shows the error and writes nothing. - Reject a key listed twice in the form, in the backend and in the browser editor, so an empty new row cannot replace a stored secret. Header names are compared case-insensitively. - Keep saved headers when a server is switched away from http; they apply again when it is switched back, and the editor says so. Part of CraftOS-dev#185.
|
Thanks. All three are fixed in 7c06ea9. The branch also merges #541's review fixes in (c81d55d), without rewriting history:
Tests: each fix has a regression test that fails on the previous commit. MCP tests: 234 passed. Browser |
ahmad-ajmal
left a comment
There was a problem hiding this comment.
Thanks, this is a solid change. Making env values, header values and stdio arguments write-only is the right call, and the keep / replace / delete scheme (null keeps, a string replaces, a missing row deletes) is simple and easy to follow. Shipping the backend and both editors together is also right, since the old editors would have saved true over real keys. The three points from the earlier review are fixed and each has a regression test. Locally, test_mcp_settings_write_only.py, test_mcp_settings.py, test_mcp_config.py and test_resource_changes.py pass (131 tests).
Most of what I found is cleanup the switch left behind. Details are in the inline comments.
Please fix in this PR (all small):
- Delete the
mcp_get_envpath. Nothing sends it any more, andget_server_env_varsreturns raw secrets with no caller. - Delete the unused
MCPServerConfig/MCPListResponsetypes intypes/index.tsinstead of updating them. - Check the types of
enabled,argsanddescriptionon save."enabled": "false"is currently saved as a string, and a non-empty string is truthy, so the server stays enabled. - Send
headersfor every transport, so a header the user deleted stays deleted after a transport switch. - Add
mcp_save_serverto_RESOURCE_BY_MESSAGE_TYPEinapp/ui_layer/events/resource_changes.py(line 161), next to the other MCP messages. That file isn't in this diff, so I can't leave the comment inline. - Remove the
mcp.env.*locale keys the old modal used, in all seven locale files.
Fine here or as a follow-up:
- Refresh the status line after enable / disable / remove / Add from JSON too, not only after Save (see the comment on
_schedule_mcp_refresh). - Have the terminal save env through
mcp_save_server, so there is one write path. - Pre-fill env rows for
missing_envkeys in the editor. - Send a
url_redactedflag instead of matching the redaction text in TypeScript. - Translations: only
enhas the newmcp.editor.*strings, and the other six locales'addHintstill says the add button is for JSON config. Ignore this if translations are handled separately. - Longer term: arguments are hidden as a whole, so changing one path means retyping the full list without seeing it. Supporting
${NAME}in stdioargs(the same way headers work) would let secrets live inenv, and the arguments could be shown normally. That belongs in its own PR.
On merging: since this is stacked on #541, could we merge #541 first and then rebase this branch? That way the diff shows only this PR's own ~1,100 lines.
| @@ -6589,16 +6613,29 @@ async def _handle_mcp_add_json(self, name: str, config: str) -> None: | |||
| ) | |||
|
|
|||
| async def _handle_mcp_get_env(self, name: str) -> None: | |||
There was a problem hiding this comment.
Nothing sends mcp_get_env any more. The browser editor stopped using it in this PR, and the terminal tab dropped it too. So instead of updating it, we can delete:
- this handler and its
elifbranch in the dispatcher (line 2104), get_server_env_statusandget_server_env_varsinmcp_settings.py,- their exports in
settings/__init__.py.
get_server_env_vars in particular returns raw secret values and has no caller, so it's worth removing before someone reaches for it.
| command?: string | ||
| action_set: string | ||
| env: Record<string, string> | ||
| transport: 'stdio' | 'sse' | 'websocket' | 'http' |
There was a problem hiding this comment.
MCPServerConfig and MCPListResponse in this file aren't imported anywhere. The editor, the settings page and the terminal all use the type in mcpSettingsSlice.ts. Could we delete these two rather than keep two copies in sync?
| if "command" in form: | ||
| data["command"] = form["command"] or None | ||
| if form.get("args") is not None: # None keeps the stored arguments | ||
| data["args"] = list(form["args"]) |
There was a problem hiding this comment.
These form values go into the config without a type check. I tried a few against a temp config:
"enabled": "false"is saved as the string"false". It's truthy, so the server stays enabled."args": "abc"is saved as["a", "b", "c"], becauselist()splits a string into characters."args": [1, null]and"description": 123are saved as they are.
The form never sends these, so the risk is low today, but this is the WebSocket entry point. The JSON file has the same gap, so checking types in MCPServerConfig.__post_init__ would cover both: enabled is a bool, args is a list of strings, description is a string. A bad hand-edited entry would then show up as invalid in the list instead of half-working.
| const typed = args.split('\n').map(a => a.trim()).filter(Boolean) | ||
| form.args = typed.length === 0 && savedArgs > 0 ? null : typed // null keeps them | ||
| } | ||
| if (transport === 'http') { |
There was a problem hiding this comment.
headers is only sent while the transport is http. Here's how a deleted header can come back:
- The user deletes a header row.
- They switch the transport to stdio, sse or websocket and save. The form leaves out
headers, so the backend keeps the deleted header (set aside). - If they switch back to http later, the header is back.
Sending headers for every transport fixes this, because the backend already sets them aside for non-http servers. The duplicate-name check on lines 121–122 would then also run for every transport.
| () => (server?.headers ?? []).map(h => row(h.name, true, h.uses)), | ||
| ) | ||
| const [env, setEnv] = useState<Row[]>( | ||
| () => Object.entries(server?.env ?? {}).map(([key, isSet]) => row(key, isSet)), |
There was a problem hiding this comment.
Env rows come only from server.env. If a header uses ${TOKEN} but TOKEN isn't in env (easy to end up with via Add from JSON), the list says "Needs config", but the editor shows no TOKEN field. The user has to work out that they should add it by hand. Could we add an empty row for each key in server.missing_env that isn't already in env?
| @@ -554,6 +554,46 @@ | |||
| "desc": "Set the required environment variables for this MCP server.", | |||
| "none": "No environment variables to configure.", | |||
| "placeholder": "Enter {{key}}..." | |||
There was a problem hiding this comment.
The old env modal is gone, so the mcp.env.* keys (title, desc, none, placeholder) aren't used any more. They can be removed here and in the other six locale files.
| "command": server.command, | ||
| # Arguments can carry tokens (--api-key ...): count only. The | ||
| # editor keeps them unless the user enters a new list. | ||
| "args": None, |
There was a problem hiding this comment.
Nit: args is always None, here and in the invalid-entry branch, and args_count carries the information. We could drop the key, along with args?: string[] | null in the TS type.
| seen.add(folded) | ||
| value = item.get("value") | ||
| if value is None: | ||
| lookup_key = key.lower() if case_insensitive else key |
There was a problem hiding this comment.
Nit: lookup_key has the same value as folded from line 398, so we can reuse folded.
| /** The backend says whether a server still needs values (env says only | ||
| * which keys are set: values are never sent to a client). */ | ||
| export function needsConfig(server: MCPServerConfig): boolean { | ||
| if (typeof server.needs_config === 'boolean') return server.needs_config |
There was a problem hiding this comment.
Nit: the backend always sends needs_config, both from describe_server and for invalid entries, so the fallback on the next line never runs. Since the terminal and backend ship together, this could simply be return server.needs_config === true.
| .filter(s => !query | ||
| || s.name.toLowerCase().includes(query) | ||
| || (s.description && s.description.toLowerCase().includes(query))) | ||
| .slice() |
There was a problem hiding this comment.
Nit: .filter() already returns a new array, so .slice() isn't needed before .sort().
Depends on #541 (stacked on it and on #540; review the top commit only until both are merged).
Part of #185.
Summary
MCP env values and stdio arguments often hold API keys. Today the settings payload sends them in plain text to the browser and terminal UIs. This PR makes them write-only and updates both editors to match.
mcp_settings.py,browser_adapter.py):envis reported as{KEY: true|false}(set or not), and stdio arguments asargs_count. Values are never sent.mcp_get_envreturns the same booleans.mcp_save_serverhandler takes the whole form. It validates it with the same rules asmcp_config.json, saves it, and refreshes the running servers.nullkeeps the stored value. This applies to env and header values,urlandargs.MCPServerEditorform for creating and editing servers. It covers transport, URL, command and arguments, timeout, headers and env.McpTabno longer reads values back. It sends only the keys the user changed (mcpEnv.ts) and shows a "keep" placeholder for keys that are already set.Why the backend change and both UIs ship together
Once the payload reports booleans instead of values, the current editors would load
trueas an env value and write it back on save, overwriting the real key. The masking and both editors therefore have to land in the same change. #541 keeps the old payload shape for exactly this reason, so merging #541 alone is safe, and this PR switches everything at once.Testing
tests/test_mcp_settings_write_only.py(write-only payloads, keep-on-empty, error messages without secrets, create/duplicate/missing/invalid, browser handlers)tests/test_mcp*.py, Python 3.10, with SDK interop enabledpytest --continue-on-collection-errors --assert=plain, 9 min 2 s)devwithout this change (listed in #541)tsc --noEmitandvite buildmcpTab.test.ts)Not tested:
npm run lintexits with an error ondevas well).Behaviour changes
mcp_listandmcp_get_envno longer return env values, andargsis replaced byargs_count. Any other client of these messages needs the same update. I found none in the repo besides the two editors updated here.