Skip to content

Studio: only a UI session may define a local (stdio) MCP command - #8550

Merged
danielhanchen merged 5 commits into
mainfrom
studio-stdio-mcp-ui-session-gate
Aug 12, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-stdio-mcp-ui-session-gate

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The problem

A stdio MCP server is not a URL, it is a command Studio runs on the host as the backend user, outside the python/terminal sandbox. That is the point of the feature, and typing a command into your own machine's settings page is fine.

The routes that accept that command were guarded only by get_current_subject, which accepts sk-unsloth- API keys on equal footing with a UI session JWT. An API key is something you paste into another program so it can reach your model. It should not also be able to pick what program the backend runs:

POST /api/mcp/servers/test
Authorization: Bearer sk-unsloth-...
{"url": "/bin/sh -c '...'"}

_validate_url sees a non-http value, treats it as a command, and /test immediately probes it, which spawns it. Same primitive in routes/data_recipe/mcp.py, which takes command / args / env straight from the request body.

The host-level gate is already in good shape after #5892, #6295 and #7875: stdio_mcp_enabled() only auto-enables on a loopback bind, excludes Colab, and is revoked by --disable-tools and by an active remote connector. What was missing was the credential class.

The change

Only a UI session may define a local command. This reuses the existing authenticated_via_api_key classifier and the require_ui_session pattern already used in routes/settings.py and routes/providers.py, via one new helper in auth/authentication.py.

Gated, since the caller supplies the command:

  • routes/mcp_servers.py: create, update, test, refresh, import
  • routes/data_recipe/: /mcp/tools, /jobs, /validate

Placement details:

  • The guard runs before any write, OAuth cleanup, cache eviction, session close or probe, so a refusal changes nothing. On /test in particular it has to land before list_tools_async, since after that the process has already started.
  • update checks both the stored and the resulting address, so an API key can neither repoint an http row at a command nor edit an existing stdio row's env, name or enabled flag.
  • import gates per entry, so a mixed config still creates its http servers and reports the stdio ones in errors. Re-importing the same config stays idempotent.

What does not change

Caller Local (stdio) command http(s) MCP server
Studio web UI / desktop app (session JWT) unchanged unchanged
API key (sk-unsloth-) 403 unchanged

An API key also still uses stdio servers the owner configured through the UI during chat. Those are the owner's own approved tools, and the key can no longer choose what the command is, so the arbitrary-execution primitive is gone without touching the inference path.

The web UI, the Data Recipe UI and the desktop app all authenticate through the shared authFetch helper with a session JWT, and the desktop app trades its local secret for a JWT. A grep across the repo, including notebooks, docs, Rust and the CLI, found no caller of these endpoints using an API key, so the new 403 is unreachable from anything we ship.

No change to stdio_mcp_enabled(), host_policy.py, main.py, run.py or the frontend, and MCP processes are not sandboxed, since real servers legitimately need filesystem and network access.

Testing

New tests/test_mcp_stdio_api_key_gate.py, 18 tests. The probe is stubbed to fail the test if it is ever reached, so a guard placed after the spawn would not pass.

  • API key plus a command on create, update, test, refresh, import: 403, nothing written, transport never reached.
  • API key converting an http row to a command, and editing an existing stdio row's name, env or enabled flag: 403.
  • API key on http(s) create, update, test, refresh: unchanged.
  • Mixed import from an API key: http entry created, stdio entry reported in errors, second import idempotent.
  • UI session: every current stdio behaviour preserved.
  • Data recipe: /mcp/tools, /jobs and /validate refuse a stdio provider from an API key.

All existing MCP suites pass with no edits to any of them (302 passed, 2 skipped across test_mcp_servers.py, test_mcp_stdio_pr5863.py, test_mcp_stdio_improvements.py, test_mcp_config_import.py, test_mcp_stdio_sessions.py, test_mcp_server.py, test_mcp_flatten_result.py, test_remote_access_settings.py). That is deliberate: the dependency is Annotated[bool, Depends(...)] = False rather than a Depends default, because a Depends object is truthy and would have made every direct handler call in those suites read as an API key.

Verified against a running app as well: with an API key, POST /api/mcp/servers/test with a shell command returns 403 and the command does not run, while the same request with a session JWT still returns 201 on create, and an API key testing an https:// server still reaches the transport as before.

danielhanchen and others added 3 commits August 12, 2026 12:18
A stdio MCP server is a command Studio runs on the host as the backend
user, outside the python/terminal sandbox. The routes that accept that
command were guarded by get_current_subject, which accepts sk-unsloth API
keys on equal footing with a UI session JWT. An API key is something you
paste into another program so it can reach the model, so it should not
also be able to pick what program the backend runs.

Gate the routes where the caller supplies the command on a non-API-key
credential, reusing the existing authenticated_via_api_key classifier and
the require_ui_session pattern from routes/settings.py and
routes/providers.py:

  - mcp_servers: create, update, test, refresh, import
  - data_recipe: /mcp/tools, /jobs, /validate, which take command/args/env
    straight from the request body

