Skip to content

feat(mcp): spotatui mcp, the MCP server front door on dj-core - #429

Merged
LargeModGames merged 4 commits into
mainfrom
dj/mcp-server
Aug 8, 2026
Merged

LargeModGames merged 4 commits into
mainfrom
dj/mcp-server

Conversation

@LargeModGames

@LargeModGames LargeModGames commented Aug 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

PR 2 of the stack. Part of #196.

Puts a spotatui mcp stdio server in front of the dj-core tool table, so
Claude Code, Codex, Gemini CLI, or any MCP client can act as the DJ: read the
listening history, search the catalogue, and queue tracks. No LLM client and
no API key are compiled in, and no crate dependency is added; the agent on the
other end brings its own model.

  • Off by default: behavior.mcp_enabled: true turns it on, and the control
    socket binds loopback-only behind a token in ~/.config/spotatui/mcp.json
  • Written against MCP revision 2026-07-28 (stateless), and dual-era: it still
    answers initialize for the clients shipping today
  • search_tracks marks every result owned or new; queue_tracks takes
    exclude_owned: true for agents that want the guarantee, reports what it
    skipped, and substitutes nothing
  • docs/mcp-setup.md is written as instructions for an agent to follow, with
    spotatui mcp status as a safe, machine-checkable probe of each step
  • The Logging to: startup notice moves to stderr, since the MCP spec allows
    nothing but protocol messages on stdout

Testing

  • cargo clippy -D warnings on: telemetry / telemetry,dj-core /
    telemetry,mcp-server / all-sources minus audio-viz
  • cargo test --no-default-features --features telemetry,mcp-server
    (670 passed, including 47 MCP protocol/relay/control tests)
  • cargo check --locked
  • Cargo.lock unchanged (no new dependency)

Additional notes

Two links are intentionally absent from docs/mcp-setup.md in this PR because
their targets land later in the stack: the agent-plugin shortcut (PR 5) and
the see-also to docs/ai-dj.md (PR 4). A few allow(dead_code) attributes are
staged and narrow to their final form when the in-TUI door lands.


💬 Questions or want to chat with other contributors? Join the spotatui Discord.

Summary by CodeRabbit

  • New Features

    • Added an optional MCP server for agent-controlled playback, listening history, catalogue search, and queue management.
    • Added spotatui mcp and mcp status, including machine-readable status reports.
    • Added secure local connections with token authentication, ownership-aware queueing, and offline guidance.
    • Added support for modern and legacy MCP clients.
  • Documentation

    • Added setup, configuration, troubleshooting, and client registration guidance.
    • Expanded AI DJ and feature documentation.
  • Bug Fixes

    • Startup logs now consistently go to stderr.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4911b84b-3126-4efd-bed6-e6fae0b68588

📥 Commits

Reviewing files that changed from the base of the PR and between 05f81f7 and 538208e.

📒 Files selected for processing (1)
  • src/infra/mcp/relay.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/infra/mcp/relay.rs

📝 Walkthrough

Walkthrough

The PR adds an opt-in mcp-server feature. It provides an MCP stdio relay, authenticated loopback control, protocol compatibility, DJ playback tools, status checks, configuration, documentation, and CI coverage.

Changes

MCP server integration

