Repository navigation
feat(wren): serve project capabilities over MCP - #2438
Conversation
Add `wren serve mcp`, an in-process MCP server that exposes a Wren project's query, semantic-model, and business-knowledge tools to MCP clients (Claude Desktop/Code, IDEs) with no ibis-server or separate backend — it drives the same in-process WrenEngine the CLI uses. - 14 tools — query: run_sql/dry_run/dry_plan/query_cube; schema: get_mdl/list_models/describe_model/get_data_source/list_cubes/ describe_cube/list_functions; knowledge: get_instructions/ recall_queries/store_query - 3 resources (wren://mdl, wren://instructions, wren://project) and a wren_workflow prompt - stdio (default) and streamable-http transports; --allow-write gates store_query; --no-connect yields a transpile-only server - checks target/mdl.json freshness at startup (warns, never auto-builds) - new optional `mcp` extra (mcp[cli]); docs guide + CLI reference Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughAdds an in-process MCP server for Wren, wires it into ChangesMCP Server Feature
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant ServeCLI
participant WrenEngine
participant mcp_server
User->>ServeCLI: wren serve mcp
ServeCLI->>ServeCLI: resolve project and validate target/mdl.json
ServeCLI->>ServeCLI: build connection_info from --profile
ServeCLI->>WrenEngine: construct engine from MDL and connection info
ServeCLI->>mcp_server: run_server(ServeContext, transport, host, port)
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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 |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
core/wren/src/wren/serve_cli.py (1)
46-51: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winGuard non-loopback HTTP binds
serve_mcp(..., transport="http")startsstreamable-httpwithout any auth settings here, so--host 0.0.0.0exposes the query tools — andstore_querywhen--allow-writeis set — on the network. Warn on non-loopback hosts or document that HTTP mode must sit behind an authenticating proxy.🤖 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 `@core/wren/src/wren/serve_cli.py` around lines 46 - 51, The HTTP serve path in serve_mcp is currently allowed to bind to non-loopback hosts without any auth, which can expose query tools and store_query when allow_write is enabled. Update the serve_cli option handling and the serve_mcp transport="http" flow to either warn/block non-loopback hosts like 0.0.0.0 by default or clearly require an authenticating proxy before exposing streamable-http. Use the serve_mcp and serve_cli host/transport options to locate the behavior and keep the guidance consistent for --host and --allow-write.core/wren/src/wren/mcp_server.py (2)
104-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReaching into a private helper across module boundaries.
_build_cube_queryis imported fromwren.cube_cliwith a leading underscore, signaling it's intended as an internal implementation detail of the cube CLI, not a stable cross-module API. If its signature or behavior changes to suit CLI-only needs, this MCP tool breaks silently.Consider extracting the shared cube-query-building logic into a public helper (e.g., in a shared module) that both
cube_cli.pyandmcp_server.pycall, rather than importing a private symbol.🤖 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 `@core/wren/src/wren/mcp_server.py` around lines 104 - 123, The query construction in mcp_server.py is depending on the private helper _build_cube_query from wren.cube_cli, which should not be used as a cross-module API. Move the shared cube-query-building logic into a public helper in a shared module, then update both _build_cube_query usage in cube_cli and the query_cube flow in mcp_server.py to call that public function instead of importing the underscored symbol.
433-452: 🔒 Security & Privacy | 🔵 TrivialStreamable-HTTP transport has no authentication and shares a single engine instance across requests.
Two things worth confirming before this ships:
host/portare caller-configurable (perserve_cli.py), and there's no visible auth/token check beforemcp.run(transport="streamable-http"). Defaulting to127.0.0.1mitigates exposure, but if a user points--hostat0.0.0.0(e.g., to reach it from a container or another machine),run_sql/store_querybecome network-reachable with no authentication, exposing arbitrary SQL execution and writes.ctx.engine(built once inserve_cli.py) is shared across every concurrent tool invocation under HTTP. If the underlying connector isn't safe for concurrent use (e.g., a single DuckDB connection), simultaneousrun_sql/query_cubecalls from multiple MCP clients could race or produce corrupted results.Please confirm FastMCP's streamable-http transport offers an auth hook that should be documented/enabled for non-local deployments, and that the connector layer tolerates concurrent
query/dry_runcalls.🤖 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 `@core/wren/src/wren/mcp_server.py` around lines 433 - 452, The streamable-HTTP path in run_server currently exposes the FastMCP server without any visible auth gate and reuses the single ctx.engine across all HTTP requests. Please either add/document the supported FastMCP auth/token hook before mcp.run(transport="streamable-http") or restrict non-local binds, and confirm the server is safe when host is set beyond 127.0.0.1. Also verify the connector used by build_server/ctx.engine is concurrency-safe for simultaneous tool calls like run_sql, store_query, and query_cube; if not, serialize access or create per-request/per-session engine instances.
🤖 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 `@core/wren/.claude/CLAUDE.md`:
- Line 35: The MCP dependency name in the CLAUDE docs is inconsistent with the
rest of the project. Update the `wren serve mcp` entry in `CLAUDE.md` to use
`wrenai[mcp]` instead of `wren[mcp]`, matching the terminology used by the CLI
error text and other documentation references.
In `@core/wren/src/wren/mcp_server.py`:
- Line 45: The truncation check in the MCP server result path is too coarse and
can mark exact-limit results as truncated. Update the logic around the row
retrieval flow in the MCP server to fetch one extra row when a limit is
requested, then trim back to the requested size and set the truncated flag only
if the extra row was actually returned. Use the existing symbols around the
`truncated` calculation and the row-count handling in `mcp_server.py` to keep
the change localized.
- Around line 60-70: The run_sql tool currently accepts a format argument but
ignores it, so callers get the same dict output regardless of the requested
value. Update run_sql in mcp_server.py to either branch on format and return the
appropriate representation (for example, JSON vs CSV) using the existing
ctx.engine.query and _table_to_result flow, or remove the unused format
parameter from the function signature and any related tool schema so the
declared interface matches behavior.
- Around line 319-357: The indexing call in store_query should be fully
best-effort so a successful markdown save is not turned into a failed tool call.
Update the MemoryStore.store_query() path inside
_register_write_tools().store_query() to catch and swallow any runtime
exceptions from indexing, not just ModuleNotFoundError, while still returning
{"path": str(md_path)}. If possible, log the indexing failure for visibility,
but do not let it escape after write_query_markdown() succeeds.
- Around line 34-51: Normalize the rows returned by _table_to_result before they
reach FastMCP, because to_pandas().to_dict(orient="records") can still leave
non-JSON-native values like Timestamp, Decimal, bytes, or numpy scalars that
break transport serialization. Update _table_to_result to explicitly convert
each cell to JSON-safe types in both the pandas path and the pydict fallback,
and avoid a blanket except Exception by catching the conversion failure more
narrowly while preserving a safe fallback path.
---
Nitpick comments:
In `@core/wren/src/wren/mcp_server.py`:
- Around line 104-123: The query construction in mcp_server.py is depending on
the private helper _build_cube_query from wren.cube_cli, which should not be
used as a cross-module API. Move the shared cube-query-building logic into a
public helper in a shared module, then update both _build_cube_query usage in
cube_cli and the query_cube flow in mcp_server.py to call that public function
instead of importing the underscored symbol.
- Around line 433-452: The streamable-HTTP path in run_server currently exposes
the FastMCP server without any visible auth gate and reuses the single
ctx.engine across all HTTP requests. Please either add/document the supported
FastMCP auth/token hook before mcp.run(transport="streamable-http") or restrict
non-local binds, and confirm the server is safe when host is set beyond
127.0.0.1. Also verify the connector used by build_server/ctx.engine is
concurrency-safe for simultaneous tool calls like run_sql, store_query, and
query_cube; if not, serialize access or create per-request/per-session engine
instances.
In `@core/wren/src/wren/serve_cli.py`:
- Around line 46-51: The HTTP serve path in serve_mcp is currently allowed to
bind to non-loopback hosts without any auth, which can expose query tools and
store_query when allow_write is enabled. Update the serve_cli option handling
and the serve_mcp transport="http" flow to either warn/block non-loopback hosts
like 0.0.0.0 by default or clearly require an authenticating proxy before
exposing streamable-http. Use the serve_mcp and serve_cli host/transport options
to locate the behavior and keep the guidance consistent for --host and
--allow-write.
🪄 Autofix (Beta)
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: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 213f97df-c4bd-4e7c-a34e-b8e4bd7787a3
⛔ Files ignored due to path filters (1)
core/wren/uv.lockis excluded by!**/*.lock
📒 Files selected for processing (8)
core/wren/.claude/CLAUDE.mdcore/wren/README.mdcore/wren/pyproject.tomlcore/wren/src/wren/cli.pycore/wren/src/wren/mcp_server.pycore/wren/src/wren/serve_cli.pydocs/core/guides/mcp.mddocs/core/reference/cli.md
- normalize run_sql/query_cube rows to JSON-native types (datetime→iso, Decimal→float, bytes→str, numpy scalars, NaN/inf→null) via to_pylist, and stop swallowing conversion errors - fix truncated false-positive with a limit+1 probe (exact-fit no longer reports truncation) - drop the unused run_sql `format` parameter - make store_query's LanceDB indexing truly best-effort (log + continue after the markdown source-of-truth is written) - docs: correct extra name to wrenai[mcp] Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
core/wren/src/wren/mcp_server.py (1)
531-541: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winHandle config parse failures as regular errors
core/wren/src/wren/mcp_server.py:531-539—schema_version/knowledge_schema_versionstill raiseSystemExithere, and FastMCP only normalizesExceptions. That bypasses the MCP error path and can take down the long-lived server. Catch these in the resource handler and return a normal resource error instead.🤖 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 `@core/wren/src/wren/mcp_server.py` around lines 531 - 541, The resource handler in mcp_server.py is still calling get_schema_version and get_knowledge_schema_version directly, so any parse failure can raise SystemExit and bypass FastMCP’s normal error handling. Update the handler that builds the JSON response after load_project_config(ctx.project) to catch these failures as regular exceptions and return a normal resource error instead, keeping the logic localized in the same resource method.
🧹 Nitpick comments (1)
core/wren/src/wren/mcp_server.py (1)
415-444: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNarrow the fallback to import/availability failures.
except Exceptionhere also swallows genuineMemoryStoreruntime errors (corrupt index, LanceDB I/O, embedding failures) and silently returns the markdown view, masking real configuration problems. This contradicts the deliberate design inget_context(Lines 376-378), which only catchesImportErrorso that real store errors surface. Consider catchingImportError(missingmemoryextra) here as well and letting other exceptions propagate.♻️ Suggested change
- try: + try: from wren.memory.cli import _default_memory_path # noqa: PLC0415 from wren.memory.store import MemoryStore # noqa: PLC0415 store = MemoryStore(path=str(_default_memory_path())) rows, _total = store.list_queries( source=source, limit=limit if limit is not None else MAX_ROW_LIMIT, ) return {"queries": [_normalize_value(row) for row in rows]} - except Exception: + except ImportError: from wren.memory.markdown import load_query_pairs # noqa: PLC0415🤖 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 `@core/wren/src/wren/mcp_server.py` around lines 415 - 444, The fallback in the query-loading path is too broad because `except Exception` in the `MemoryStore` block hides real runtime failures and always falls back to markdown. Narrow this in `wren/mcp_server.py` by catching only `ImportError` around the `_default_memory_path`, `MemoryStore`, or `load_query_pairs` imports, and let non-import errors from `MemoryStore.list_queries` propagate like `get_context` does.
🤖 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.
Outside diff comments:
In `@core/wren/src/wren/mcp_server.py`:
- Around line 531-541: The resource handler in mcp_server.py is still calling
get_schema_version and get_knowledge_schema_version directly, so any parse
failure can raise SystemExit and bypass FastMCP’s normal error handling. Update
the handler that builds the JSON response after load_project_config(ctx.project)
to catch these failures as regular exceptions and return a normal resource error
instead, keeping the logic localized in the same resource method.
---
Nitpick comments:
In `@core/wren/src/wren/mcp_server.py`:
- Around line 415-444: The fallback in the query-loading path is too broad
because `except Exception` in the `MemoryStore` block hides real runtime
failures and always falls back to markdown. Narrow this in `wren/mcp_server.py`
by catching only `ImportError` around the `_default_memory_path`, `MemoryStore`,
or `load_query_pairs` imports, and let non-import errors from
`MemoryStore.list_queries` propagate like `get_context` does.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: a380c9e3-3f39-4da0-8b46-8c68409f02f8
📒 Files selected for processing (3)
core/wren/src/wren/mcp_server.pydocs/core/guides/mcp.mddocs/core/reference/cli.md
✅ Files skipped from review due to trivial changes (2)
- docs/core/guides/mcp.md
- docs/core/reference/cli.md
On `wren serve mcp` startup, print (to stderr) ready-to-copy commands to register the server with a client, tailored to the invocation: - http: `claude mcp add --transport http` / `codex mcp add --url` plus an MCP Inspector hint, with the actual URL - stdio: those `claude`/`codex` add commands plus a JSON `mcpServers` config block, reflecting --project/--profile/--allow-write and WREN_HOME Add `--quiet`/`-q` to suppress. stderr is used so stdio's stdout MCP channel stays clean. Docs updated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
core/wren/src/wren/serve_cli.py (1)
44-115: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider unit tests for
_serve_args/_print_connection_help.Both are pure/deterministic functions producing user-facing text that's easy to silently regress (flag ordering, quoting, JSON shape). Worth covering with focused tests given they're on the "first thing a user copies" path.
🤖 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 `@core/wren/src/wren/serve_cli.py` around lines 44 - 115, Add focused unit tests for _serve_args and _print_connection_help to lock down their deterministic output. Cover the exact argument ordering and optional flags returned by _serve_args, and verify _print_connection_help’s stderr text for both transport branches, including the generated command strings, WREN_HOME handling, and the JSON config shape built from _serve_args and the server mapping.
🤖 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 `@core/wren/src/wren/serve_cli.py`:
- Around line 81-84: The Streamable HTTP URL shown by serve_cli should not
display the wildcard bind host when host is 0.0.0.0, because that is not a
usable client target. Update the URL construction in the transport == "http"
branch to detect wildcard hosts and substitute a loopback address for display
only, while leaving the actual bind behavior unchanged; use the serve_cli
host/port URL echo logic as the place to adjust this.
- Around line 73-104: Quote the copy-pasteable stdio registration commands in
serve_cli.py so paths and env values with spaces do not break; update the branch
that builds the Claude Code and Codex snippets to shell-quote argline, env_flag,
and wren_cmd before interpolation. While you’re in the same echo block,
sanity-check the wren_cmd fallback from sys.argv[0] in the stdio path so the
generated command remains re-runnable when wren is invoked via python -m wren.
---
Nitpick comments:
In `@core/wren/src/wren/serve_cli.py`:
- Around line 44-115: Add focused unit tests for _serve_args and
_print_connection_help to lock down their deterministic output. Cover the exact
argument ordering and optional flags returned by _serve_args, and verify
_print_connection_help’s stderr text for both transport branches, including the
generated command strings, WREN_HOME handling, and the JSON config shape built
from _serve_args and the server mapping.
🪄 Autofix (Beta)
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: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 8343a0ed-52db-4412-a36d-43a16b51a450
📒 Files selected for processing (3)
core/wren/src/wren/serve_cli.pydocs/core/guides/mcp.mddocs/core/reference/cli.md
✅ Files skipped from review due to trivial changes (1)
- docs/core/guides/mcp.md
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/core/reference/cli.md
Address review feedback on the startup registration banner: - shell-quote wren path, args, and WREN_HOME (shlex.quote) so the copy-paste claude/codex commands survive paths containing spaces - display a loopback URL when bound to a wildcard host (0.0.0.0/::), which isn't a connectable client target Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
What
Adds
wren serve mcp— an in-process MCP server that exposes a Wren project's query, semantic-model, and business-knowledge tools to MCP clients (Claude Desktop/Code, Cursor, IDEs). It drives the same in-processWrenEnginethe CLI already uses, so it needs no ibis-server and no separate service — just the CLI installed in a project directory.Run it from inside a wren project:
Surface
run_sql,dry_run,dry_plan,query_cubeget_mdl,list_models,describe_model,get_data_source,list_cubes,describe_cube,list_functionsget_instructions,recall_queries,store_querywren://mdl,wren://instructions,wren://projectwren_workflow(schema → instructions → recall → dry-run → run → cube → store SOP)Behavior / flags
--transport stdio|http(defaultstdio),--host/--port(http, binds127.0.0.1)--project,--profile--allow-writegatesstore_query(server is read-only otherwise)--no-connectyields a transpile-only server (disablesrun_sql/dry_run/query_cube)wren context build; checkstarget/mdl.jsonfreshness at startup and warns if stale (never auto-builds)Packaging
New optional extra
mcp = ["mcp[cli]>=1.19"](folded intoall); the SDK is lazy-imported inside the command so the CLI degrades cleanly when the extra is absent (pip install 'wrenai[mcp]').Docs
docs/core/guides/mcp.mdwren servesection indocs/core/reference/cli.mdcore/wren/.claude/CLAUDE.mdcommand listTesting
ruff format --check+ruff checkclean on new/changed filesorder_metricscube: all 14 tools, 3 resources, and the prompt verified returning correct resultsNotes for reviewers
core/wren/src/wren/serve_cli.py(Typerservegroup),core/wren/src/wren/mcp_server.py(FastMCP app).{"models": [...]}etc.) for a single clean JSON block.Summary by CodeRabbit
wren serve mcpto expose Wren project query, schema, and knowledge capabilities via an MCP server.--allow-writeto enable storing query examples and--no-connectfor connection-free operation.target/mdl.json), tool/resource coverage, and client registration examples.