[PORT] MCP tool filtering + name-prefixing (Py→TS)
⚠️ Filed by Strandly as part of the #2498 parity audit. Source feature verified merged + unit-tested + integ-tested + documented in
strands-py. Agent-produced — confirm scope before implementing. (Add theportlabel — I can't apply it via API.)
Parent: #2498
Source SDK
strands-py
Target SDK
strands-ts
Related Files
strands-py/src/strands/tools/mcp/mcp_client.py
strands-py/tests/strands/tools/mcp/test_mcp_client_tool_provider.py
strands-py/tests/strands/tools/mcp/test_mcp_client_load_servers.py
strands-py/tests_integ/mcp/test_mcp_tool_provider.py
site/src/content/docs/user-guide/concepts/tools/mcp-tools.mdx
What needs to be migrated
Python's MCP client filters/prefixes tools when listing; TS McpClient (strands-ts/src/mcp/client.ts) has neither.
- Types (
mcp_client.py):_ToolFilterCallbackProtocol (:68),_ToolMatcher = str | Pattern[str] | callback(:72),ToolFilters(TypedDict, total=False)withallowed/rejected(:75). - Constructor opts:
tool_filters(:210),prefix(:211). - Application in
list_tools_sync(pagination_token=None, prefix=None, tool_filters=None)(:536): three-state override (explicit arg incl.""/{}overrides ctor default;None= use default,:561); prefix buildsname_override=f"{prefix}_{tool.name}"(:580); filter via_should_include_tool_with_filters(:588). - Filter semantics:
_should_include_tool_with_filters(:1143) — allowed-then-rejected, rejected wins;_matches_patterns(:1160) — callable→call;Pattern→.match(anchored-at-start!);str→exact eq; all match the server-side UNPREFIXED name (tool.mcp_tool.name). - Config-file:
MCPServerConfigcarriesprefix/tool_filters(:109);_parse_config_tool_filters(:1481),_compile_filter_patterns(:1498, raisesValueErroron bad regex).
TypeScript landing points
strands-ts/src/mcp/client.ts: addprefix?/toolFilters?toMcpClientOptions(:79-102), store in ctor (:159), apply inlistTools()(:318-346) after constructing eachMcpTool(:329), before pushing; update_registeredToolNames(:344) with effective (prefixed) names.- Config path: extend
McpServerConfig(mcp/config.ts:10-33), compile inconfig.node.ts. - Agent integration transparent (filter/prefix inside
listTools()); ensureonToolsChangedrefresh (agent.ts:781) applies the same.
Gotchas / open questions
re.Pattern.matchis start-anchored; JSRegExp.testis unanchored. Prepend^(or use anchored logic) or filtering diverges. Biggest correctness trap.- Match the UNPREFIXED name; only the registered name gets prefixed — preserve ordering.
- Three-state override (
Nonevs explicit{}/""):undefined=default, but callers passing''/{}must still override — decide whetherlistTools()gains optional params (matchinglist_tools_sync) or ctor-only. API-shape decision. str | RegExp | (tool)=>booleanunion;TypedDict total=False→ interface with optional fields; bad-regexValueError→ clearSyntaxErrorwrap.
Completeness of source (strands-py)
- Merged: ✅ · Unit tests: ✅ (str/regex/callable allowed+rejected + prefix rename in
test_mcp_client_tool_provider.py:252-367; config filters intest_mcp_client_load_servers.py) · Integ: ✅ (test_mcp_tool_provider.py:18-115) · Docs: ✅ (mcp-tools.mdx).
Confirmation
- [x] The change is complete in the source SDK (merged + unit + integ tested + documented); every related artifact is listed above.
@strandly-the-agent implement
Implementation is blocked by the execution environment, not the repository: this follow-up was routed back to the terminated Code Interpreter session 01KY32HQ5JKXF9PVV586S1HNKZ, so every filesystem, shell, and subagent operation fails with Code interpreter session ... is not active.
I verified via GitHub at current main (50d388ece857cb386c157c82e0fd42c3ec956a3b) that neither refs/heads/port/mcp-tool-filtering-prefixing-to-ts nor a PR for that head exists. I therefore have not claimed or published an implementation.
A genuinely fresh harness sandbox is required to reconstruct the recorded port, add the three requested Agent-path integration cases, run full gates plus correctness/API re-reviews, and only then commit, push, and open the artifact-complete PR.
@strandly-the-agent try implement again
@strandly-the-agent review this pr. Some things I want to call out.
- naming conventions
- accesive use of async -- took into some typescript async conventions
- makeing changes outside the view of a strict python to typescript port.
Investigate and revise if necessary.
Reviewed my own PR against those three points — all three were valid, so I revised rather than defended. #3415 is force-pushed to ba4a8eb7c, rebased onto current main: 907+/58- across 14 files → 519+/28- across 10, and agent.ts / tool-registry.ts are no longer touched.
Scope was the root cause, and it was self-inflicted: my own prior review loop kept spawning correctness passes that found hypothetical races, and I kept "fixing" them inside a port PR. Removed: connect()/disconnect() promise-queue mutexes, listTools() serialization, a multi-subscriber tools-changed module, defensive deep-cloning of tools, Agent.initialize() single-flighting with transactional registry rollback, and a new replaceOwnedTools registry primitive. None of it was required by the source feature.
async: no new async/await outside tests now — the filter helpers are plain sync functions and option resolution is plain assignment. Naming: the worst offenders disappeared with the reverts (a notifyInternalListeners boolean-trap param, and an addMcpToolsChangedListener.listeners() function-with-a-property).
Re-deriving the port from mcp_client.py also exposed a real bug the extra machinery had been obscuring: I filtered before prefixing and passed the unprefixed tool to callback matchers. Python prefixes first, so a callback sees the agent-facing name while string/regex matchers compare tool.mcp_tool.name. The old revision even had a test asserting the wrong behavior. Fixed, with docs corrected.
Verification + two pre-existing issues I left alone
On ba4a8eb7c: unit 141 files / 3903 tests; MCP+config focused 140; MCP integration 8 passed against a real stdio server and live Bedrock (incl. 3 new Agent-path cases); lint, format, type-check, build, browser bundle, docs (473 tests, 873-page site build) all green. Independent port-fidelity, correctness and API passes came back clean — full traceability matrix with file:line on both sides is in the PR body.
Two things I found but deliberately did not touch, since they're pre-existing on main and unrelated to filtering/prefixing:
agent.tsassignsclient.onToolsChangedas a single slot, so two Agents sharing oneMcpClientclobber each other's refresh callback. Registration and invocation are fine; only a live refresh surfaces it.McpClient.connect()is check-then-act on_state, so concurrent first calls can race the handshake.
Say the word and I'll file both as separate issues.
One open question for you: the three-state override (undefined inherits, explicit ''/{} disables) is verbatim Python parity, but an API pass argued TS would be better served by null as the disable sentinel. I kept parity — changing it is a cross-SDK API call, not mine to make inside a port.
Still needs a human approve, and the API pass suggested an api/needs-review label (I can't apply labels via the API).
@strandly-the-agent
@strandlytheagent
we should make all the changes in the ListTools function of the MCPClient. I don’t see a need to overreach in this PR.
I really think a good refactor will be to move this mcpClient initalization and mcp tool folding into toolrggistry in agent loop into the tool registry.
public async initialize(): Promise
// Initialize MCP clients and register their tools
await Promise.all(
this._mcpClients.map(async (client) => {
const tools = await client.listTools()
this._toolRegistry.add(tools)
client.onToolsChanged = (oldTools, newTools): void => {
oldTools.forEach((name) => this._toolRegistry.remove(name))
this._toolRegistry.addOrReplace(newTools)
}
})
)
That way we are not getting into weird logic with callbacks for tool changes and refiltering. I think when new tools are changed, we can resync the toolrggistry from there and bubble that up to the agent.py loop