Repository navigation
feat(mcp): spotatui mcp, the MCP server front door on dj-core - #429
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe PR adds an opt-in ChangesMCP server integration
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
✨ Simplify code
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. Comment |
cee6984 to
d8a66bb
Compare
d8a66bb to
98b9d27
Compare
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (6)
docs/mcp-setup.md (2)
6-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd language tags to the fenced blocks.
markdownlint-cli2reports MD040 for the prompt, diagram, and status-output fences. Addtextto 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 winKeep local-checkout installation locked.
Cargo.lockexists for this project, so add--lockedto 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 winUse the network-layer status-message helper, and set it outside the locked block.
Line 261 writes the status message through
app.set_status_messagewhile theApplock is held inside this block. The path instruction requiresself.show_status_message(msg, ttl_secs)in the async network layer.show_status_messagetakes theApplock 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_messagedirectly:app.set_status_message(msg, ttl_secs)in sync handlers/UI, orself.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 winThis test asserts nothing about the code it names.
non_spotify_uris_are_queued_as_is_and_radio_is_rejectednever callstracks_for_uris. It builds aVec<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 byuris_that_are_not_tracks_are_reported_rather_than_fabricatedandopaque_source_uris_pass_through_when_their_source_is_compiled_in.Either call
tracks_for_urishere 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 telemetryand 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 winRemove the
expectfrom the_metainsertion path.
or_insert_withreturns the existing entry when_metais already present. If any future caller puts a non-object under_meta,as_object_mut()returnsNoneand 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 banunwrap-style failure in non-test code.As per coding guidelines: "Use
anyhow::Result<T>and the?operator for error propagation; do not useunwrap()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
pidis displayed but never used for the staleness check it was added for.
Handshake.pidis documented insrc/infra/mcp/control.rsat 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, andrelay.rsignores 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.rsso 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
📒 Files selected for processing (27)
.github/workflows/cd.yml.github/workflows/ci.ymlCHANGELOG.mdCLAUDE.mdCargo.tomlREADME.mddocs/mcp-setup.mdsrc/cli/mcp.rssrc/cli/mod.rssrc/core/app.rssrc/core/queue.rssrc/core/user_config.rssrc/infra/dj/brief.rssrc/infra/dj/exec.rssrc/infra/dj/mod.rssrc/infra/dj/tools.rssrc/infra/mcp/control.rssrc/infra/mcp/executor.rssrc/infra/mcp/mod.rssrc/infra/mcp/protocol.rssrc/infra/mcp/relay.rssrc/infra/mcp/server.rssrc/infra/mcp/status.rssrc/infra/mod.rssrc/infra/network/dj.rssrc/infra/network/mod.rssrc/runtime.rs
98b9d27 to
d9f27bf
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
.github/workflows/ci.ymldocs/mcp-setup.mdsrc/infra/mcp/control.rssrc/infra/mcp/protocol.rssrc/infra/mcp/relay.rssrc/infra/mcp/server.rssrc/infra/mcp/status.rssrc/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
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/infra/mcp/relay.rs (1)
291-303: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winValidate 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 wrongidis not proof that the replayedinitializerequest succeeded.Require a JSON-RPC response whose
idmatches the replayed handshake. Otherwise, discard the connection and setoffline_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
📒 Files selected for processing (2)
docs/mcp-setup.mdsrc/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.
538208e to
bf919a1
Compare
Summary
PR 2 of the stack. Part of #196.
Puts a
spotatui mcpstdio server in front of the dj-core tool table, soClaude 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.
behavior.mcp_enabled: trueturns it on, and the controlsocket binds loopback-only behind a token in
~/.config/spotatui/mcp.jsonanswers
initializefor the clients shipping todaysearch_tracksmarks every result owned or new;queue_trackstakesexclude_owned: truefor agents that want the guarantee, reports what itskipped, and substitutes nothing
docs/mcp-setup.mdis written as instructions for an agent to follow, withspotatui mcp statusas a safe, machine-checkable probe of each stepLogging to:startup notice moves to stderr, since the MCP spec allowsnothing but protocol messages on stdout
Testing
telemetry,mcp-server / all-sources minus audio-viz
(670 passed, including 47 MCP protocol/relay/control tests)
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
spotatui mcpandmcp status, including machine-readable status reports.Documentation
Bug Fixes