Repository navigation
feat(mcp): load code tools from modules named in the config - #761
Merged
Merged
Conversation
This was referenced Oct 20, 2026
vishal-bala
marked this pull request as ready for review
October 27, 2026 13:47
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
limjoobin
approved these changes
Oct 30, 2026
Base automatically changed from
feat/mcp-code-tools/03-server-code-tool
to
main
October 30, 2026 15:18
vishal-bala
added a commit
that referenced
this pull request
Oct 30, 2026
## Motivation
This PR makes code tools usable from a server started in the caller's
own Python process. It builds on the tool wrapper from the previous PR:
```python
from redisvl.mcp import MCPSettings, RedisVLMCPServer, ToolContext
from redisvl.query import CountQuery
from redisvl.query.filter import Tag
server = RedisVLMCPServer(MCPSettings(config="/path/to/mcp_config.yaml"))
@server.code_tool(index="tickets")
async def count_open_tickets(ctx: ToolContext, product: str) -> dict:
"""Count open support tickets for a product."""
open_for_product = (Tag("status") == "open") & (Tag("product") == product)
return {"open": await ctx.index.query(CountQuery(open_for_product))}
```
The model sees `count-open-tickets`, taking `product`, and never the
context or the index.
## Changes
### Registration
`server.code_tool(...)` checks the function at decoration and returns it
unchanged. Registering after the first startup raises `RuntimeError`,
because tools register once per process. Code tools register after
profiles.
The method is named `code_tool` rather than `custom_tool`, which the
proposal used. `custom_tools:` already means profiles in the config, and
every message and setting calls these code tools.
### Startup checks
Each tool is paired with its binding once the config is loaded, before
any binding connects. Startup fails, naming the tool, when:
| Refused when | Why |
|---|---|
| `index` is missing with several bindings, or names no binding | The
model never chooses a code tool's index, so it must be settled in
advance. |
| The name is already used by a profile or another code tool | Built-in
and reserved names are already refused at decoration. |
| The tool writes, and the server or the binding is read-only | It would
fail on every call it exists for. The message says which of the two is
read-only. |
| The tool's binding is over a Redis index that a profile scopes with
`lock.inject` | A code tool can run any query its handle allows, so
nothing shows that it applies the tenant scope. Bindings are grouped by
`redis_name`, so a sibling binding over the same documents counts. |
The last check extends `_verify_no_unscoped_route_to_injected_indexes`
rather than duplicating its grouping, so the error lists a code tool
alongside any other unscoped route.
A restart that would pair the registered code tools with different
bindings now fails, rather than taking the warning path other
tool-surface changes take. The old pairing would stay live, and for
operator code that is not something a log line should report.
### Docs and exports
`ToolContext`, `IndexHandle` and `WritableIndexHandle` are exported from
`redisvl.mcp`; the guide shows the `cast` a type checker needs to see a
writing tool's methods. The concepts page gains a Code Tools section
covering what the context exposes and withholds, the rails applied to
every call, and what fails at startup. The how-to guide gains "Code
Tools Registered From Python", with a read tool and a guarded delete,
plus a troubleshooting entry. The tool-surface and tenant-scoping
sections now mention code tools, and a line saying custom tools never
involve Python now says that of profiles specifically.
## Notes
Integration tests run against Redis 8:
- a writing tool loads through its handle;
- startup refuses a code tool on a tenant-scoped index;
- two concurrent calls of a tool that queries twice finish under a
concurrency cap of one. That would deadlock if the cap were held across
the tool's whole body.
A failed `ctx.index.load` reaches the client as a non-retryable
`internal_error`, even for a lost connection, because
`AsyncSearchIndex.load` wraps every error in `RedisVLError`. The
built-in `upsert-records` behaves the same way, so the docs state it
rather than this PR changing the error mapping; that change belongs in
its own PR, for both tools.
## Release Notes
Register an async Python function as an MCP tool with
`server.code_tool(...)` when you run the server from your own process.
It reaches Redis only through a `ToolContext` whose handle stays inside
the bound index, bounds every call, and offers writes only to tools
declared with `writes=True`.
## Next Steps
The final PR in the stack lets `rvl mcp` load code tools from modules
named in the config, behind an explicit opt-in.
## Reviewer Brief
**Start here:** `redisvl/mcp/server.py:457`, `_resolve_code_tools`. It
pairs each code tool with a binding once the config is loaded, and every
startup refusal for code tools happens there or in the injection check
it feeds.
**Where it could fail**
- `redisvl/mcp/server.py:503`: a code tool on any binding over a
`redis_name` that a profile scopes with `lock.inject` must be refused,
sibling bindings included; aliases and overlapping, empty or
separator-only prefixes are outside this check by design.
- `redisvl/mcp/server.py:645`: a restart compares the new pairing with
the recorded one; an unchanged config must compare equal, or every
restart of a server with code tools fails.
- `redisvl/mcp/server.py:260`: registration must be refused once startup
has begun, or a tool added while bindings connect is silently left out.
**Not verified:** FastMCP 2.x; an in-process restart against a live
Redis, which only the unit tests exercise.
**Beyond CI:** the guide's writing-tool example passes mypy as
published; a mutant that stops recording the pairing fails the restart
test; the Sphinx build at the #761 head adds no warnings to these pages.
<sub>Reviewed `09f1886`, fixes in `87e692f` · Claude Code
(claude-opus-5-5) · lenses: correctness, security, design, tests, docs,
Redis behaviour</sub>
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes MCP tool surface and tenant-isolation startup rules;
misconfiguration is fail-closed, but code tools still run operator
Python with process privileges behind a bounded handle.
>
> **Overview**
> Adds **code tools**: async Python functions you register with
**`@server.code_tool(...)`** before starting a server from your own
process, for logic YAML profiles cannot express.
>
> **Registration and lifecycle:** The decorator validates the function
at decoration time and registers tools once at first startup (after
profiles). Registering during or after startup is rejected. An
in-process restart that changes which code tools exist or which index
they bind to now **fails with `RuntimeError`** instead of silently
keeping the old pairing.
>
> **Startup policy:** Each tool is resolved to a binding (required when
multiple indexes exist), checked for name clashes with profiles, and
refused if **`writes=True`** on a read-only server or binding.
Tenant-scoped indexes with **`lock.inject`** also refuse any code tool
on that Redis index, extending the existing “no unscoped route” check
because the server cannot prove operator code applies the tenant filter.
>
> **Public API:** **`ToolContext`**, **`IndexHandle`**, and
**`WritableIndexHandle`** are exported from **`redisvl.mcp`**. Docs add
a Code Tools section (concepts + how-to) and troubleshooting, and
tenant-scoping text now mentions code tools as alternate routes to the
same data.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d6e71eb. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
vishal-bala
force-pushed
the
feat/mcp-code-tools/04-module-loader
branch
from
October 30, 2026 15:22
8a22c82 to
927124e
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
server.code_tool(...)from the previous PR only helps when the caller's own code constructs the server. The common deployment isrvl mcp --config, which imports no user code. This PR lets the config name modules for the server to import. Because importing a module runs its code with the server's privileges, nothing is imported unless the operator opts in separately.Changes
@code_tool(...), exported fromredisvl.mcp, takes the same arguments asserver.code_tool. It checks the function and attaches its spec as an attribute, without registering it anywhere:At startup, the server imports each listed module before any binding connects. Every function marked with
@code_toolis validated and registered alongside tools fromserver.code_tool, under the same startup checks.Startup refuses, naming the module or setting:
code_tool_modulesis set withoutallow_code_tools: true(defaultfalse)@code_toolfunction@code_toolfunctools.wrapscopies the marker while the spec still calls the inner function, so the outer decorator would silently never run.The marker lives on the function, not in a module-level registry. Importing a module therefore registers nothing anywhere, and two servers in one process stay independent, as do tests that import a tool module. The loader considers only functions and reads the marker from each function's own
__dict__, so a module attribute with a permissive__getattr__, such as a lazy module proxy, is never consulted. A tool one listed module re-exports from another registers once.The docs gain "Code Tools Loaded From Modules" and a troubleshooting entry. They state that
rvldoes not put the working directory on the import path: modules must be installed or onPYTHONPATH, and underuvxinstalled in the environment it builds.Notes
The loader does not edit
sys.path. Adding the config's directory would make import resolution depend on where the config file happens to live.I verified the end-to-end flow manually with
rvl mcp --transport streamable-http, a scratch module onPYTHONPATHand the server started from outside the project directory. A FastMCP client listedsupport-count-open-ticketswith onlyproductin its schema, and a call returned the expected count.Release Notes
rvl mcpcan load code tools from Python modules. Mark async functions with@code_toolfromredisvl.mcp, list their modules underserver.code_tool_modules, and setserver.allow_code_tools: true, which defaults tofalsebecause importing a module runs its code with the server's privileges. Modules must be importable by the server process.Next Steps
code_toolnames, noctx.guarded(the handle applies the limits itself), id-only writes and no filter-wide bulk writes, no code tools on tenant-scoped indexes, async tools only, and the whole-call timeout.Reviewer Brief
Start here:
redisvl/mcp/tools/code.py:269,load_code_tools. It imports the modules a config names, so it is where configuration becomes running code.Where it could fail
redisvl/mcp/config.py:266:allow_code_toolsis the only gate on importing operator code; check no settings or environment path can setcode_tool_modulesaround it.redisvl/mcp/tools/code.py:269: the loader reads the@code_toolmarker from each function's own__dict__and refuses a decorator wrapped over it; check a tool re-exported from a second module registers once.Not verified: importing modules under
uvx, which the guide's advice rests on reasoning about howuvxbuilds its environment; FastMCP 2.x.Since the last brief:
927124erebases the PR ontomainas one commit after #758, #759 and #760 were squash-merged; the code is unchanged from the reviewed head plus its fixes.Reviewed
6ff481b, fixes incc9249f· Claude Code (claude-opus-5-5) · lenses: correctness, security, design, tests, docs, Redis behaviourNote
Medium Risk
When
allow_code_toolsis enabled, listed modules run with the MCP server process privileges at import time; misconfiguration or untrusted modules are the main exposure, though defaults stay off and config validation fails closed on bad entries.Overview
rvl mcp --configcan now register custom code tools without constructingRedisVLMCPServerin Python. Add@code_tool(exported fromredisvl.mcp, same options asserver.code_tool) on async functions; list modules underserver.code_tool_modulesand setserver.allow_code_tools: true(defaultsfalse).At startup—before any Redis binding connects—the server imports each listed module via
load_code_tools, collects functions marked with__redisvl_mcp_tool__, and registers them through the same validation path as tools added withserver.code_tool(name collisions, index binding, read-only/write rules, tenantlock.injectroutes). Config load rejectscode_tool_moduleswithout the opt-in, duplicate or blank module names, failed imports, modules with no@code_toolfunctions, and decorators wrapped outside@code_tool.Docs add module-based registration,
PYTHONPATH/uvximport notes, and troubleshooting for module load failures.Reviewed by Cursor Bugbot for commit 927124e. Bugbot is set up for automated code reviews on this repo. Configure here.