Repository navigation
fix(tool): fail fast on duplicate tool registration instead of silent replacement - #3332
Conversation
7a464e5 to
f76f79d
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Addresses #3328 in the right place: the duplicate check sits in the single funnel every registration path goes through, the conflict message names both sides and the escape hatches, and refreshSameSource keeps the common "re-register the same annotated object" idiom idempotent instead of turning it into a new failure. The DuplicateToolRegistrationTest suite is thorough (MCP shadowing, prefixed coexistence, self-clash, copy() meta-tool rebind).
Holding at COMMENT because the guard is not atomic against concurrent registration (the failure mode it is meant to remove is still reachable), and because the strict rule turns re-registration of schema-only and MCP tools — both of which build a fresh instance per call — into an IllegalStateException. Details inline. Also: build (windows-latest) was still pending at f76f79dc, and this changes public-API behaviour, so a changelog/migration note looks necessary regardless.
Findings
- [Warning]
agentscope-core/.../tool/ToolRegistry.java:70— check-then-act across two separate maps; the silent-shadowing race is still reachable. - [Warning]
agentscope-core/.../tool/Toolkit.java:275—refreshSameSourceonly coversReflectiveFunctionTool;registerSchemaand MCP re-registration build a new instance per call and now fail (the MCP case also closes the client throughdoOnError). - [Info]
agentscope-core/.../tool/ToolRegistry.java:105— server-supplied descriptions interpolated verbatim into the exception message. - [Info]
agentscope-core/.../tool/Toolkit.java:222— public-API behaviour change needs a migration note; consider aToolkitConfigpolicy. - [Info]
agentscope-core/src/test/.../ToolkitTest.java:424— dropping the second registration emptiesinactiveGroup, so the "registered but group-inactive" case is no longer covered.
Nothing here is architectural — the direction is right and the tests are the kind of coverage this change needs. Mostly I want the two concurrency/compat questions answered before merge.
Automated review by github-manager-bot
| if (toolName == null || toolName.isBlank()) { | ||
| throw new IllegalArgumentException("Tool name cannot be null or blank"); | ||
| } | ||
| AgentTool existing = tools.get(toolName); |
There was a problem hiding this comment.
[Warning] The guard is a check-then-act on two independent ConcurrentHashMaps, so it is not atomic: two threads registering different tools under the same name can both read existing == null / existing == their own and both put, which reproduces exactly the silent shadowing this change is meant to eliminate (the second write also leaves registeredTools describing the loser). removeToolIfSame in the same class already uses the CAS form (Map.remove(key, value)) for this reason. Consider making registration atomic too, e.g.
boolean[] replaced = {false};
tools.compute(toolName, (k, existing) -> {
if (existing != null && existing != tool && !allowReplaceExisting) {
replaced[0] = true;
return existing;
}
return tool;
});
if (replaced[0]) { throw new IllegalStateException(...); }
registeredTools.put(toolName, registered);|
|
||
| // Register in toolRegistry | ||
| toolRegistry.registerTool(toolName, tool, registered); | ||
| toolRegistry.registerTool(toolName, tool, registered, allowReplace || refreshSameSource); |
There was a problem hiding this comment.
[Warning] refreshSameSource only rescues ReflectiveFunctionTool registrations, so every path that builds a fresh instance per call now hard-fails on a second registration:
registerSchema(...)→new SchemaOnlyTool(schema)— re-registering the same schema (e.g.HarnessAgent.Builder.registerExternalSchemas, or aself_hostedsession that re-declares its hands tools on a shared toolkit) throwsIllegalStateException.McpClientManager.registerMcpClient(...)→ a newMcpToolper tool per call, so re-registering the same MCP client (reconnect / tool-list refresh) now throws — and because the throw propagates through the reactive pipeline, thedoOnErrorbranch also closes the client wrapper, so a refresh that used to be harmless now tears the connection down.
The old behaviour was idempotent replacement, so this is a behavioural break beyond the case #3328 targets (local vs remote shadowing). Could the refresh check also accept "same mcpClientName as the existing registration" and "same schema name/parameters" — or, if you want to keep the strict rule, call it out in the changelog and add an explicit re-register/replace path for MCP clients?
| return "Tool '" | ||
| + toolName | ||
| + "' is already registered and will not be silently replaced." | ||
| + " existing: [" |
There was a problem hiding this comment.
[Info] existing.getDescription() / incoming.getDescription() are interpolated verbatim into the exception message. For MCP tools those descriptions are server-supplied and can be multi-line and arbitrarily long, and this message ends up in logs (and possibly in a tool-error result rendered to a UI). Worth collapsing whitespace and truncating each side to a fixed budget (say 120 chars) so one hostile/large server cannot blow up log lines.
| * | ||
| * @param tool the AgentTool to register, replacing any existing tool with the same name | ||
| */ | ||
| public void replaceAgentTool(AgentTool tool) { |
There was a problem hiding this comment.
[Info] replaceAgentTool is the right explicit escape hatch. Two follow-ups to keep the migration cheap for existing users: (1) ToolRegistry.registerTool / Toolkit.registerAgentTool change the exception behaviour of a public API, so this needs a note in the release notes / migration guide; (2) consider a ToolkitConfig policy (FAIL_FAST / REPLACE, defaulting to FAIL_FAST) so an application that knowingly relies on override can flip it instead of hunting every call site.
| toolkit.createToolGroup("inactiveGroup", "Inactive tools", false); | ||
|
|
||
| // Register tools to different groups | ||
| // Register tools to the active group. (A second same-named registration used to be |
There was a problem hiding this comment.
[Info] Dropping the second registration keeps the test green but also empties inactiveGroup: the case the original test was built around — a tool that exists in the registry but whose only group is inactive — is no longer exercised (updateToolGroups(List.of("inactiveGroup"), false) is now a no-op). Registering a differently-named tool object into inactiveGroup would preserve that coverage without tripping the duplicate guard.
8fa2e4b to
95cebc5
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
This PR replaces implicit duplicate-tool overwrites with atomic per-name fail-fast registration, an explicit replacement API, and narrow idempotent refresh paths. IllegalStateException is appropriate for a conflict with the current registry state, and the tests cover the principal local, MCP, schema, and normal concurrent duplicate paths. However, tool and registration metadata updates remain non-atomic, a same-named distinct MCP wrapper can silently take over a tool, and the reflective-refresh exemption can race an explicit replacement. These cases should be fixed and tested before merge.
Re-reviewed at head 8fa2e4b3c4; CLA: signed.
Automated review by github-manager-bot
| } | ||
| return tool; | ||
| }); | ||
| registeredTools.put(toolName, registered); |
There was a problem hiding this comment.
tools.compute completes before registeredTools.put, so the two registry maps are not updated atomically. For example, a concurrent removeTool can run after a replacement binds the new tool but before this write, then this write recreates metadata for an absent tool; ToolSchemaProvider reads that metadata map and can advertise the stale tool. The new concurrency test only checks the primary map. Store tool and registration metadata as one atomic value (or synchronize every cross-map operation) and test replacement/removal interleavings.
| */ | ||
| private static boolean isIdempotentRefresh(AgentTool existing, AgentTool incoming) { | ||
| if (existing instanceof McpTool existingMcp && incoming instanceof McpTool incomingMcp) { | ||
| return existingMcp.getClientName().equals(incomingMcp.getClientName()); |
There was a problem hiding this comment.
isIdempotentRefresh identifies an MCP client solely by getClientName(). McpClientManager accepts a second wrapper with the same name and overwrites its mcpClients entry on success, so a different wrapper (and potentially a different server) with the same configured name silently replaces the first wrapper's tool; the first initialized wrapper is no longer tracked and will not be closed by removeMcpClient. This reintroduces the MCP shadowing/lifecycle problem for duplicate client names. Compare wrapper identity (or reject a duplicate client name explicitly) and add a test using two distinct wrappers with the same name.
|
|
||
| // Register in toolRegistry | ||
| toolRegistry.registerTool(toolName, tool, registered); | ||
| toolRegistry.registerTool(toolName, tool, registered, allowReplace || refreshSameSource); |
There was a problem hiding this comment.
refreshSameSource is computed before ToolRegistry's per-key compute and is then passed as an unconditional replacement permission. If thread A re-registers an annotated source, thread B intentionally calls replaceAgentTool for the same name after A has inspected the old reflective tool, and A then reaches this call, A silently overwrites B's explicit replacement. This conflicts with the atomic-registration guarantee and the new concurrency test only covers distinct direct AgentTool contenders. Revalidate the source identity inside the per-name atomic operation (or retry on a changed binding) and add this interleaving to the regression tests.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-reviewed the merge of main into this branch (b4768ba). The conflict resolution keeps the fail-fast duplicate-registration path intact: ToolRegistry rejects duplicate tool names atomically via ConcurrentHashMap.compute, same-instance refresh is still allowed by identity, @Tool method re-registration is allowed when source object/method match, MCP reconnects from the same client are allowed, and registerMetaTool() / Toolkit.copy() go through the explicit replaceAgentTool() path. The unrelated JDBC docs rename pulled in from main matches 3a6baf6 and does not touch the fix. Test coverage (local/MCP/schema conflicts, self-clashing methods, concurrency, message formatting) looks adequate.
One non-blocking follow-up: the public registration behaviour changed from silent replacement to IllegalStateException, so the user-facing docs should describe that plus Toolkit.replaceAgentTool() as the explicit override API (see inline comment).
Automated review by github-manager-bot
- [INFO]
agentscope-core/src/main/java/io/agentscope/core/tool/Toolkit.java:209— The public registration behavior changed from silent replacement to fail-fast. Please updatedocs/v2/en/docs/building-blocks/tool.mdand its Chinese counterpart to documentToolkit.replaceAgentTool()as the explicit override API and mention that duplicate names now throwIllegalStateException.
Automated review by github-manager-bot
… replacement Registering a tool whose name is already bound to a different AgentTool silently replaced the existing tool (no exception, no log) - including MCP tools quietly shadowing same-named local tools, so anything keyed by tool name (permission rules, tool groups, confirmation handling) applied to the wrong tool without any signal. - ToolRegistry keeps a single map (name -> RegisteredToolFunction) holding the tool binding and its metadata, written and removed in one atomic operation so they can never diverge. registerTool classifies the conflict and installs the new registration inside one ConcurrentHashMap.compute: concurrent registrations of different tools under one name have exactly one winner, and every loser fails fast with an IllegalStateException naming both tools (descriptions, plus the MCP client name when applicable) and the escape hatches. - Idempotent re-registration stays allowed: refreshing the exact same @tool source object+method, an MCP client re-registering its own tools (same client wrapper instance - reconnect / tool-list refresh), and a SchemaOnlyTool re-declared with an identical schema (description, parameters, strict, deferred-loading flag) are treated as refreshes, not conflicts. A distinct wrapper reusing an existing client name is refused at name reservation, before any connection work starts: it may talk to a different server, and accepting it would silently take over the first wrapper's tools while the first wrapper falls out of tracking (and never gets closed). - McpClientManager reserves the client name at subscription time and tracks each registration attempt with a claim: a failed attempt rolls back only the tools it wrote (including their group membership) and closes the wrapper exactly once; a synchronous initialize() throw or a subscription cancel releases the reservation without orphaned tools; a client removed mid-registration is never resurrected by its late success; a close failure never masks the original error. - A new explicit Toolkit.replaceAgentTool API covers deliberate replacement, used by registerMetaTool for the intentional rebind in Toolkit.copy(); it leaves group membership (keyed by tool name) untouched, so the replacement inherits the replaced name's groups. - Rejected-registration messages summarize tool descriptions (whitespace collapsed, 120-char cap, null rendered as "null") so errors stay single-line readable. - MCP registration funnels through the same check, so a name clash is reported when the server's tools are registered; mcpToolNamePrefix keeps coexistence possible. ToolGroupManager.removeToolFromAllGroups keeps group membership in sync when a rolled-back registration had joined groups. - en/zh tool docs gain a "Duplicate-name conflicts and explicit replacement" section. - agui adapter tests: the two cases that probed 'adapter never reverts the shared toolkit' used same-name re-registration as the probe; they now use the explicit replaceAgentTool API, which keeps the assertion intact under the new contract. The ToolkitTest group-gating test registers a differently-named tool into the inactive group instead of relying on the previously silent override. Fixes agentscope-ai#3328
b4768ba to
66a3aa7
Compare
…omAgent ## Problem `Builder.fromAgent()` copied the source toolkit as-is. When the source was a `HarnessAgent`-built delegate, the copy still carried the harness platform tool instances (teams / subagents / task tools, memory tools, session search, filesystem tools, `deliver_artifact`, `execute`, web and plan-mode tools). `buildInstance()` then re-registers the same names with fresh bindings, and the fail-fast duplicate-name rule introduced in `66a3aa7aa` rejected them with `IllegalStateException: Tool name already registered`. ## Changes - Add `HarnessAgent.FROM_AGENT_RESET_TOOL_NAMES`: `HarnessPlatformTools.NAMES` plus the tool names `buildInstance()` registers directly (memory, session, filesystem, artifact delivery, shell, web tools). - `fromAgent()` strips those names from the copied toolkit before rebuilding, so `buildInstance()` re-creates every harness tool with fresh bindings. User-registered tools are left untouched and remain inherited as-is. - Add `HarnessAgentTest.fromAgent_rebuildsHarnessPlatformToolsWithoutCollision` guarding the rebuild path. ## Compatibility - No API change. `fromAgent()` on a harness-built source previously failed with `IllegalStateException`; it now succeeds.
3730c6b to
889759d
Compare
Buktal
left a comment
There was a problem hiding this comment.
-
[P1] Preserve user bindings when rebuilding Harness tools —
agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java:1617.FROM_AGENT_RESET_TOOL_NAMESidentifies tools by name, not ownership. A user-providedread_fileon a plainReActAgent, or a user replacement on a Harness agent, is removed byfromAgent; disabling filesystem tools then loses that binding, while leaving them enabled silently substitutes the framework implementation. The same cleanup misses tools in inactive groups becausegetToolSchemas()filters them, and cannot remove inherited tools whenallowToolDeletion(false)is configured. Both cases make rebuilding fail with duplicate-registration errors. Track framework-owned instances and exclude only those bindings during construction-time copying, preserving user tools and deletion policy. Add regressions for user-defined names, explicit user replacements, inactive groups, and disabled deletion. -
[P2] Bound MCP refresh bookkeeping —
agentscope-core/src/main/java/io/agentscope/core/tool/McpClientManager.java:506. Every refresh appends newly created tools toClientClaim.registeredTools, but a completed claim does not retire superseded entries: the list is cleared only when the claim is released or becomes stale. Repeated refreshes retain every generation of tools and schemas for the client's lifetime. Retire entries once they are no longer needed by active attempts or current bindings, preserving identity-guarded rollback. Test repeated successful refreshes and partially failed refreshes after an initial success. -
[P2] Coordinate cancellation with tool publication —
agentscope-core/src/main/java/io/agentscope/core/tool/McpClientManager.java:497. The claim check at line 423, registration callback, and rollback-list insertion at line 506 are separate operations. Cancellation during the callback can release the claim, snapshot an incomplete rollback list, and close the wrapper before the callback finishes publishing the tool. This interleaving is identified from code inspection; it has not been reproduced by a runtime test. Establish a coordinated publication/cleanup boundary or compensate for writes that finish after cancellation. Add a deterministic latch-based test that cancels while the registration callback is in progress, then verifies no tool/group entries survive and the wrapper is closed exactly once. -
Separate lifecycle coordination from tool conversion —
agentscope-core/src/main/java/io/agentscope/core/tool/McpClientManager.java:259. This method spans roughly 290 lines and combines validation, claim state transitions, connection initialization, metadata validation, tool construction, registry publication, rollback, and closing. Extract schema/metadata validation and tool construction into focused helpers, and encapsulate claim transitions and terminal cleanup around explicit invariants. Keep the outer reactive chain responsible for orchestration. The refactoring should make the publication/rollback boundary in item 3 explicit. -
Keep comments focused on invariants and rationale —
agentscope-core/src/main/java/io/agentscope/core/tool/McpClientManager.java:369. Reduce repeated narration and emphatic wording such as “Fail loud” and uppercase state descriptions. Keep concise explanations of non-obvious guarantees, such as subscription-time admission and instance-guarded rollback. For example, the metadata-override comment can state:Overrides must target tools selected for registration.Rework the surrounding nesting so explanatory comments remain readable.
Keep tool metadata and group updates consistent during registration and cleanup. Centralize same-source refresh checks and include the MCP remote tool identity. Release failed MCP claims before downstream recovery and preserve cancellation cleanup. Rebuild framework tools by source identity when copying agents, including plain ReActAgent requirements. Add regression coverage and align the English and Chinese tool documentation.
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
AgentScope-Java Version
2.0.4-SNAPSHOTDescription
Fixes #3328
Summary
Registering a tool whose name is already bound to a different tool now fails fast with an
IllegalStateExceptioninstead of silently replacing the previous registration, and an explicit replacement API is provided for intentional overrides. Duplicate detection is race-free (atomic per-name check-and-bind over a single name→registration map), and idempotent re-registration patterns — MCP client reconnects, unchanged schema re-declarations and same-source-method refreshes — remain supported. Failed MCP registration attempts roll back their own partial registrations and close the client wrapper exactly once.Root cause
ToolRegistry.registerToolperformed an unconditionaltools.put(toolName, tool)with no exception and no log. Every public registration path funnels through it — annotated@Toolscanning, directregisterAgentTool,registerSchema, sub-agent tools and MCP tools (viaMcpClientManager's registration callback) — so a later registration of the same name quietly won.For MCP this is especially dangerous: MCP tools are registered after local tools, so with the name prefix disabled a remote tool silently shadows a same-named local tool, and everything keyed by tool name (permission rules, tool groups, confirmation handling) then applies to the remote tool without any signal.
Changes
agentscope-core/ToolRegistry:RegisteredToolFunctionholding both theAgentToolinstance and its registration metadata (extended schema, MCP client name, preset parameters). The binding and its metadata are written and removed together in one atomic map operation, so they can never diverge.registerToolrejects a name already bound to a differentAgentToolwith anIllegalStateExceptionwhose message names both tools and points to the escape hatches. The check-then-bind sequence runs atomically per name viaConcurrentHashMap.compute, so concurrent registrations of different tools under one name have exactly one winner and every loser fails fast instead of silently shadowing.SchemaOnlyToolre-declared with an identical schema (description, parameters, strict mode and deferred-loading flag) are treated as refreshes, not conflicts. A distinct wrapper reusing an existing client name is refused at name reservation, before any connection work starts: it may talk to a different server, and accepting it would silently take over the first wrapper's tools while the first wrapper falls out of tracking (and never gets closed). Everything else — local-over-MCP, MCP-over-local, two different MCP clients claiming one name, or a schema that changed under the same name — stays a fail-fast conflict.nullrendered as"null") so a rejected registration stays a single readable log line even with long multi-line descriptions.agentscope-core/Toolkit: re-registering the same@Toolsource object and method stays an idempotent refresh (backward compatible); new publicToolkit.replaceAgentTool(AgentTool)for intentional overrides;registerMetaToolroutes through it so the legitimate meta-tool rebind inToolkit.copy()is unaffected. Group membership is keyed by tool name and is left untouched by a replacement, so the replacement inherits the replaced name's groups (documented in the Javadoc).agentscope-core/McpClientManager: the client name is reserved at subscription time and each registration attempt is tracked with a claim — a failed attempt rolls back only the tools it wrote (including their group membership) and closes the wrapper exactly once; a synchronousinitialize()throw or a subscription cancel releases the reservation without orphaned tools; a client removed mid-registration is never resurrected by its late success; a close failure never masks the original error.agentscope-core/ToolGroupManager: newremoveToolFromAllGroupskeeps group membership in sync when a rolled-back registration had joined groups.mcpToolNamePrefixkeeps coexistence possible.Migration
Previously, re-registering a tool over a taken name silently replaced the old binding, and some code relied on that. After this change:
toolkit.replaceAgentTool(tool); it is the only explicit replacement path.registerSchema) → no change needed when the schema is identical (description, parameters, strict, deferred-loading flag). A changed schema under the same name — including only flipping deferred loading — is now a hard conflict: remove the old registration first or pick a different name.McpClientWrapperwith an existing client name → now refused. Remove the old client first (removeMcpClient) or use a different client name.toolNamePrefixor rename one tool; previously the last registration silently won.How to test
mvn -pl agentscope-core test -Dtest=DuplicateToolRegistrationTest,ToolRegistryTest,ToolkitTest,ToolGroupManagerTest,McpClientManagerTest,McpToolTest,ReflectiveFunctionToolTestType of change
Checklist
mvn spotless:applydocs/v2/docs/building-blocks/tool.mdgained a "Duplicate-name conflicts and explicit replacement" section covering the fail-fast behavior, the idempotent-refresh boundaries,toolNamePrefixcoexistence andreplaceAgentTool