Layer / File(s) Summary
Feature, configuration, and entry points
.github/workflows/*, Cargo.toml, src/cli/*, src/runtime.rs, src/core/*, README.md, docs/mcp-setup.md, CLAUDE.md, CHANGELOG.md
Adds the mcp-server feature, opt-in configuration, CLI commands, runtime startup and cleanup, CI coverage, documentation, changelog entries, and conditional dead-code handling.
Protocol and executor
src/infra/mcp/protocol.rs, src/infra/mcp/server.rs, src/infra/dj/exec.rs, src/infra/mcp/executor.rs
Adds modern and legacy protocol negotiation, JSON-RPC handling, tool descriptors, shared execution, offline errors, and protocol tests.
Authenticated control and relay flow
src/infra/mcp/control.rs, src/infra/mcp/relay.rs, src/infra/mcp/status.rs
Adds loopback authentication, protected handshake files, stdio relaying, reconnect handling, offline fallback, status probing, and related tests.
DJ tool routing and playback operations
src/infra/network/dj.rs, src/infra/network/mod.rs
Adds serial-lane DJ calls for search, ownership filtering, queueing, URI resolution, and playback, with structured outcomes and validation.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Relay
  participant TUI
  participant Network
  Client->>Relay: Send MCP JSON-RPC request
  Relay->>TUI: Authenticate over loopback control channel
  TUI->>Network: Route DjToolCall
  Network-->>TUI: Return ToolOutcome
  TUI-->>Relay: Return MCP response
  Relay-->>Client: Write response
Loading

Possibly related PRs

  • LargeModGames/spotatui#428: Provides the shared dj-core tool layer that this PR enables through mcp-server and connects to MCP execution.
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title uses the valid feat(mcp): prefix and describes the MCP server change, but its subject is not imperative. Use an imperative subject, for example: feat(mcp): add the spotatui MCP server front door for dj-core
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dj/mcp-server
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch dj/mcp-server

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Base automatically changed from dj/core to main August 8, 2026 08:24

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 10

🧹 Nitpick comments (6)
docs/mcp-setup.md (2)

6-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add language tags to the fenced blocks.

markdownlint-cli2 reports MD040 for the prompt, diagram, and status-output fences. Add text to the opening fences at Lines [6], [24], and [106].

Also applies to: 24-26, 106-110

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/mcp-setup.md` around lines 6 - 10, Add the text language tag to the
opening fences for the prompt, diagram, and status-output blocks in the
documentation, including the fences near the shown prompt and the additional
blocks near lines 24 and 106, while preserving their contents.

Source: Linters/SAST tools


63-67: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Keep local-checkout installation locked.

Cargo.lock exists for this project, so add --locked to the checkout install command as well to use the committed dependency graph.

Proposed command change
-  cargo install --path . --features mcp-server
+  cargo install --locked --path . --features mcp-server
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/mcp-setup.md` around lines 63 - 67, Update the checkout installation
command in the MCP setup instructions to include the --locked flag, matching the
existing spotatui installation command and ensuring Cargo uses the committed
dependency graph.
src/infra/network/dj.rs (2)

255-263: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the network-layer status-message helper, and set it outside the locked block.

Line 261 writes the status message through app.set_status_message while the App lock is held inside this block. The path instruction requires self.show_status_message(msg, ttl_secs) in the async network layer. show_status_message takes the App lock itself, so the call has to move after the block ends.

As per path instructions: "User feedback goes through the status-message helpers, never by assigning app.status_message directly: app.set_status_message(msg, ttl_secs) in sync handlers/UI, or self.show_status_message(msg, ttl_secs) in the async network layer."

♻️ Proposed change
     let summary = report.summary();
     let accepted = {
       let mut app = self.app.lock().await;
-      let accepted = app.extend_native_queue_from_dj(std::mem::take(&mut report.resolved));
-      app.set_status_message(format!("MCP: {summary}"), 5);
-      accepted
+      app.extend_native_queue_from_dj(std::mem::take(&mut report.resolved))
     };
+    self.show_status_message(format!("MCP: {summary}"), 5).await;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infra/network/dj.rs` around lines 255 - 263, Update the async network
flow around `extend_native_queue_from_dj` to remove the in-lock
`app.set_status_message` call, retain the accepted result from the locked block,
and invoke `self.show_status_message(format!("MCP: {summary}"), 5)` after the
block completes.

Source: Path instructions


877-892: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This test asserts nothing about the code it names.

non_spotify_uris_are_queued_as_is_and_radio_is_rejected never calls tracks_for_uris. It builds a Vec<String>, filters it by prefix, and asserts the filter worked. Both assertions hold for any input list. The behavior in the name is already covered by uris_that_are_not_tracks_are_reported_rather_than_fabricated and opaque_source_uris_pass_through_when_their_source_is_compiled_in.

Either call tracks_for_uris here and assert the classification, or delete the test so the suite does not report coverage it does not have.

As per coding guidelines: "Run tests with cargo test --no-default-features --features telemetry and add or adjust tests when behavior changes."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infra/network/dj.rs` around lines 877 - 892, The test
non_spotify_uris_are_queued_as_is_and_radio_is_rejected only validates local
string filtering and does not exercise tracks_for_uris. Delete this redundant
test, or rewrite it to call tracks_for_uris and assert the actual non-Spotify
pass-through and radio-rejection behavior; then run the specified cargo test
command.

Source: Coding guidelines

src/infra/mcp/protocol.rs (1)

151-166: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Remove the expect from the _meta insertion path.

or_insert_with returns the existing entry when _meta is already present. If any future caller puts a non-object under _meta, as_object_mut() returns None and this panics inside a connection task. No current caller inserts _meta, so this is not live today, but the panic is one added line away and the coding guidelines ban unwrap-style failure in non-test code.

As per coding guidelines: "Use anyhow::Result<T> and the ? operator for error propagation; do not use unwrap() in non-test code."

♻️ Proposed change
   if !era.is_legacy() {
     body.insert("resultType".to_string(), json!("complete"));
-    let meta = body
-      .entry("_meta".to_string())
-      .or_insert_with(|| json!({}))
-      .as_object_mut()
-      .expect("_meta is always inserted as an object");
-    meta.insert(META_SERVER_INFO.to_string(), server_info());
+    // Overwrite a non-object `_meta` rather than panicking on it.
+    let entry = body.entry("_meta".to_string()).or_insert_with(|| json!({}));
+    if !entry.is_object() {
+      *entry = json!({});
+    }
+    if let Some(meta) = entry.as_object_mut() {
+      meta.insert(META_SERVER_INFO.to_string(), server_info());
+    }
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infra/mcp/protocol.rs` around lines 151 - 166, Update result_response so
the _meta entry is handled without expect or other panic-based failure when
as_object_mut() returns None. Use the project’s Result-based error propagation
pattern and adjust the function’s return type/callers as needed to propagate the
conversion error while preserving existing response construction for valid
object metadata.

Source: Coding guidelines

src/infra/mcp/status.rs (1)

63-97: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

pid is displayed but never used for the staleness check it was added for.

Handshake.pid is documented in src/infra/mcp/control.rs at lines 49-51 as existing "so a relay can tell a live socket from a stale file left by a process that was killed". Nothing reads it for that purpose. This check prints it, and relay.rs ignores it. The connection check does catch a dead listener indirectly, but a port reused by an unrelated process would pass the connect and then fail the token line with a confusing message.

Either check that the pid is alive before the connection probe, or correct the field comment in control.rs so it does not promise a check that is not there.

Do you want me to add the liveness check, or open an issue to track it?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infra/mcp/status.rs` around lines 63 - 97, Implement the missing
Handshake.pid liveness validation before calling probe in the connection-check
flow. Use the existing Handshake value to verify the recorded process is alive,
report a failed connection check with the stale-control-file guidance when it is
not, and only run probe for a live process; preserve the current successful
handshake reporting.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/ci.yml:
- Around line 40-41: Update the synchronization comment near the CI feature list
to reference the actual release feature-list entries in cd.yml at lines 82 and
84, or preferably identify the corresponding release step by name so the
reference remains stable when lines change.

In `@docs/mcp-setup.md`:
- Around line 75-86: Update the configuration paths in the MCP setup guide to
use spotatui’s config-directory resolver: prefer absolute XDG_CONFIG_HOME when
set, otherwise use the platform default. Apply this consistently to the
config.yml and mcp.json examples, including the additional referenced sections,
while preserving the existing setup instructions.

In `@src/infra/mcp/control.rs`:
- Around line 37-39: Restrict the SPOTATUI_MCP_HANDSHAKE_PATH override used by
handshake_path to test builds only, ensuring release builds always derive the
path from the configured directory. Apply the same cfg(test) gating to the
related logic around the handshake-path handling and keep the test-only
documentation accurate.
- Around line 138-145: Update the accept error branch in the listener loop to
sleep briefly after logging the failure and before retrying. Preserve the
current retry behavior for transient errors, but add the delay in the Err path
to prevent persistent failures from causing a hot loop and log flood.
- Around line 111-116: Update generate_token() to obtain both u64 halves
directly from the OS CSPRNG, such as SysRng, instead of rand::random; preserve
the existing 128-bit value and 32-character lowercase hex encoding.
- Around line 180-190: Cap the pre-authentication handshake read in the control
connection flow before calling read_line, using AsyncReadExt::take on the reader
and a defined maximum handshake-line length. Reject or bail when the capped read
reaches the limit without a newline, while preserving the existing timeout, EOF,
and I/O error handling. Import tokio::io::AsyncReadExt as needed.

In `@src/infra/mcp/relay.rs`:
- Around line 258-270: Introduce one shared read-timeout constant in
src/infra/mcp/relay.rs and apply it to both upstream.reader.next_line() calls:
in forward (src/infra/mcp/relay.rs#L258-L270), map expiry to ForwardError::Sent;
in ensure_upstream’s handshake replay (src/infra/mcp/relay.rs#L229-L240), set
offline_reason on expiry instead of blocking indefinitely.
- Around line 180-196: Update the reconnect-failure branch in the surrounding
forwarding method so that when ensure_upstream() returns false, it preserves the
offline_reason set by ensure_upstream instead of overwriting it with the earlier
send error. Keep the existing retry-error handling unchanged.

In `@src/infra/mcp/server.rs`:
- Around line 167-192: Update the name extraction in the tools/call handling
before tools::parse_call so a missing or non-string name returns
proto::error_response with proto::INVALID_PARAMS and a descriptive validation
message. Only pass a present, valid name to tools::parse_call, preserving
METHOD_NOT_FOUND for genuinely unknown non-empty tool names.

In `@src/infra/network/dj.rs`:
- Around line 310-326: Update dj_play_now’s non-Spotify branch to validate the
URI with crate::core::queue::is_playable_track_uri before calling
dj_start_playback. Reject spotify album URIs, Spotify web URLs, free text, radio
streams, and other non-track inputs using the same invalid-track behavior as
tracks_for_uris, while preserving the missing_source_feature handling for valid
source-specific playable URIs.

---

Nitpick comments:
In `@docs/mcp-setup.md`:
- Around line 6-10: Add the text language tag to the opening fences for the
prompt, diagram, and status-output blocks in the documentation, including the
fences near the shown prompt and the additional blocks near lines 24 and 106,
while preserving their contents.
- Around line 63-67: Update the checkout installation command in the MCP setup
instructions to include the --locked flag, matching the existing spotatui
installation command and ensuring Cargo uses the committed dependency graph.

In `@src/infra/mcp/protocol.rs`:
- Around line 151-166: Update result_response so the _meta entry is handled
without expect or other panic-based failure when as_object_mut() returns None.
Use the project’s Result-based error propagation pattern and adjust the
function’s return type/callers as needed to propagate the conversion error while
preserving existing response construction for valid object metadata.

In `@src/infra/mcp/status.rs`:
- Around line 63-97: Implement the missing Handshake.pid liveness validation
before calling probe in the connection-check flow. Use the existing Handshake
value to verify the recorded process is alive, report a failed connection check
with the stale-control-file guidance when it is not, and only run probe for a
live process; preserve the current successful handshake reporting.

In `@src/infra/network/dj.rs`:
- Around line 255-263: Update the async network flow around
`extend_native_queue_from_dj` to remove the in-lock `app.set_status_message`
call, retain the accepted result from the locked block, and invoke
`self.show_status_message(format!("MCP: {summary}"), 5)` after the block
completes.
- Around line 877-892: The test
non_spotify_uris_are_queued_as_is_and_radio_is_rejected only validates local
string filtering and does not exercise tracks_for_uris. Delete this redundant
test, or rewrite it to call tracks_for_uris and assert the actual non-Spotify
pass-through and radio-rejection behavior; then run the specified cargo test
command.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f9650681-7a1d-4e84-a09d-69abd25a1837

📥 Commits

Reviewing files that changed from the base of the PR and between 22f531e and 98b9d27.

📒 Files selected for processing (27)
  • .github/workflows/cd.yml
  • .github/workflows/ci.yml
  • CHANGELOG.md
  • CLAUDE.md
  • Cargo.toml
  • README.md
  • docs/mcp-setup.md
  • src/cli/mcp.rs
  • src/cli/mod.rs
  • src/core/app.rs
  • src/core/queue.rs
  • src/core/user_config.rs
  • src/infra/dj/brief.rs
  • src/infra/dj/exec.rs
  • src/infra/dj/mod.rs
  • src/infra/dj/tools.rs
  • src/infra/mcp/control.rs
  • src/infra/mcp/executor.rs
  • src/infra/mcp/mod.rs
  • src/infra/mcp/protocol.rs
  • src/infra/mcp/relay.rs
  • src/infra/mcp/server.rs
  • src/infra/mcp/status.rs
  • src/infra/mod.rs
  • src/infra/network/dj.rs
  • src/infra/network/mod.rs
  • src/runtime.rs

Comment thread .github/workflows/ci.yml Resolved
Comment thread docs/mcp-setup.md Resolved
Comment thread src/infra/mcp/control.rs Resolved
Comment thread src/infra/mcp/control.rs Resolved
Comment thread src/infra/mcp/control.rs Resolved
Comment thread src/infra/mcp/control.rs Resolved
Comment thread src/infra/mcp/relay.rs Resolved
Comment thread src/infra/mcp/relay.rs Resolved
Comment thread src/infra/mcp/server.rs Resolved
Comment thread src/infra/network/dj.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/mcp-setup.md`:
- Around line 49-50: Update the initial-state expectation in the setup
instructions to document both valid failures: a binary lacking mcp-server may
report “unrecognized subcommand 'mcp'”, while a supported binary may fail at
“control-file” before setup. Clarify that either outcome is expected at this
stage.
- Around line 157-158: Add a Windows-specific alternative to the binary path
resolution guidance near the existing command -v spotatui instruction, using
standard PowerShell Get-Command spotatui or where.exe spotatui while preserving
the existing Unix guidance.

In `@src/infra/mcp/relay.rs`:
- Around line 254-277: Detect the control server’s {"error":"unauthorized"}
response before it can reach the agent or satisfy a handshake replay. Add an
is_control_rejection helper near send_line, apply it to the first upstream line
handled by forward, and reject matching handshake replay lines in the
stored-handshake branch; set offline_reason and return the existing failure
result instead of treating the line as normal JSON-RPC traffic.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 34a5371e-542a-476f-a67e-af145f70cf43

📥 Commits

Reviewing files that changed from the base of the PR and between 98b9d27 and d9f27bf.

📒 Files selected for processing (8)
  • .github/workflows/ci.yml
  • docs/mcp-setup.md
  • src/infra/mcp/control.rs
  • src/infra/mcp/protocol.rs
  • src/infra/mcp/relay.rs
  • src/infra/mcp/server.rs
  • src/infra/mcp/status.rs
  • src/infra/network/dj.rs
🚧 Files skipped from review as they are similar to previous changes (6)
  • .github/workflows/ci.yml
  • src/infra/mcp/protocol.rs
  • src/infra/mcp/control.rs
  • src/infra/mcp/status.rs
  • src/infra/network/dj.rs
  • src/infra/mcp/server.rs

Comment thread docs/mcp-setup.md Resolved
Comment thread docs/mcp-setup.md Resolved
Comment thread src/infra/mcp/relay.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
src/infra/mcp/relay.rs (1)

291-303: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Validate the handshake replay reply before setting token_checked.

At Lines 294-303, any line except {"error":"unauthorized"} marks the connection as validated. A malformed line or a JSON-RPC response with the wrong id is not proof that the replayed initialize request succeeded.

Require a JSON-RPC response whose id matches the replayed handshake. Otherwise, discard the connection and set offline_reason.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infra/mcp/relay.rs` around lines 291 - 303, Validate the replay response
in the handshake flow before setting upstream.token_checked: require a
well-formed JSON-RPC response with an id matching the replayed initialize
request, while preserving control_rejection handling. For malformed replies or
mismatched ids, discard the connection, set self.offline_reason, and return
false; only valid matching responses may mark the connection checked.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@src/infra/mcp/relay.rs`:
- Around line 291-303: Validate the replay response in the handshake flow before
setting upstream.token_checked: require a well-formed JSON-RPC response with an
id matching the replayed initialize request, while preserving control_rejection
handling. For malformed replies or mismatched ids, discard the connection, set
self.offline_reason, and return false; only valid matching responses may mark
the connection checked.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8f30793a-21c0-4bc2-b760-4c4285b17180

📥 Commits

Reviewing files that changed from the base of the PR and between d9f27bf and 05f81f7.

📒 Files selected for processing (2)
  • docs/mcp-setup.md
  • src/infra/mcp/relay.rs

Second layer of the five-PR stack splitting feat/ai-dj-mcp-server. It puts a
`spotatui mcp` stdio server in front of the dj-core tool table, so Claude Code,
Codex, or any MCP client can read the listening history, search the catalogue
and queue tracks over a loopback control socket that is off until
behavior.mcp_enabled is set.

No LLM client and no API key are compiled in, and no crate dependency is added:
the agent on the other end brings its own model. The startup logging notice
moves to stderr, because the MCP spec allows nothing but protocol messages on
stdout.
The two that matter are both pre-authentication: the handshake read was
bounded in time but not in size, so any local process could open a
connection and grow a String for five seconds without presenting a token,
and an accept error retried with no delay, so a persistent one (EMFILE)
would spin a core for the life of the process. Alongside those, no read on
the relay's upstream socket had a deadline, which let a stopped spotatui
take an agent's whole MCP session down with it.

The handshake-path override is now compiled in only under cfg(test), so no
inherited environment can move the token file out of the directory whose
permissions protect it. The token itself comes from SysRng rather than the
thread RNG, which is what its comment always claimed.

play_now was reported as accepting non-playable URIs. It does not:
tools::parse_call gates them at parse time and is the only producer of
DjToolCall::PlayNow. Pinned with a test rather than re-checked in the lane.
The control channel answers a good token with silence and a bad one with a
single non-MCP line, so nothing told the two apart until the socket first
spoke. With no handshake to replay, that line came back as the response to
whatever request was in flight and reached the agent under an id it was
still waiting on. With one, the replay read took it for a valid handshake
answer and marked a socket the server had already hung up on as healthy.

A stale control file gets there: the token rotates on every restart.
Checked once per connection rather than on every line, and reported as
Unsent, since the refusal happens before the server reads anything.

Also two setup-doc corrections: `spotatui mcp status` has two normal
starting failures, not one, and `command -v` is not a PowerShell command.
Rejecting the unauthorized line was only half of it. Every other line still
marked the socket healthy, including one from a process that is not
spotatui at all. That is reachable: shutdown unpublishes the control file
but a crash does not, so the port in it can belong to anything by the time
the next relay reads it, and the agent would then be handed that process's
output as a JSON-RPC response.

The reply now has to be a well-formed response carrying the replayed
request's own id. Left as it is on the forward path, where the line is the
answer to the agent's own request and the agent validates it; the replay is
the one the relay reads for itself, so nothing else would catch it.
@LargeModGames
LargeModGames merged commit e68a00c into main Aug 8, 2026
19 checks passed
@LargeModGames
LargeModGames deleted the dj/mcp-server branch August 8, 2026 09:55
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