Skip to content

The agent that grows with you

fix(desktop): exact tool ownership per chat owner; whole-path producer match

Teknium4fb80ec2acf7
diff --git a/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx b/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx
index 5a8ba0c8cb4..57a6da866f9 100644
--- a/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool-media-slot.test.tsx
@@ -11,7 +11,7 @@ import {
type ToolMediaRendererContribution,
type ToolMediaRendererProps
} from '@/lib/tool-media-renderers'
-import { $toolMediaOwners } from '@/store/tool-media-owners'
+import { $toolMediaOwners, toolMediaOwnerKey } from '@/store/tool-media-owners'
import { MarkdownText, MessageTextContent } from './markdown-text'
import { createdAt, stubThreadEnvironment, ThreadRuntime, userMessage } from './test-utils'
@@ -116,14 +116,16 @@ describe('tool media renderers', () => {
sfx: { id: 'sfx', kind: 'disk', name: 'SFX', packageName: 'sfx', status: 'loaded' },
thief: { id: 'thief', kind: 'disk', name: 'Thief', packageName: 'thief', status: 'loaded' }
})
- // What the backend's plugins.manage list reported for the active route.
+ // What the backend's plugins.manage list reported for this chat's owner.
$toolMediaOwners.set({
- key: '|default|0',
- owners: new Map([
- ['sfx', { prefixes: [], tools: new Set(['sfx_make']) }],
- ['thief', { prefixes: [], tools: new Set(['thief_tool']) }]
- ]),
- status: 'ready'
+ [toolMediaOwnerKey(null)]: {
+ owners: new Map([
+ ['sfx', { tools: new Set(['sfx_make']) }],
+ ['thief', { tools: new Set(['thief_tool']) }]
+ ]),
+ request: 1,
+ status: 'ready'
+ }
})
})
diff --git a/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx b/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx
index d9c47ac3d4b..47a1d44a511 100644
--- a/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx
+++ b/apps/desktop/src/components/assistant-ui/tool-media-slot.tsx
@@ -18,7 +18,12 @@ import {
type ToolMediaRendererContribution,
type ToolMediaRendererProps
} from '@/lib/tool-media-renderers'
-import { $toolMediaOwners, ensureToolMediaOwners, packageOfContributionSource } from '@/store/tool-media-owners'
+import {
+ $toolMediaOwners,
+ ensureToolMediaOwners,
+ packageOfContributionSource,
+ toolMediaOwnerKey
+} from '@/store/tool-media-owners'
/**
* Where a `MEDIA:` attachment meets the tool media renderer area. With no
@@ -78,17 +83,22 @@ const ClaimedToolMediaSlot: FC<{ children: ReactNode; claims: readonly Contribut
}) => {
const part = useProducingToolCall(path)
const producer = useMemo(() => (part ? effectiveToolCall(part) : null), [part])
- const owners = useStore($toolMediaOwners)
+ const view = useSessionView()
+ const storedId = useStore(view.$storedId)
+ const runtimeId = useStore(view.$runtimeId)
+ const sessionId = storedId || runtimeId || null
+ const entries = useStore($toolMediaOwners)
+ const entry = entries[toolMediaOwnerKey(sessionId)]
// Re-resolve when a plugin record (enable state, package) changes.
useStore($pluginRecords)
useEffect(() => {
if (producer) {
- ensureToolMediaOwners()
+ ensureToolMediaOwners(sessionId)
}
- }, [producer, owners])
+ }, [producer, sessionId, entry])
- const ready = owners.status === 'ready' ? owners.owners : null
+ const ready = entry?.status === 'ready' ? entry.owners : null
useEffect(() => {
if (!ready) {
@@ -115,7 +125,7 @@ const ClaimedToolMediaSlot: FC<{ children: ReactNode; claims: readonly Contribut
return (
<ErrorBoundary fallback={() => children} label={`contrib:${claim.id}`}>
- <ToolMediaLeaf contribution={claim} fallback={children} path={path} producer={producer} />
+ <ToolMediaLeaf contribution={claim} fallback={children} path={path} producer={producer} sessionId={sessionId} />
</ErrorBoundary>
)
}
@@ -125,11 +135,9 @@ const ToolMediaLeaf: FC<{
fallback: ReactNode
path: string
producer: ToolCallLike
-}> = ({ contribution, fallback, path, producer }) => {
+ sessionId: null | string
+}> = ({ contribution, fallback, path, producer, sessionId }) => {
const render = (contribution.data as ToolMediaRendererContribution).render
- const view = useSessionView()
- const storedId = useStore(view.$storedId)
- const runtimeId = useStore(view.$runtimeId)
const file = useMemo<ToolMediaFile>(
() => ({
@@ -162,7 +170,7 @@ const ToolMediaLeaf: FC<{
fallback={fallback}
file={file}
result={producer.result}
- sessionId={storedId || runtimeId || null}
+ sessionId={sessionId}
toolCallId={producer.toolCallId ?? ''}
toolName={producer.toolName ?? ''}
/>
diff --git a/apps/desktop/src/lib/tool-media-renderers.test.ts b/apps/desktop/src/lib/tool-media-renderers.test.ts
index 42184701e51..a64eb2de58b 100644
--- a/apps/desktop/src/lib/tool-media-renderers.test.ts
+++ b/apps/desktop/src/lib/tool-media-renderers.test.ts
@@ -4,6 +4,7 @@ import {
claimPatternOwned,
effectiveToolCall,
findProducingToolCall,
+ namesWholePath,
ownerOfTool,
refusedClaimPatterns,
resolveToolMediaClaim,
@@ -37,6 +38,25 @@ describe('findProducingToolCall', () => {
expect(findProducingToolCall([messages[2], messages[4]], 'a2', path)?.toolName).toBe('terminal')
})
+ it('matches whole paths only: a longer sibling file never claims this one', () => {
+ const messages = [
+ { id: 'u', role: 'user', content: [] },
+ {
+ id: 'a',
+ role: 'assistant',
+ content: [
+ call('first', { path: `${path}.bak` }),
+ call('nested', `copied /x${path}`),
+ call('second', `saved to ${path}.`)
+ ]
+ }
+ ]
+
+ expect(findProducingToolCall(messages, 'a', path)?.toolName).toBe('second')
+ expect(namesWholePath(`MEDIA:${path}`, path)).toBe(true)
+ expect(namesWholePath(`${path}.bak`, path)).toBe(false)
+ })
+
it('ignores failed calls and finds Windows paths inside JSON results', () => {
const win = 'C:\\Users\\me\\out\\clip.wav'
@@ -68,23 +88,22 @@ describe('effectiveToolCall', () => {
describe('ownership', () => {
const owners = new Map<string, ToolOwnership>([
- ['sfx', { prefixes: [], tools: new Set(['sfx_make']) }],
- ['meshy', { prefixes: ['mcp__meshy__'], tools: new Set() }],
- ['nested', { prefixes: ['mcp__meshy__x__'], tools: new Set() }]
+ ['sfx', { tools: new Set(['sfx_make']) }],
+ ['meshy', { tools: new Set(['mcp__meshy__download', 'mcp__meshy__status']) }],
+ ['nested', { tools: new Set(['mcp__meshy__x__gen']) }]
])
- it('resolves a tool to exactly one package, longest MCP namespace first', () => {
+ it('resolves a tool to the one package that registered it', () => {
expect(ownerOfTool('sfx_make', owners)).toBe('sfx')
expect(ownerOfTool('mcp__meshy__download', owners)).toBe('meshy')
expect(ownerOfTool('mcp__meshy__x__gen', owners)).toBe('nested')
expect(ownerOfTool('text_to_speech', owners)).toBeNull()
})
- it('lets a wildcard claim only inside the package’s own namespace', () => {
+ it('counts a claim pattern as owned only when it names a tool the package registered', () => {
expect(claimPatternOwned('mcp__meshy__*', owners.get('meshy'))).toBe(true)
- expect(claimPatternOwned('mcp__*', owners.get('meshy'))).toBe(false)
- expect(claimPatternOwned('sfx_*', owners.get('sfx'))).toBe(false)
expect(claimPatternOwned('text_to_speech', owners.get('sfx'))).toBe(false)
+ expect(claimPatternOwned('mcp__other__*', owners.get('meshy'))).toBe(false)
expect(claimPatternOwned('sfx_make', undefined)).toBe(false)
})
@@ -108,7 +127,7 @@ describe('ownership', () => {
expect(resolveToolMediaClaim(claims, 'mcp__meshy__download', { onRefused, owners, packageOf })?.id).toBe('meshy:x')
expect(onRefused.mock.calls.map(([c]) => c.id)).toEqual(['thief:x', 'solo:x'])
- // The nested server's tools are not meshy's, even through meshy's own wildcard.
+ // Another package's tool is never served through meshy's wildcard.
expect(resolveToolMediaClaim(claims, 'mcp__meshy__x__gen', { owners, packageOf })).toBeNull()
expect(refusedClaimPatterns(claims, owners, packageOf).map(r => r.claim.id)).toEqual(['thief:x', 'solo:x'])
})
diff --git a/apps/desktop/src/lib/tool-media-renderers.ts b/apps/desktop/src/lib/tool-media-renderers.ts
index eaead8a468c..6a446db5b4c 100644
--- a/apps/desktop/src/lib/tool-media-renderers.ts
+++ b/apps/desktop/src/lib/tool-media-renderers.ts
@@ -14,7 +14,7 @@ import type { MediaKind } from '@/lib/media'
*
* Ownership is provenance, never file type or name: the backend reports which
* tools each installed package's own code registered (`plugins.manage list` →
- * `tools` / `tool_prefixes`), and a claim on any other tool is refused.
+ * `tools`), and a claim on any other tool is refused.
*/
export const TOOL_MEDIA_RENDERER_AREA = 'transcript.toolMedia'
@@ -50,19 +50,19 @@ export interface ToolMediaRendererProps {
/** Payload of a `transcript.toolMedia` contribution's `data`. */
export interface ToolMediaRendererContribution {
- /** Tool names this renderer draws. A trailing `*` matches a namespace the
- * package owns (`mcp__meshy__*` for its MCP server). Claims on tools the
- * package did not register are refused with a console warning. */
+ /** Tool names this renderer draws. A trailing `*` matches by prefix
+ * (`mcp__meshy__*` for an MCP server's tools); either way only tools this
+ * plugin's package registered are served, and other claims are refused with
+ * a console warning. */
tools: readonly string[]
/** Mounted inside an error boundary whose fallback is the built-in player. */
render: (props: ToolMediaRendererProps) => ReactNode
}
-/** What one package's own code registered. */
+/** The exact tool names one package's own code registered (native tools and
+ * its MCP servers' live tools), as the backend reports them. */
export interface ToolOwnership {
tools: ReadonlySet<string>
- /** MCP server namespaces (`mcp__<server>__`). */
- prefixes: readonly string[]
}
/** The tool-call fields a producer lookup reads (an assistant-ui part). */
@@ -97,7 +97,9 @@ function pathNeedles(path: string): string[] {
const bare = path.startsWith('file:') ? decodeURIComponentSafe(path.replace(/^file:\/\//, '')) : path
// JSON-escaped forms too: a Windows path sits in a JSON result as `C:\\Users\\…`.
- return [...new Set([path, bare, JSON.stringify(path).slice(1, -1), JSON.stringify(bare).slice(1, -1)])]
+ return [...new Set([path, bare, JSON.stringify(path).slice(1, -1), JSON.stringify(bare).slice(1, -1)])].filter(
+ Boolean
+ )
}
function decodeURIComponentSafe(value: string): string {
@@ -108,6 +110,15 @@ function decodeURIComponentSafe(value: string): string {
}
}
+const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+
+/** Whether `text` names `needle` as a WHOLE path: `/out/a.glb` matches in
+ * `{"path":"/out/a.glb"}`, `saved to /out/a.glb.` and `MEDIA:/out/a.glb`, but
+ * never inside `/out/a.glb.bak` or `/x/out/a.glb`. */
+export function namesWholePath(text: string, needle: string): boolean {
+ return new RegExp(`(?<=^|[\\s"'\`(=\\[{,:])${escapeRegExp(needle)}(?=$|[\\s"'\`),;\\]}>]|\\.(?:$|\\s))`).test(text)
+}
+
function toolCallsOf(message: MessageLike): ToolCallLike[] {
return Array.isArray(message.content)
? (message.content as ToolCallLike[]).filter(
@@ -149,7 +160,7 @@ export function findProducingToolCall(
const text = payloadText(call.result)
- if (needles.some(needle => needle && text.includes(needle))) {
+ if (needles.some(needle => namesWholePath(text, needle))) {
return call
}
}
@@ -180,50 +191,26 @@ export function effectiveToolCall(part: ToolCallLike): ToolCallLike {
: part
}
-/** The package that owns `toolName`: an exact registration first, else the
- * longest MCP namespace that covers it (so `mcp__a__` never takes a server
- * named `a__b`'s tools). */
+/** The package that owns `toolName`: the one package whose registered tools
+ * include it (the backend already drops a name two packages list). */
export function ownerOfTool(toolName: string, owners: ReadonlyMap<string, ToolOwnership>): null | string {
- let best: null | string = null
- let bestLength = 0
-
for (const [pkg, owned] of owners) {
if (owned.tools.has(toolName)) {
return pkg
}
-
- for (const prefix of owned.prefixes) {
- if (toolName.startsWith(prefix) && toolName.length > prefix.length && prefix.length > bestLength) {
- best = pkg
- bestLength = prefix.length
- }
- }
}
- return best
+ return null
}
export function claimPatternMatches(pattern: string, toolName: string): boolean {
return pattern.endsWith('*') ? pattern.length > 1 && toolName.startsWith(pattern.slice(0, -1)) : toolName === pattern
}
-/** Whether `pattern` names only tools `owned` registered (a wildcard must sit
- * inside one of the package's MCP namespaces). */
+/** Whether `pattern` names a tool `owned` registered (a wildcard must match at
+ * least one). Only what the claim's own package registered is ever served. */
export function claimPatternOwned(pattern: string, owned: ToolOwnership | undefined): boolean {
- if (!owned) {
- return false
- }
-
- if (pattern.endsWith('*')) {
- const stem = pattern.slice(0, -1)
-
- return owned.prefixes.some(prefix => stem.startsWith(prefix))
- }
-
- return (
- owned.tools.has(pattern) ||
- owned.prefixes.some(prefix => pattern.startsWith(prefix) && pattern.length > prefix.length)
- )
+ return owned ? [...owned.tools].some(tool => claimPatternMatches(pattern, tool)) : false
}
export interface ToolMediaClaim {
diff --git a/apps/desktop/src/store/tool-media-owners.ts b/apps/desktop/src/store/tool-media-owners.ts
index 7c1f0a2cc0b..9fed8015807 100644
--- a/apps/desktop/src/store/tool-media-owners.ts
+++ b/apps/desktop/src/store/tool-media-owners.ts
@@ -10,79 +10,136 @@ import {
activeGatewayProfileKey,
gatewayActivationEpoch
} from '@/store/gateway'
+import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
+import { knownOwnerForSession } from '@/store/session-states'
/**
- * Which tools each installed package's own code registered, per active backend
- * route — the authority behind tool media renderers. Read from the backend's
- * `plugins.manage list` (`tools` / `tool_prefixes`), never from the renderer:
- * a desktop half could otherwise name any tool. Loaded lazily the first time a
- * claimed attachment needs it and refetched when the route or the agent plugin
- * list changes. A backend that predates the fields reports nothing, so every
- * claim falls back to the built-in player.
+ * Which tools each installed package's own code registered, per chat owner
+ * (connection + profile) — the authority behind tool media renderers. Read
+ * from the owning backend's `plugins.manage list` (`tools`), never from the
+ * renderer: a desktop half could otherwise name any tool. Loaded lazily the
+ * first time a claimed attachment needs it, refetched when the agent plugin
+ * list changes, retried with a bounded backoff after a failure. A backend that
+ * predates the field reports nothing, so every claim keeps the built-in player.
*/
-export type ToolMediaOwnersState =
- | { status: 'idle' | 'loading' | 'error'; key: string }
- | { status: 'ready'; key: string; owners: ReadonlyMap<string, ToolOwnership> }
+export type ToolMediaOwnersEntry =
+ | { status: 'loading' | 'error'; request: number }
+ | { status: 'ready'; request: number; owners: ReadonlyMap<string, ToolOwnership> }
-export const $toolMediaOwners = atom<ToolMediaOwnersState>({ key: '', status: 'idle' })
+export const $toolMediaOwners = atom<Readonly<Record<string, ToolMediaOwnersEntry>>>({})
-type OwnershipRow = AgentPluginRow & { tool_prefixes?: string[]; tools?: string[] }
+type OwnershipRow = AgentPluginRow & { tools?: string[] }
-function routeKey(): string {
- return `${activeGatewayConnectionId() ?? ''}|${activeGatewayProfileKey()}|${gatewayActivationEpoch()}`
-}
+let requests = 0
+const failures = new Map<string, number>()
export function ownersFromPluginRows(rows: readonly OwnershipRow[]): Map<string, ToolOwnership> {
const owners = new Map<string, ToolOwnership>()
for (const row of rows) {
- const tools = Array.isArray(row.tools) ? row.tools.filter(name => typeof name === 'string') : []
-
- const prefixes = Array.isArray(row.tool_prefixes)
- ? row.tool_prefixes.filter(prefix => typeof prefix === 'string' && prefix.length > 0)
- : []
+ const tools = Array.isArray(row.tools) ? row.tools.filter(name => typeof name === 'string' && name) : []
- if (tools.length > 0 || prefixes.length > 0) {
- owners.set(agentPackageName(row), { prefixes, tools: new Set(tools) })
+ if (tools.length > 0) {
+ owners.set(agentPackageName(row), { tools: new Set(tools) })
}
}
return owners
}
-/** Fetch the ownership list for the active route unless it is loaded or loading. */
-export function ensureToolMediaOwners(): void {
- const key = routeKey()
- const current = $toolMediaOwners.get()
+/** The backend profile a session owner names (the profile `plugins.manage` must list). */
+function ownerProfile(owner: SessionOwnerScope): null | string {
+ if (!owner) {
+ return null
+ }
- if (current.key === key && current.status !== 'idle') {
- return
+ return typeof owner === 'string' ? owner : (owner.targetProfile ?? owner.profile)
+}
+
+/** Cache key for the chat `sessionId` belongs to: its exact owner when known, else the active route. */
+export function toolMediaOwnerKey(sessionId: null | string): string {
+ const owner = knownOwnerForSession(sessionId)
+
+ if (owner) {
+ return typeof owner === 'string' ? `profile:${owner}` : `route:${owner.connectionId}|${ownerProfile(owner)}`
}
+ return `active:${activeGatewayConnectionId() ?? ''}|${activeGatewayProfileKey()}|${gatewayActivationEpoch()}`
+}
+
+function setEntry(key: string, entry: null | ToolMediaOwnersEntry) {
+ const next = { ...$toolMediaOwners.get() }
+
+ if (entry) {
+ next[key] = entry
+ } else {
+ delete next[key]
+ }
+
+ $toolMediaOwners.set(next)
+}
+
+function scheduleRetry(key: string, stillCurrent: () => boolean) {
+ const attempt = (failures.get(key) ?? 0) + 1
+
+ failures.set(key, attempt)
+ // Bounded backoff (2 s doubling to 60 s): clearing the entry lets the next
+ // render of a claimed attachment fetch again once the connection is back.
+ setTimeout(
+ () => {
+ if (stillCurrent()) {
+ setEntry(key, null)
+ }
+ },
+ Math.min(60_000, 2_000 * 2 ** (attempt - 1))
+ )
+}
+
+/** Fetch the ownership list for the chat `sessionId` belongs to, unless it is loaded, loading or backing off. */
+export function ensureToolMediaOwners(sessionId: null | string): void {
+ const key = toolMediaOwnerKey(sessionId)
const gateway = activeGateway()
- if (!gateway) {
+ if ($toolMediaOwners.get()[key] || !gateway) {
return
}
- $toolMediaOwners.set({ key, status: 'loading' })
- void gateway
- .request<{ plugins?: OwnershipRow[] }>('plugins.manage', { action: 'list' })
+ const owner = knownOwnerForSession(sessionId)
+ const profile = ownerProfile(owner)
+ const request = ++requests
+
+ setEntry(key, { request, status: 'loading' })
+ // Only the newest request for a key may write it: an invalidation (plugin
+ // toggle) mid-flight clears the entry, and the older answer is dropped.
+ const stillCurrent = () => $toolMediaOwners.get()[key]?.request === request
+
+ requestForSessionProfile<{ plugins?: OwnershipRow[] }>(
+ owner,
+ (method, params) => gateway.request(method, params),
+ 'plugins.manage',
+ profile ? { action: 'list', profile } : { action: 'list' }
+ )
.then(result => {
- if ($toolMediaOwners.get().key === key) {
- $toolMediaOwners.set({ key, owners: ownersFromPluginRows(result?.plugins ?? []), status: 'ready' })
+ if (stillCurrent()) {
+ failures.delete(key)
+ setEntry(key, { owners: ownersFromPluginRows(result?.plugins ?? []), request, status: 'ready' })
}
})
.catch(() => {
- if ($toolMediaOwners.get().key === key) {
- $toolMediaOwners.set({ key, status: 'error' })
+ if (stillCurrent()) {
+ setEntry(key, { request, status: 'error' })
+ scheduleRetry(key, stillCurrent)
}
})
}
-// A toggle/install/update in Capabilities reloads `$agentPlugins`: re-read ownership on next use.
-$agentPlugins.listen(() => $toolMediaOwners.set({ key: '', status: 'idle' }))
+// A toggle/install/update in Capabilities reloads `$agentPlugins`: drop every
+// cached list (orphaning in-flight answers) so the next use re-reads ownership.
+$agentPlugins.listen(() => {
+ failures.clear()
+ $toolMediaOwners.set({})
+})
/** The agent package a contribution's plugin is the desktop half of (`plugin:<id>` →
* its record's `packageName`); null for standalone desktop plugins and core. */
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 20315a911e3..796e8766a98 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4444,7 +4444,6 @@ export interface AgentPluginRow {
pinned_sha?: string | null
settings_schema?: PluginSettingField[] | null
tools?: string[]
- tool_prefixes?: string[]
}
export interface PluginServerRow {
name: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index b6e36c12ce7..ac6116ab1bc 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -5083,13 +5083,6 @@
},
"title": "Tools",
"type": "array"
- },
- "tool_prefixes": {
- "items": {
- "type": "string"
- },
- "title": "Tool Prefixes",
- "type": "array"
}
},
"required": [
diff --git a/tests/tui_gateway/test_plugins_manage_tool_ownership.py b/tests/tui_gateway/test_plugins_manage_tool_ownership.py
index a5efe62e50f..dd88030bc1c 100644
--- a/tests/tui_gateway/test_plugins_manage_tool_ownership.py
+++ b/tests/tui_gateway/test_plugins_manage_tool_ownership.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import os
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
from hermes_cli.config import load_config, save_config
@@ -57,7 +58,16 @@ def test_list_reports_only_tools_the_package_itself_registered():
"entries": {"sfx": {"allow_tool_override": True}}}
save_config(cfg)
- with patch("hermes_cli.plugins_cmd_catalog.catalog_rows_maps", return_value=({}, {}, {})):
+ # The package's MCP server as the MCP client records it once connected (no real server here),
+ # plus a config server with a look-alike name that must not count for the package.
+ from tools.mcp_tool_common import _core
+ from tools.mcp_tool_scope import _resolve_server_key
+ connected = {
+ _resolve_server_key("meshy-3d"): SimpleNamespace(_registered_tool_names=["mcp__meshy_3d__download"]),
+ _resolve_server_key("meshy_3d_x"): SimpleNamespace(_registered_tool_names=["mcp__meshy_3d_x__steal"]),
+ }
+ with patch.dict(_core._servers, connected), \
+ patch("hermes_cli.plugins_cmd_catalog.catalog_rows_maps", return_value=({}, {}, {})):
resp = server.handle_request({"id": "1", "method": "plugins.manage", "params": {"action": "list"}})
rows = {row["name"]: row for row in resp["result"]["plugins"]}
@@ -67,7 +77,5 @@ def test_list_reports_only_tools_the_package_itself_registered():
# is never listed on this row.
assert rows["sfx"]["tools"] == ["sfx_make"]
assert rows["other"]["tools"] == ["other_tool"]
- assert rows["sfx"]["tool_prefixes"] == [] and rows["other"]["tool_prefixes"] == []
- # A portable package owns its MCP server's tool namespace (the wire name sanitizes '-').
- assert rows["meshy-ish"]["tools"] == []
- assert rows["meshy-ish"]["tool_prefixes"] == ["mcp__meshy_3d__"]
+ # A portable package owns exactly the tools its own MCP server registered.
+ assert rows["meshy-ish"]["tools"] == ["mcp__meshy_3d__download"]
diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.py
index 49b89e09bd0..21d3fd7ca1c 100644
--- a/tui_gateway/contracts/tools_mcp_plugins.py
+++ b/tui_gateway/contracts/tools_mcp_plugins.py
@@ -713,10 +713,9 @@ class AgentPluginRow(Result):
update_target: str | None = None
pinned_sha: str | None = None
settings_schema: list[PluginSettingField] | None = None
- # Tools this package's own code registered (native names; MCP ``mcp__<server>__`` namespaces):
+ # Exact tool names this package's own code registered (native + its MCP servers' tools):
# Desktop renders a plugin's tool-media renderer only for these.
tools: list[str] = Field(default_factory=list)
- tool_prefixes: list[str] = Field(default_factory=list)
class PluginLiveServer(Result):
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 0aeb6215e91..cab45b0683a 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -1669,7 +1669,7 @@ def _plugin_rows() -> list[dict]:
git_updates = _tools_mod("hermes_cli.plugins_cadence").cached_git_updates(ref_pins)
out = []
active = pc._category_active_names()
- owned_tools, owned_prefixes = _plugin_tool_ownership()
+ owned_tools = _plugin_tool_ownership()
for name, version, desc, source, _dir, key in sorted(pc._discover_all_plugins()):
# Bundled backends/platforms/providers and the live memory provider run without an explicit
# enable: _plugin_status reports the truthful default instead of "not enabled" (reads as OFF).
@@ -1687,8 +1687,8 @@ def _plugin_rows() -> list[dict]:
# Manifest ``config_schema`` + current values: the Plugins hub renders these as a form.
"settings_schema": _tools_mod("hermes_cli.plugins_settings").plugin_settings_fields(key, _dir_path),
"servers": _plugin_server_rows(_dir_path, key, portable=portable, catalog_titles=titles),
- # Tools this package's own code produces: Desktop's tool-media renderer ownership check.
- "tools": owned_tools.get(key, []), "tool_prefixes": owned_prefixes.get(key, []),
+ # Tools this package's own code registered: Desktop's tool-media renderer ownership check.
+ "tools": owned_tools.get(key, []),
**cat.catalog_row_fields(_dir, pins, versions),
**({"update_available": True, "update_target": target}
if _dir_path and (target := git_updates.get(_dir_path.name)) else {}),
diff --git a/tui_gateway/methods_tools_plugin_servers.py b/tui_gateway/methods_tools_plugin_servers.py
index ad6a968e940..701e63a9eef 100644
--- a/tui_gateway/methods_tools_plugin_servers.py
+++ b/tui_gateway/methods_tools_plugin_servers.py
@@ -58,34 +58,33 @@ def _plugin_server_rows(
return rows
-def _plugin_tool_ownership() -> tuple[dict[str, list[str]], dict[str, list[str]]]:
- """Which tools each loaded plugin's OWN code produces, by manifest key: ``(tools, prefixes)``.
+def _plugin_tool_ownership() -> dict[str, list[str]]:
+ """The exact tool names each loaded plugin's OWN code registered, by manifest key.
Desktop lets a plugin's desktop half render media only from these tools, so the answer comes
- from the loader's records, never from a manifest claim. Native: names the plugin registered,
- minus built-in tool names (an approved override of ``text_to_speech`` is still the core voice
- reply to the user) and minus any name two plugins list. Portable: one ``mcp__<server>__``
- prefix per MCP server the loader attributed to the package (duplicate server names are refused
- at load, and a clamped long tool name keeps its prefix)."""
+ from the loader's and the MCP client's records, never from a manifest claim or a name prefix.
+ Native: names the plugin registered, minus built-in tool names (an approved override of
+ ``text_to_speech`` is still the core voice reply to the user). Portable: the tools each MCP
+ server the loader attributed to the package registered (a server that is not connected yet
+ owns nothing until it is). A name two packages list belongs to neither."""
plugins_mod = _tools_mod("hermes_cli.plugins")
toolsets = _tools_mod("toolsets")
- schema = _tools_mod("tools.mcp_tool_schema")
+ core = _tools_mod("tools.mcp_tool_common")._core
+ resolve_key = _tools_mod("tools.mcp_tool_scope")._resolve_server_key
plugins_mod.discover_plugins()
manager = plugins_mod.get_plugin_manager()
builtin = set(toolsets._HERMES_CORE_TOOLS)
for entry in toolsets.TOOLSETS.values():
builtin.update(entry.get("tools", ()))
listed = {key: set(loaded.tools_registered) - builtin for key, loaded in manager._plugins.items()}
+ for server_name, owner in manager.get_portable_mcp_server_plugins().items():
+ server = core._servers.get(resolve_key(server_name))
+ listed.setdefault(owner, set()).update(getattr(server, "_registered_tool_names", None) or ())
seen: dict[str, int] = {}
for names in listed.values():
for name in names:
seen[name] = seen.get(name, 0) + 1
- tools = {key: sorted(n for n in names if seen[n] == 1) for key, names in listed.items()}
- prefixes: dict[str, list[str]] = {}
- for server, owner in manager.get_portable_mcp_server_plugins().items():
- prefix = f"{schema.MCP_TOOL_NAME_PREFIX}{schema.sanitize_mcp_name_component(server)}__"
- prefixes.setdefault(owner, []).append(prefix)
- return tools, {key: sorted(values) for key, values in prefixes.items()}
+ return {key: sorted(n for n in names if seen[n] == 1) for key, names in listed.items()}
def register(server) -> None:
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 1f2d10fae44..54f853808fe 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -1224,9 +1224,10 @@ What the host guarantees:
- **Ownership is provenance, never file type.** A claim counts only for tools
your package's own code registered: native tools from `ctx.register_tool` in
the same package's `plugin.yaml` plugin, or the tools of the MCP servers your
- portable package declares (claim those with a trailing `*`, e.g.
- `mcp__meshy__*`). The backend reports this per package (`plugins.manage
- list` → `tools` / `tool_prefixes`), so a claim on a core tool
+ portable package declares (a trailing `*` matches by prefix, e.g.
+ `mcp__meshy__*`). The backend reports the exact tool names per package
+ (`plugins.manage list` → `tools`, from the chat's own backend and profile),
+ so a claim on a core tool
(`text_to_speech`), another plugin's tool, or from a standalone desktop
plugin with no agent half is refused with a console warning.
- **Everything else keeps the built-in player:** core voice replies, files