sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[PORT] MCP tool filtering + name-prefixing (Py→TS)

Open strandly-the-agent opened this issue 4 months ago • 6 comments

⚠️ 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 the port label — 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): _ToolFilterCallback Protocol (:68), _ToolMatcher = str | Pattern[str] | callback (:72), ToolFilters(TypedDict, total=False) with allowed/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 builds name_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: MCPServerConfig carries prefix/tool_filters (:109); _parse_config_tool_filters (:1481), _compile_filter_patterns (:1498, raises ValueError on bad regex).

TypeScript landing points

  • strands-ts/src/mcp/client.ts: add prefix?/toolFilters? to McpClientOptions (:79-102), store in ctor (:159), apply in listTools() (:318-346) after constructing each McpTool (:329), before pushing; update _registeredToolNames (:344) with effective (prefixed) names.
  • Config path: extend McpServerConfig (mcp/config.ts:10-33), compile in config.node.ts.
  • Agent integration transparent (filter/prefix inside listTools()); ensure onToolsChanged refresh (agent.ts:781) applies the same.

Gotchas / open questions

  • re.Pattern.match is start-anchored; JS RegExp.test is 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 (None vs explicit {}/""): undefined=default, but callers passing ''/{} must still override — decide whether listTools() gains optional params (matching list_tools_sync) or ctor-only. API-shape decision.
  • str | RegExp | (tool)=>boolean union; TypedDict total=False → interface with optional fields; bad-regex ValueError → clear SyntaxError wrap.

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 in test_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 avatar Jul 09 '26 22:07 strandly-the-agent

@strandly-the-agent implement

arielnabavian avatar Jul 21 '26 19:07 arielnabavian

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 avatar Jul 21 '26 20:07 strandly-the-agent

@strandly-the-agent try implement again

arielnabavian avatar Jul 22 '26 13:07 arielnabavian

@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.

arielnabavian avatar Jul 30 '26 23:07 arielnabavian

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:

  1. agent.ts assigns client.onToolsChanged as a single slot, so two Agents sharing one McpClient clobber each other's refresh callback. Registration and invocation are fine; only a live refresh surfaces it.
  2. 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 avatar Jul 31 '26 00:07 strandly-the-agent

@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 { if (this._initialized) { return }

// 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

arielnabavian avatar Jul 31 '26 02:07 arielnabavian