The guard runs before any write, OAuth cleanup, cache eviction, session
close or probe, so a refusal changes nothing. update checks the stored and
the resulting address, so an API key can neither repoint an http row at a
command nor edit an existing stdio row's env. import gates per entry, so a
mixed config still creates its http servers and reports the stdio ones,
and re-importing stays idempotent.

Nothing else changes. http(s) MCP servers keep working from an API key,
and an API key still uses stdio servers the owner configured through the
UI in chat, since it can no longer choose what the command is. The web UI,
the Data Recipe UI and the desktop app all authenticate with a session
JWT, so none of them is affected.

The dependency is Annotated with a plain False default rather than a
Depends default, so the existing suites that call these handlers directly
keep reading as UI sessions and needed no edits.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 12, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a664840502

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +212 to +213
if is_stdio(old["url"]) or is_stdio(changes.get("url", old["url"])):
require_ui_session_for_local_commands(via_api_key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recheck the transport atomically before applying updates

When an API-key request updates an OAuth-enabled HTTP row, this check occurs before clear_oauth_tokens_async yields, while the eventual database update is unconditional. If a UI request converts the same row to stdio during that await, an API-key payload such as {headers: ..., use_oauth: false} subsequently writes those headers as the stdio process environment, bypassing the new credential gate and potentially changing what executes. Make the write conditional on the previously checked URL/version, or re-read and reapply the gate after the await before updating.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 4210c01. Reproduced it: with clear_oauth_tokens_async patched to convert the row to a command mid-await, an API-key PUT of {headers: {LD_PRELOAD: ...}, use_oauth: false} passed the gate as http and then wrote those headers as the command's process environment. The await is real I/O (auth.token_storage_adapter.clear()), so the loop is free to run the converting request in that window.

The row is now re-read after the await and the gate re-applied before the write, so the same repro returns 403 and headers_json stays null. Added test_update_regates_after_the_oauth_clear_await. The other handlers have no await between their gate and their side effect: create and import write synchronously, and test and refresh gate the address they later probe.

clear_oauth_tokens_async awaits real I/O, so the event loop can run another
request between the gate and the write. If a UI session converts the same row
to a local command in that window, an API-key payload of {headers, use_oauth:
false} passed the gate as http and then wrote those headers as the command's
process environment, which PATH or LD_PRELOAD can use to change what runs.

Re-read the row after the await and re-apply the gate before writing.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 4210c012a5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen
danielhanchen merged commit 7dfee7e into main Aug 12, 2026
45 of 53 checks passed
@danielhanchen
danielhanchen deleted the studio-stdio-mcp-ui-session-gate branch August 12, 2026 12:55
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 02e3ff9120

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 12, 2026
Follow-up to unslothai#8550, which put local (stdio) MCP commands behind a UI
session on every route that defines one. Two paths still let an
sk-unsloth API key around it.

GET /api/mcp/servers/ returns stored rows verbatim. For a stdio row both
fields are secrets: url is the argv, which carries credentials often
enough that stdio_log_id exists so it is never logged raw, and headers is
the subprocess env. A key that may not define a command could still read
back one the owner had defined, tokens included. Listing now drops stdio
rows for API-key callers. Dropping the row rather than blanking its
fields also keeps a redacted url from round-tripping into update as a
bogus command. http(s) rows are untouched, headers included, and a UI
session still sees everything.

mcp_server.py calls the validate route function directly, so the
ViaApiKey dependency never runs and its `= False` default reads as a UI
session. The /mcp surface is a remote static bearer, so it could validate
a recipe carrying a stdio provider, which discovers that provider's tools
and starts the command. It now passes via_api_key = True explicitly.

Tests: the listing hides the stdio row from a key with the argv and env
secrets asserted absent from the serialized response, shows both to a
session, keeps http headers visible to a key, and pins the call site that
has to hand in the flag.
danielhanchen added a commit that referenced this pull request Aug 12, 2026
* Studio: two ways past the stdio MCP UI-session gate

Follow-up to #8550, which put local (stdio) MCP commands behind a UI
session on every route that defines one. Two paths still let an
sk-unsloth API key around it.

GET /api/mcp/servers/ returns stored rows verbatim. For a stdio row both
fields are secrets: url is the argv, which carries credentials often
enough that stdio_log_id exists so it is never logged raw, and headers is
the subprocess env. A key that may not define a command could still read
back one the owner had defined, tokens included. Listing now drops stdio
rows for API-key callers. Dropping the row rather than blanking its
fields also keeps a redacted url from round-tripping into update as a
bogus command. http(s) rows are untouched, headers included, and a UI
session still sees everything.

mcp_server.py calls the validate route function directly, so the
ViaApiKey dependency never runs and its `= False` default reads as a UI
session. The /mcp surface is a remote static bearer, so it could validate
a recipe carrying a stdio provider, which discovers that provider's tools
and starts the command. It now passes via_api_key = True explicitly.

Tests: the listing hides the stdio row from a key with the argv and env
secrets asserted absent from the serialized response, shows both to a
session, keeps http headers visible to a key, and pins the call site that
has to hand in the flag.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: tighten the stdio MCP listing comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant