Skip to content

The agent that grows with you

feat: installed plugins' MCP tools and skills are live in every open chat, no Connect-now (#119644)

Siddharth Balyan9039b690fc34
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.test.tsx b/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
index 44422b0edcd..5ad620907a2 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.test.tsx
@@ -191,65 +191,4 @@ describe('Install from Git entry flow', () => {
)
)
})
-
- it('offers Connect now for deferred MCP servers and reloads them on click', async () => {
- const { $notifications, dismissNotification } = await import('@/store/notifications')
- probePluginRepo.mockResolvedValue({ ok: true, agent: true, desktop: false, warnings: [] })
- requestGateway.mockImplementation(async (method: string, params?: { action?: unknown }) => {
- if (method === 'plugins.manage' && params?.action === 'install') {
- return {
- ok: true,
- plugin_name: 'nvidia-app',
- plugins: [],
- gateway_reloaded: true,
- activation: { deferred: { mcp_servers: ['nvidia-app'] } }
- }
- }
-
- return { plugins: [] }
- })
- renderFlow()
- act(() => openPluginInstallRequest({ repo: 'https://github.com/example/nvidia-app' }))
- fireEvent.click(await screen.findByRole('button', { name: 'Install' }))
-
- await waitFor(() => {
- const toast = $notifications.get().find(item => item.action?.label === 'Connect now')
- expect(toast).toBeTruthy()
- expect(toast?.message).toBe('nvidia-app installed. Its MCP server is not connected yet.')
- })
-
- const toast = $notifications.get().find(item => item.action?.label === 'Connect now')
- toast?.action?.onClick()
-
- await waitFor(() =>
- expect(requestGateway).toHaveBeenCalledWith('reload.mcp', expect.objectContaining({ confirm: true }))
- )
- await waitFor(() => expect(requestGateway).toHaveBeenCalledWith('plugins.manage', { action: 'list' }))
-
- for (const item of $notifications.get()) {
- dismissNotification(item.id)
- }
- })
-
- it('still offers the gateway restart when the install reports no activation', async () => {
- const { $notifications, dismissNotification } = await import('@/store/notifications')
- probePluginRepo.mockResolvedValue({ ok: true, agent: true, desktop: false, warnings: [] })
- requestGateway.mockImplementation(async method =>
- method === 'plugins.manage' ? { ok: true, plugin_name: 'plugin', plugins: [] } : { plugins: [] }
- )
- renderFlow()
- act(() => openPluginInstallRequest({ repo: 'https://github.com/example/plugin' }))
- fireEvent.click(await screen.findByRole('button', { name: 'Install' }))
-
- await waitFor(() => {
- const toast = $notifications.get().find(item => item.action?.label === 'Restart gateway')
- expect(toast).toBeTruthy()
- expect(toast?.message).toBe('Restart the gateway for the plugin to take effect.')
- })
- expect($notifications.get().some(item => item.action?.label === 'Connect now')).toBe(false)
-
- for (const item of $notifications.get()) {
- dismissNotification(item.id)
- }
- })
})
diff --git a/apps/desktop/src/app/settings/plugin-install-modal.tsx b/apps/desktop/src/app/settings/plugin-install-modal.tsx
index 991990cb05b..f760ea224ac 100644
--- a/apps/desktop/src/app/settings/plugin-install-modal.tsx
+++ b/apps/desktop/src/app/settings/plugin-install-modal.tsx
@@ -23,8 +23,8 @@ import { useI18n } from '@/i18n'
import { ExternalLink } from '@/lib/external-link'
import { AlertTriangle } from '@/lib/icons'
import { resolvePluginSourceLinks } from '@/lib/plugin-source-urls'
-import { COMMIT_SHA_RE, installAgentPlugin, loadAgentPlugins } from '@/store/agent-plugins'
-import { notify, notifyError } from '@/store/notifications'
+import { type AgentPluginLiveNow, COMMIT_SHA_RE, installAgentPlugin, loadAgentPlugins } from '@/store/agent-plugins'
+import { notify } from '@/store/notifications'
import {
$pluginInstallRequest,
closePluginInstallRequest,
@@ -32,13 +32,25 @@ import {
type PluginInstallRequest
} from '@/store/plugin-install-request'
import { $activeGatewayProfile, $profiles, $profileScope, normalizeProfileKey, profileLabel } from '@/store/profile'
-import { $activeSessionId, $connection } from '@/store/session'
-import { runGatewayRestart } from '@/store/system-actions'
+import { $connection } from '@/store/session'
type ProbeResult = Awaited<ReturnType<NonNullable<NonNullable<Window['hermesDesktop']>['probePluginRepo']>>>
type ProbePhase = 'idle' | 'probing' | 'ready' | 'error'
+type InstallModalCopy = ReturnType<typeof useI18n>['t']['settings']['plugins']['installModal']
+
+/** What an agent-plugin install made usable, as toast fragments ("12 tools connected", ...). */
+function installOutcome(m: InstallModalCopy, live: AgentPluginLiveNow, nextChat: boolean): string[] {
+ const tools = live.mcpServers.reduce((n, server) => n + (server.connected ? server.tools.length : 0), 0)
+
+ return [
+ ...(tools > 0 ? [m.toolsConnected(tools)] : []),
+ ...(live.skills.length > 0 ? [m.skillsReady(live.skills)] : []),
+ ...(nextChat ? [m.nextChat] : [])
+ ]
+}
+
export function PluginInstallModal() {
const request = useStore($pluginInstallRequest)
const { t } = useI18n()
@@ -207,9 +219,7 @@ export function PluginInstallModal() {
const errors: string[] = []
const successes: string[] = []
let agentInstalled = false
- let deferredMcpServers: string[] = []
- let gatewayReloaded = false
- let agentPluginName = ''
+ let live: AgentPluginLiveNow = { mcpServers: [], skills: [] }
try {
if (installAgent && probe.agent) {
@@ -223,11 +233,13 @@ export function PluginInstallModal() {
})
if (result.ok) {
- successes.push(m.agentSuccess(result.pluginName ?? request.repo))
+ successes.push(
+ [m.agentSuccess(result.pluginName ?? request.repo), ...installOutcome(m, result.live, result.nextChat)].join(
+ ' · '
+ )
+ )
agentInstalled = true
- deferredMcpServers = result.deferredMcpServers
- gatewayReloaded = result.gatewayReloaded
- agentPluginName = result.pluginName ?? request.repo
+ live = result.live
if (result.missingEnv?.length) {
const firstVar = result.missingEnv[0]
@@ -290,41 +302,10 @@ export function PluginInstallModal() {
notify({ kind: 'success', message })
}
- // The right follow-up depends on what the backend says is live now:
- // deferred MCP servers can be connected in place (reload.mcp), an
- // already-reloaded gateway needs nothing, and only a plugin the
- // gateway did not pick up still needs the restart.
+ // Open chats of the profile already have the plugin's MCP tools and skills (no click).
if (agentInstalled && enableAgent) {
- if (deferredMcpServers.length > 0) {
- notify({
- kind: 'success',
- message: m.connectServers(agentPluginName, deferredMcpServers.length),
- meta: m.connectSub,
- action: {
- label: m.connectNow,
- onClick: () => {
- void (async () => {
- try {
- await requestGateway('reload.mcp', {
- confirm: true,
- session_id: $activeSessionId.get() ?? undefined
- })
- await loadAgentPlugins(requestGateway, targetProfile)
- } catch (err) {
- notifyError(err, m.connectFailed)
- }
- })()
- }
- }
- })
- } else if (gatewayReloaded) {
- notify({ kind: 'success', message: m.liveNow(agentPluginName) })
- } else {
- notify({
- kind: 'success',
- message: m.restartToApply,
- action: { label: m.restartNow, onClick: () => void runGatewayRestart() }
- })
+ for (const server of live.mcpServers.filter(s => !s.connected)) {
+ notify({ kind: 'warning', message: m.serverNotConnected(server.name, server.error || '') })
}
}
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index e7527c732bf..8b50efee12f 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -530,14 +530,10 @@ export const ar = defineLocale({
empty: 'لا توجد إضافات سطح مكتب مثبتة بعد.',
kinds: { bundled: 'مضمّنة', disk: 'على القرص', runtime: 'وقت التشغيل' },
installModal: {
- connectServers: (name, n) =>
- n === 1
- ? `تم تثبيت ${name}. خادم MCP الخاص به لم يتصل بعد.`
- : `تم تثبيت ${name}. خوادم MCP ال${n} الخاصة به لم تتصل بعد.`,
- connectNow: 'الاتصال الآن',
- connectSub: 'الدردشات المفتوحة تعيد إرسال سياقها',
- connectFailed: 'تعذر الاتصال بخوادم MCP الخاصة بالإضافة.',
- liveNow: name => `تم تثبيت ${name} وهو مفعّل.`
+ toolsConnected: n => `تم توصيل ${n} من الأدوات`,
+ skillsReady: names => (names.length === 1 ? `المهارة ${names[0]} جاهزة` : `${names.length} من المهارات جاهزة`),
+ nextChat: 'أدوات أخرى متاحة في دردشتك التالية',
+ serverNotConnected: (server, reason) => `خادم MCP ${server} غير متصل${reason ? `: ${reason}` : '.'}`
}
},
notifications: {
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index a84166f530f..dbc98a57b1b 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -848,16 +848,10 @@ export const en: Translations = {
reviewedHeading: 'Reviewed catalog entry',
reviewedIntro:
'This entry was human-reviewed at its pinned commit. You can still inspect the exact code below.',
- restartToApply: 'Restart the gateway for the plugin to take effect.',
- restartNow: 'Restart gateway',
- connectServers: (name, n) =>
- n === 1
- ? `${name} installed. Its MCP server is not connected yet.`
- : `${name} installed. Its ${n} MCP servers are not connected yet.`,
- connectNow: 'Connect now',
- connectSub: 'Open chats re-send their context',
- connectFailed: 'Could not connect the plugin’s MCP servers.',
- liveNow: name => `${name} installed and active.`,
+ toolsConnected: n => (n === 1 ? '1 tool connected' : `${n} tools connected`),
+ skillsReady: names => (names.length === 1 ? `skill ${names[0]} ready` : `${names.length} skills ready`),
+ nextChat: 'more tools available in your next chat',
+ serverNotConnected: (server, reason) => `MCP server ${server} is not connected${reason ? `: ${reason}` : '.'}`,
missingEnvAction: 'Set it up',
alreadyInstalled: (name: string) => `${name} is already installed.`,
desktopTarget: "Installs into this app's local desktop-plugins folder",
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 7f7f5ab87d9..f4c5f000e58 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -362,14 +362,10 @@ export const ja = defineLocale({
installFromGit: 'Git からインストール',
reviewRepository: 'リポジトリを確認',
repoPlaceholder: 'https://github.com/owner/repo',
- connectServers: (name, n) =>
- n === 1
- ? `${name} をインストールしました。その MCP サーバーはまだ接続されていません。`
- : `${name} をインストールしました。${n} 個の MCP サーバーはまだ接続されていません。`,
- connectNow: '今すぐ接続',
- connectSub: '開いているチャットはコンテキストを再送します',
- connectFailed: 'プラグインの MCP サーバーに接続できませんでした。',
- liveNow: name => `${name} はインストールされ、有効です。`
+ toolsConnected: n => `${n} 個のツールを接続しました`,
+ skillsReady: names => (names.length === 1 ? `スキル ${names[0]} の準備ができました` : `${names.length} 個のスキルの準備ができました`),
+ nextChat: 'ほかのツールは次のチャットで使えます',
+ serverNotConnected: (server, reason) => `MCP サーバー ${server} は接続されていません${reason ? `: ${reason}` : '。'}`
}
},
closeSettings: '設定を閉じる',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index c9056181623..9390ff671bd 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -534,14 +534,10 @@ export const ru = defineLocale({
agentFailed: 'Не удалось установить плагин агента',
desktopFailed: 'Не удалось установить плагин приложения',
missingEnv: (_name, vars) => `Не хватает переменных окружения: ${vars}. Добавьте их в Настройки → Ключи.`,
- connectServers: (name, n) =>
- n === 1
- ? `${name} установлен. Его MCP-сервер ещё не подключён.`
- : `${name} установлен. Его ${n} MCP-сервера ещё не подключены.`,
- connectNow: 'Подключить сейчас',
- connectSub: 'Открытые чаты повторно отправят свой контекст',
- connectFailed: 'Не удалось подключить MCP-серверы плагина.',
- liveNow: name => `${name} установлен и активен.`
+ toolsConnected: n => `Подключено инструментов: ${n}`,
+ skillsReady: names => (names.length === 1 ? `навык ${names[0]} готов` : `готово навыков: ${names.length}`),
+ nextChat: 'остальные инструменты появятся в следующем чате',
+ serverNotConnected: (server, reason) => `MCP-сервер ${server} не подключён${reason ? `: ${reason}` : '.'}`
}
},
notifications: {
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 9204c4db352..1e4129efdda 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -713,13 +713,10 @@ export interface Translations {
catalogPinned: (name: string, sha: string) => string
reviewedHeading: string
reviewedIntro: string
- restartToApply: string
- restartNow: string
- connectServers: (name: string, n: number) => string
- connectNow: string
- connectSub: string
- connectFailed: string
- liveNow: (name: string) => string
+ toolsConnected: (n: number) => string
+ skillsReady: (names: string[]) => string
+ nextChat: string
+ serverNotConnected: (server: string, reason: string) => string
missingEnvAction: string
alreadyInstalled: (name: string) => string
desktopTarget: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 5604145b60e..9334b21273f 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -353,12 +353,10 @@ export const zhHant = defineLocale({
installFromGit: '從 Git 安裝',
reviewRepository: '檢查儲存庫',
repoPlaceholder: 'https://github.com/owner/repo',
- connectServers: (name, n) =>
- n === 1 ? `${name} 已安裝。其 MCP 伺服器尚未連線。` : `${name} 已安裝。其 ${n} 個 MCP 伺服器尚未連線。`,
- connectNow: '立即連線',
- connectSub: '開啟的聊天會重新傳送其上下文',
- connectFailed: '無法連線該外掛的 MCP 伺服器。',
- liveNow: name => `${name} 已安裝並生效。`
+ toolsConnected: n => `已連線 ${n} 個工具`,
+ skillsReady: names => (names.length === 1 ? `技能 ${names[0]} 已就緒` : `${names.length} 個技能已就緒`),
+ nextChat: '更多工具將在下一次聊天中可用',
+ serverNotConnected: (server, reason) => `MCP 伺服器 ${server} 未連線${reason ? `:${reason}` : '。'}`
}
},
closeSettings: '關閉設定',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index b7ff561c6c3..1fa305d758e 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -630,14 +630,10 @@ export const zh = defineLocale({
`Hermes 目录条目「${name}」— agent 部分将安装在经过审核的固定提交${sha ? ` ${sha}` : ''},而不是分支最新代码。`,
reviewedHeading: '经过审核的目录条目',
reviewedIntro: '此条目已在其固定提交处经过人工审核。你仍可在下方检查确切代码。',
- restartToApply: '重启网关后插件才会生效。',
- restartNow: '重启网关',
- connectServers: (name, n) =>
- n === 1 ? `${name} 已安装。其 MCP 服务器尚未连接。` : `${name} 已安装。其 ${n} 个 MCP 服务器尚未连接。`,
- connectNow: '立即连接',
- connectSub: '打开的聊天会重新发送其上下文',
- connectFailed: '无法连接该插件的 MCP 服务器。',
- liveNow: name => `${name} 已安装并生效。`,
+ toolsConnected: n => `已连接 ${n} 个工具`,
+ skillsReady: names => (names.length === 1 ? `技能 ${names[0]} 已就绪` : `${names.length} 个技能已就绪`),
+ nextChat: '更多工具将在下一次聊天中可用',
+ serverNotConnected: (server, reason) => `MCP 服务器 ${server} 未连接${reason ? `:${reason}` : '。'}`,
missingEnvAction: '去设置',
alreadyInstalled: (name: string) => `${name} 已安装。`,
desktopTarget: '安装到此应用的本地 desktop-plugins 文件夹',
diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.ts
index ffe55d48886..3a2f3b1e04a 100644
--- a/apps/desktop/src/store/agent-plugins.ts
+++ b/apps/desktop/src/store/agent-plugins.ts
@@ -241,12 +241,26 @@ export interface AgentPluginInstallResult {
warnings?: string[]
missingEnv?: string[]
error?: string
- /** Plugin MCP servers not connected yet (`activation.deferred.mcp_servers`). */
- deferredMcpServers: string[]
- /** A running gateway already re-wired the plugin's handlers. */
- gatewayReloaded: boolean
+ /** What became usable in open chats of the profile (`activation.live_now`). */
+ live: AgentPluginLiveNow
+ /** Python tools or prompt sections that wait for the next chat (`activation.deferred`). */
+ nextChat: boolean
}
+export interface AgentPluginLiveServer {
+ name: string
+ connected: boolean
+ tools: string[]
+ error?: string | null
+}
+
+export interface AgentPluginLiveNow {
+ mcpServers: AgentPluginLiveServer[]
+ skills: string[]
+}
+
+const NO_LIVE: AgentPluginLiveNow = { mcpServers: [], skills: [] }
+
export async function installAgentPlugin(
request: GatewayRequest,
opts: {
@@ -268,8 +282,13 @@ export async function installAgentPlugin(
plugin_name?: string
warnings?: string[]
missing_env?: string[]
- activation?: { activated_now?: Record<string, string[]>; deferred?: Record<string, string[]> } | null
- gateway_reloaded?: boolean
+ activation?: {
+ live_now?: {
+ mcp_servers?: AgentPluginLiveServer[]
+ skills?: { name: string }[]
+ } | null
+ deferred?: Record<string, string[]>
+ } | null
error?: string
}>(
'plugins.manage',
@@ -287,7 +306,7 @@ export async function installAgentPlugin(
)
if (!result?.ok) {
- return { ok: false, error: result?.error || 'Install failed', deferredMcpServers: [], gatewayReloaded: false }
+ return { ok: false, error: result?.error || 'Install failed', live: NO_LIVE, nextChat: false }
}
return {
@@ -295,15 +314,19 @@ export async function installAgentPlugin(
pluginName: result.plugin_name,
warnings: result.warnings,
missingEnv: result.missing_env,
- deferredMcpServers: result.activation?.deferred?.mcp_servers ?? [],
- gatewayReloaded: Boolean(result.gateway_reloaded)
+ live: {
+ mcpServers: result.activation?.live_now?.mcp_servers ?? [],
+ // `<namespace>:<skill>` is what the model loads; the toast shows the skill's own name.
+ skills: (result.activation?.live_now?.skills ?? []).map(skill => skill.name.split(':').pop() ?? skill.name)
+ },
+ nextChat: Object.keys(result.activation?.deferred ?? {}).length > 0
}
} catch (e) {
return {
ok: false,
error: e instanceof Error ? e.message : String(e),
- deferredMcpServers: [],
- gatewayReloaded: false
+ live: NO_LIVE,
+ nextChat: false
}
}
}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 9aed88a615f..b86a03a3920 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3964,13 +3964,30 @@ export interface PluginSettingField {
has_value?: boolean | null
}
export type PluginSettingFieldType = 'string' | 'number' | 'boolean' | 'enum' | 'secret' | 'json'
-/** What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``), ``{kind: [names]}`` with only non-empty kinds present. ``activated_now`` kinds: ``gateway_commands`` (slash names), ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in the running gateway once it reloaded (``gateway_reloaded``). ``deferred`` kinds: ``tools`` (tool names) and ``prompt`` (section ids) apply from the next session; ``mcp_servers`` lists the plugin's mcp.json server names (exactly as ``mcp.servers.*`` know them) — not connected until ``mcp.reload``. The Desktop "Installed. Connect its servers now" card reads exactly ``deferred.mcp_servers``. */
+/** What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now`` kinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in the running gateway once it reloaded (``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the error) and skills, usable in every open chat of the profile from its next turn — the chats also get a note listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids) apply from the next session. */
export interface PluginActivation {
name: string
key: string
activated_now?: Record<string, string[]>
+ live_now?: PluginLiveNow | null
deferred?: Record<string, string[]>
}
+export interface PluginLiveNow {
+ mcp_servers?: PluginLiveServer[]
+ skills?: PluginLiveSkill[]
+}
+/** One plugin MCP server connected at activation: its callable tool names, or the reason it did not connect. */
+export interface PluginLiveServer {
+ name: string
+ connected: boolean
+ tools?: string[]
+ error?: string | null
+}
+/** One plugin skill usable now through ``skill_view`` (qualified ``<plugin>:<skill>``). */
+export interface PluginLiveSkill {
+ name: string
+ description?: string
+}
/** Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``. ``answers`` rides only on a reconnect replay (locks the server already accepted). */
export interface ClarifyRequestParams {
session_id: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 4bcc18fbd86..87065298e92 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -19742,7 +19742,7 @@
},
"PluginActivation": {
"additionalProperties": false,
- "description": "What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``), ``{kind: [names]}``\nwith only non-empty kinds present. ``activated_now`` kinds: ``gateway_commands`` (slash names),\n``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) \u2014 live in\nthe running gateway once it reloaded (``gateway_reloaded``). ``deferred`` kinds: ``tools`` (tool names) and\n``prompt`` (section ids) apply from the next session; ``mcp_servers`` lists the plugin's mcp.json server\nnames (exactly as ``mcp.servers.*`` know them) \u2014 not connected until ``mcp.reload``.\nThe Desktop \"Installed. Connect its servers now\" card reads exactly ``deferred.mcp_servers``.",
+ "description": "What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now``\nkinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``gateway_transforms`` / ``hooks`` (hook\nnames), ``callbacks`` (platforms / ``slack:<action_id>``) \u2014 live in the running gateway once it reloaded\n(``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the\nerror) and skills, usable in every open chat of the profile from its next turn \u2014 the chats also get a\nnote listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids)\napply from the next session.",
"properties": {
"name": {
"title": "Name",
@@ -19762,6 +19762,17 @@
"title": "Activated Now",
"type": "object"
},
+ "live_now": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/PluginLiveNow"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
"deferred": {
"additionalProperties": {
"items": {
@@ -19780,6 +19791,86 @@
"title": "PluginActivation",
"type": "object"
},
+ "PluginLiveNow": {
+ "additionalProperties": false,
+ "properties": {
+ "mcp_servers": {
+ "items": {
+ "$ref": "#/components/schemas/PluginLiveServer"
+ },
+ "title": "Mcp Servers",
+ "type": "array"
+ },
+ "skills": {
+ "items": {
+ "$ref": "#/components/schemas/PluginLiveSkill"
+ },
+ "title": "Skills",
+ "type": "array"
+ }
+ },
+ "title": "PluginLiveNow",
+ "type": "object"
+ },
+ "PluginLiveServer": {
+ "additionalProperties": false,
+ "description": "One plugin MCP server connected at activation: its callable tool names, or the reason it did not connect.",
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "connected": {
+ "title": "Connected",
+ "type": "boolean"
+ },
+ "tools": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Tools",
+ "type": "array"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Error"
+ }
+ },
+ "required": [
+ "name",
+ "connected"
+ ],
+ "title": "PluginLiveServer",
+ "type": "object"
+ },
+ "PluginLiveSkill": {
+ "additionalProperties": false,
+ "description": "One plugin skill usable now through ``skill_view`` (qualified ``<plugin>:<skill>``).",
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "description": {
+ "default": "",
+ "title": "Description",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "title": "PluginLiveSkill",
+ "type": "object"
+ },
"PluginServerRow": {
"additionalProperties": false,
"properties": {
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 464f6ee9f9d..274deb117fe 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -994,9 +994,10 @@ class PluginContext:
self, name: str, path: Path, description: str = "",
frontmatter: Optional[Mapping[str, Any]] = None,
) -> PluginRegistration:
- """Register a read-only skill resolvable as ``'<plugin_name>:<name>'`` via ``skill_view()``.
- Not in ``~/.hermes/skills/`` nor ``<available_skills>`` — explicit loads only. Raises
- ``ValueError`` (``':'``/invalid chars) or ``FileNotFoundError``."""
+ """Register a read-only skill resolvable as ``'<plugin_name>:<name>'`` via ``skill_view()``
+ and listed by ``skills_list``. Not copied into ``~/.hermes/skills/`` and not in the system
+ prompt's ``<available_skills>``. Raises ``ValueError`` (``':'``/invalid chars) or
+ ``FileNotFoundError``."""
from agent.skill_utils import _NAMESPACE_RE
if ":" in name:
raise ValueError(f"Skill name '{name}' must not contain ':' (the namespace is derived from the "
diff --git a/hermes_cli/plugins_activation.py b/hermes_cli/plugins_activation.py
index 0d73a069f56..54e91c8d355 100644
--- a/hermes_cli/plugins_activation.py
+++ b/hermes_cli/plugins_activation.py
@@ -2,10 +2,12 @@
One seam for every surface: ``PluginManager.on_plugin_loaded`` fires with one
:func:`plugin_activation_summary` per loaded plugin. Gateway handlers (slash commands, transform hooks,
-platform callbacks) are live as soon as the plugin loads; tools, system-prompt sections and portable MCP
-servers stay deferred — tools/prompt to the next session (prompt-cache invariant, same as
-``/skills install``), MCP servers until ``mcp.reload``. :func:`activate_plugin_now` is what the install /
-enable / update surfaces call after a successful config or tree change.
+platform callbacks) are live as soon as the plugin loads; portable MCP servers and skills go live in
+the open chats of the plugin's profile (:func:`load_and_go_live`; MCP tools are deferred behind
+tool_search, so the cached prompt prefix is unchanged); Python tools and system-prompt sections stay
+deferred to the next session (prompt-cache invariant, same as ``/skills install``).
+:func:`activate_plugin_now` is what the install / enable / update surfaces call after a successful
+config or tree change.
"""
from __future__ import annotations
@@ -87,22 +89,20 @@ def find_activation(summaries: Optional[List[Dict[str, Any]]], name: str) -> Opt
def activate_plugin_now(name: str, *, in_process: bool = True) -> Dict[str, Any]:
"""After an install/enable/update: load the plugin in THIS process (so ``on_plugin_loaded``
- subscribers here — the TUI/Desktop server — see it) and nudge the running gateway to do the same
- over its control socket so live adapters re-wire their handlers. Never raises.
+ subscribers here — the TUI/Desktop server — see it), connect its MCP servers and hand them plus
+ its skills to the open chats of this profile (:func:`load_and_go_live`), and nudge the running
+ gateway to load it too over its control socket so live adapters re-wire their handlers. A caller
+ in another process (``hermes plugins install``) passes ``in_process=False``; the running Desktop /
+ dashboard backend is then asked to do the in-process half (:func:`notify_serve_backend`). Never raises.
Returns ``{"gateway_reloaded": bool, "activation": summary | None, "restart_required": bool}``.
- ``restart_required`` is True only when no gateway answered (old gateway, not running): with a
- reload, nothing needs a restart — tools/prompt wait for the next session, MCP servers for
- ``mcp.reload``, and that is what ``activation`` says."""
+ ``activation.live_now`` lists what is usable in open chats now; ``activation.deferred`` what waits
+ for the next session. ``restart_required`` is True only when no gateway answered (old gateway, not
+ running)."""
from hermes_constants import get_hermes_home
- activation: Optional[Dict[str, Any]] = None
- if in_process:
- try:
- from hermes_cli.plugins import discover_plugins, get_plugin_manager
- discover_plugins(force=True)
- activation = find_activation(activation_summaries(get_plugin_manager()), name)
- except Exception:
- logger.debug("in-process plugin reload after change to %r failed", name, exc_info=True)
+ activation: Optional[Dict[str, Any]] = load_and_go_live(name) if in_process else None
+ if not in_process:
+ activation = (notify_serve_backend(name, Path(get_hermes_home())) or {}).get("activation")
answer = None
try:
from gateway.control_socket import reload_gateway_plugins
@@ -121,19 +121,81 @@ def activate_plugin_now(name: str, *, in_process: bool = True) -> Dict[str, Any]
return {"gateway_reloaded": reloaded, "activation": activation, "restart_required": not reloaded}
+def load_and_go_live(name: str) -> Optional[Dict[str, Any]]:
+ """Force-rediscover plugins in THIS process under the caller's profile scope, connect ``name``'s
+ MCP servers and hand them (and its skills) to this profile's open chats with a turn note. Returns
+ the activation summary with ``live_now: {mcp_servers, skills}``; ``deferred`` then keeps only what
+ waits for the next session (Python ``tools``, ``prompt``). None when the plugin did not load."""
+ try:
+ from hermes_cli.plugins import discover_plugins, get_plugin_manager
+ discover_plugins(force=True)
+ activation = find_activation(activation_summaries(get_plugin_manager()), name)
+ except Exception:
+ logger.debug("in-process plugin reload after change to %r failed", name, exc_info=True)
+ return None
+ if activation is None:
+ return None
+ from hermes_cli.plugins_activation_live import connect_plugin_mcp, live_notice, plugin_skills
+ servers = connect_plugin_mcp(activation)
+ activation["live_now"] = {"mcp_servers": servers, "skills": plugin_skills(activation["key"])}
+ activation["deferred"] = {k: v for k, v in (activation.get("deferred") or {}).items() if k != "mcp_servers"}
+ import sys
+ server = sys.modules.get("tui_gateway.server") # loaded == this process hosts chats
+ note = live_notice(activation)
+ if server is not None and (servers or note):
+ from hermes_constants import get_hermes_home
+ try:
+ server.refresh_plugin_sessions(Path(get_hermes_home()), note)
+ except Exception:
+ logger.warning("open chats were not refreshed after activating %r", name, exc_info=True)
+ return activation
+
+
+def notify_serve_backend(name: str, home: Path) -> Optional[Dict[str, Any]]:
+ """Ask the running Desktop / dashboard backend (``hermes serve``, found through its host record) to
+ run :func:`load_and_go_live` for ``name`` in ``home``. None when no backend answers. Never raises."""
+ try:
+ import json
+ import urllib.request
+ from gateway import host_rendezvous as hr
+ record = hr.read_record(hr.ROLE_SERVE)
+ if record is None or not record.port or not hr.record_token_is_consistent(record):
+ return None
+ token = hr.read_token(hr.ROLE_SERVE)
+ request = urllib.request.Request(
+ f"http://{hr.dial_host(record)}:{record.port}/api/dashboard/agent-plugins/activate",
+ data=json.dumps({"name": name, "home": str(home)}).encode("utf-8"), method="POST",
+ headers={"Content-Type": "application/json", "X-Hermes-Session-Token": token})
+ with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 — loopback http
+ return json.loads(response.read().decode("utf-8"))
+ except Exception:
+ logger.debug("serve backend activation for %r failed", name, exc_info=True)
+ return None
+
+
def activation_hint(result: Dict[str, Any]) -> str:
"""One honest sentence for CLI surfaces from an :func:`activate_plugin_now` result."""
- if not result.get("gateway_reloaded"):
- return "Restart the gateway for the plugin to take effect:\n hermes gateway restart"
act = result.get("activation") or {}
+ live = act.get("live_now") or {}
+ connected = [s for s in live.get("mcp_servers") or () if s.get("connected")]
+ lines = []
+ if connected or live.get("skills"):
+ tools = sum(len(s.get("tools") or ()) for s in connected)
+ lines.append(f"Live in open chats now: {tools} MCP tools, {len(live.get('skills') or ())} skills.")
+ lines.extend(f"MCP server {s['name']} not connected: {s.get('error') or 'unknown error'}"
+ for s in live.get("mcp_servers") or () if not s.get("connected"))
+ if not result.get("gateway_reloaded"):
+ if lines: # live in open chats; a messaging gateway that starts later loads it at boot
+ return "\n".join(lines)
+ return "\n".join([*lines, "Restart the gateway for the plugin to take effect:\n hermes gateway restart"])
now, deferred = act.get("activated_now") or {}, act.get("deferred") or {}
parts = []
if now:
parts.append("active in the running gateway now: " + ", ".join(sorted(now)))
if deferred:
labels: Dict[str, str] = {"tools": "tools (next session)", "prompt": "system prompt (next session)",
- "mcp_servers": "MCP servers (mcp.reload / next session)"}
+ "mcp_servers": "MCP servers (next session)"}
parts.append("deferred: " + ", ".join(labels.get(k, k) for k in sorted(deferred)))
if not parts:
- return "Gateway reloaded plugins; nothing of this plugin needs a session or restart."
- return "Gateway reloaded plugins — " + "; ".join(parts) + "."
+ return "\n".join([*lines, "Gateway reloaded plugins; nothing of this plugin needs a session or restart."])
+ return "\n".join([*lines, "Gateway reloaded plugins — " + "; ".join(parts) + "."])
diff --git a/hermes_cli/plugins_activation_live.py b/hermes_cli/plugins_activation_live.py
new file mode 100644
index 00000000000..feb6356aa85
--- /dev/null
+++ b/hermes_cli/plugins_activation_live.py
@@ -0,0 +1,132 @@
+"""Make an installed plugin's MCP servers and skills usable in THIS process now (#87770 follow-up).
+
+:func:`hermes_cli.plugins_activation.activate_plugin_now` loads the plugin; skills are live from that
+point (``skill_view`` resolves ``<plugin>:<skill>``). MCP servers are not: nothing connects them until
+``reload.mcp``. :func:`connect_plugin_mcp` connects the plugin's servers one by one (the connector
+flow's ``register_mcp_servers({name: config})``), and :func:`live_notice` renders what became usable
+as the note an open chat receives on its next turn.
+
+MCP tools are deferred behind ``tool_search`` / ``tool_describe`` / ``tool_call``, so adding them to a
+live session leaves the model-facing tool array (and the cached prompt prefix) byte-identical.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+def connect_plugin_mcp(activation: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Connect every portable MCP server ``activation`` defers, under the caller's profile scope.
+
+ Returns ``[{name, connected, tools, error?}]``, one row per server; a server that fails to
+ connect is reported, never retried. Never raises."""
+ names = list((activation.get("deferred") or {}).get("mcp_servers") or ())
+ if not names:
+ return []
+ try:
+ from hermes_cli.plugins import get_plugin_manager
+ from tools.mcp_tool_config import _filter_suspicious_mcp_servers, _load_mcp_config
+ from tools.mcp_tool_discovery import register_mcp_servers
+ configured = _load_mcp_config()
+ portable = get_plugin_manager().get_portable_mcp_servers()
+ except Exception as exc:
+ logger.warning("plugin MCP activation could not read server config: %s", exc)
+ return [{"name": n, "connected": False, "tools": [], "error": str(exc)} for n in names]
+ rows = []
+ for name in names:
+ config = configured.get(name) or _filter_suspicious_mcp_servers(
+ {name: portable[name]} if name in portable else {}).get(name)
+ if not isinstance(config, dict):
+ rows.append({"name": name, "connected": False, "tools": [], "error": "no MCP configuration"})
+ continue
+ try:
+ register_mcp_servers({name: config})
+ from tools.connectors.mcp import _registered_tool_names
+ tools = [t for t in _registered_tool_names(name) if not t.endswith(_utility_suffixes())]
+ except Exception as exc:
+ rows.append({"name": name, "connected": False, "tools": [], "error": str(exc)})
+ continue
+ row: Dict[str, Any] = {"name": name, "connected": bool(tools), "tools": tools}
+ if not tools:
+ row["error"] = _server_error(name) or "the server did not connect"
+ rows.append(row)
+ return rows
+
+
+def _utility_suffixes() -> tuple:
+ """The resource/prompt wrappers every MCP server gets (``mcp__x__list_resources``, ...): callable,
+ but they say nothing about what the plugin does, so they are left out of counts and listings."""
+ from tools.mcp_tool_registration import _UTILITY_HANDLER_FACTORIES
+ return tuple(f"_{kind}" for kind in _UTILITY_HANDLER_FACTORIES)
+
+
+def _server_error(name: str) -> Optional[str]:
+ try:
+ from tools.mcp_tool_discovery import get_mcp_status
+ for entry in get_mcp_status():
+ if entry.get("name") == name:
+ return entry.get("error")
+ except Exception:
+ return None
+ return None
+
+
+def plugin_skills(plugin_key: str) -> List[Dict[str, str]]:
+ """``[{name, description}]`` for the skills ``plugin_key`` registered (qualified ``<ns>:<skill>``)."""
+ try:
+ from hermes_cli.plugins import get_plugin_manager
+ skills = get_plugin_manager()._plugin_skills
+ except Exception:
+ return []
+ return [{"name": qualified, "description": str(entry.get("description") or "")}
+ for qualified, entry in sorted(skills.items()) if entry.get("plugin_key") == plugin_key]
+
+
+def live_notice(activation: Dict[str, Any]) -> str:
+ """The note an open chat gets on its next turn: connected MCP servers with their tools, skills,
+ and what waits for the next session. Empty when nothing became usable."""
+ live = activation.get("live_now") or {}
+ servers, skills = live.get("mcp_servers") or [], live.get("skills") or []
+ deferred = activation.get("deferred") or {}
+ if not servers and not skills:
+ return ""
+ lines = [f"[plugin installed: {activation.get('name') or activation.get('key')}]"]
+ connected = [s for s in servers if s.get("connected")]
+ if connected:
+ lines.append("MCP servers now connected; call their tools with tool_describe / tool_call:")
+ for server in connected:
+ lines.append(f"- {server['name']}")
+ listing = _tool_listing(server["tools"])
+ if listing:
+ lines.extend(f" {line}" for line in listing.splitlines())
+ for server in (s for s in servers if not s.get("connected")):
+ lines.append(f"- {server['name']}: not connected ({server.get('error') or 'unknown error'})")
+ if skills:
+ lines.append("Skills now available; load one with skill_view:")
+ lines.extend(f"- {s['name']}: {s['description']}" if s.get("description") else f"- {s['name']}"
+ for s in skills)
+ later = [f"{len(deferred['tools'])} Python tools" if deferred.get("tools") else "",
+ f"{len(deferred['prompt'])} prompt sections" if deferred.get("prompt") else ""]
+ if any(later):
+ lines.append("Next session: " + ", ".join(p for p in later if p) + ".")
+ return "\n".join(lines)
+
+
+def _tool_listing(names: List[str]) -> str:
+ """``name: first sentence`` per tool."""
+ try:
+ from tools.registry import registry
+ from tools.tool_search_catalog import _short_desc
+ definitions = registry.get_definitions(set(names), quiet=True)
+ except Exception:
+ return ""
+ rows = []
+ for definition in definitions:
+ fn = definition.get("function") or definition
+ name = str(fn.get("name") or "")
+ if name:
+ desc = _short_desc(fn.get("description") or "")
+ rows.append(f"{name}: {desc}" if desc else name)
+ return "\n".join(sorted(rows))
diff --git a/hermes_cli/web_routers/dashboard_ui.py b/hermes_cli/web_routers/dashboard_ui.py
index 83ad205d1bd..acf3ecbf791 100644
--- a/hermes_cli/web_routers/dashboard_ui.py
+++ b/hermes_cli/web_routers/dashboard_ui.py
@@ -287,6 +287,33 @@ async def delete_agent_plugin(request: Request, name: str):
return await _named_plugin_action(request, name, dashboard_remove_user_plugin, "Remove failed.", rescan=True)
[email protected]("/api/dashboard/agent-plugins/activate")
+async def post_agent_plugin_activate(request: Request):
+ """``hermes plugins install`` / ``enable`` in another process asks this backend to load the plugin
+ for ``home`` and hand its MCP servers and skills to that profile's open chats
+ (``hermes_cli.plugins_activation.load_and_go_live``). ``home`` must be a profile this host serves."""
+ _require_token(request)
+ try:
+ body = await request.json()
+ except Exception:
+ body = {}
+ name = _validate_plugin_name(str((body or {}).get("name") or ""))
+ from hermes_constants import get_hermes_home, hermes_home_key, profile_name_for_home
+ home = Path(str((body or {}).get("home") or "")).expanduser()
+ profile = profile_name_for_home(home) if str(home) not in ("", ".") else None
+ if profile is None:
+ raise HTTPException(status_code=400, detail="Not a Hermes profile home.")
+ from hermes_cli.plugins_activation import load_and_go_live
+
+ def _run():
+ with _config_profile_scope(None if profile == "default" else profile):
+ if hermes_home_key(get_hermes_home()) != hermes_home_key(home):
+ raise HTTPException(status_code=400, detail="Home is not served by this backend.")
+ return {"ok": True, "activation": load_and_go_live(name)}
+
+ return await asyncio.to_thread(_run)
+
+
@router.put("/api/dashboard/plugin-providers")
async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody,
profile: Optional[str] = None):
diff --git a/tests/tui_gateway/test_plugins_manage_late_activation.py b/tests/tui_gateway/test_plugins_manage_late_activation.py
index 83ed5eb51a6..4982fd81b4f 100644
--- a/tests/tui_gateway/test_plugins_manage_late_activation.py
+++ b/tests/tui_gateway/test_plugins_manage_late_activation.py
@@ -1,7 +1,7 @@
"""#87770 — a Desktop/TUI ``plugins.manage install`` is a mid-run load path too: the install performs a REAL
forced rescan in the serving process, ``PluginManager.on_plugin_loaded`` fires from inside it for the newcomer,
-and the RESULT carries the activation summary (live now vs deferred, ``deferred.mcp_servers`` naming the
-plugin's mcp.json servers) plus ``gateway_reloaded`` / ``restart_required``.
+and the RESULT carries the activation summary (``live_now.mcp_servers`` naming the plugin's mcp.json servers,
+connected in place) plus ``gateway_reloaded`` / ``restart_required``.
The broken invariant: before, ``_plugins_install`` returned with no rescan, so a later non-forced
``discover_plugins()`` (``tools/mcp_tool_config._portable_mcp_servers`` → ``reload.mcp``) short-circuited on
@@ -40,12 +40,14 @@ def test_plugins_manage_install_rescans_fires_on_plugin_loaded_and_exposes_mcp_s
manager.on_plugin_loaded(events.append)
with patch("hermes_cli.plugins_cmd._install_plugin_core", _fake_install_core), \
patch("hermes_cli.plugins_cmd._install_python_dependencies_quietly", return_value=[]), \
- patch("gateway.control_socket.reload_gateway_plugins", return_value=None): # no gateway running
+ patch("gateway.control_socket.reload_gateway_plugins", return_value=None), \
+ patch("tools.mcp_tool_discovery.register_mcp_servers", return_value=[]), \
+ patch("tools.connectors.mcp._registered_tool_names", return_value=[]): # no gateway, no real server
resp = server.handle_request({"id": "1", "method": "plugins.manage",
"params": {"action": "install", "repo": "owner/late-mcp", "enable": True}})
result = resp["result"]
assert [e["name"] for e in events[-1]] == ["late-mcp"] # fired from inside the rescan, newcomer only
- servers = result["activation"]["deferred"]["mcp_servers"]
+ servers = [row["name"] for row in result["activation"]["live_now"]["mcp_servers"]]
assert servers == ["worker"] # exactly the mcp.json name, as mcp.servers.* know it
assert result["gateway_reloaded"] is False and result["restart_required"] is True
# The invariant that was broken: a later NON-forced discovery (what reload.mcp runs) sees the servers.
diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.py
index e0777657768..ff7be024ef9 100644
--- a/tui_gateway/contracts/tools_mcp_plugins.py
+++ b/tui_gateway/contracts/tools_mcp_plugins.py
@@ -671,18 +671,40 @@ class AgentPluginRow(Result):
settings_schema: list[PluginSettingField] | None = None
+class PluginLiveServer(Result):
+ """One plugin MCP server connected at activation: its callable tool names, or the reason it did not connect."""
+
+ name: str
+ connected: bool
+ tools: list[str] = Field(default_factory=list)
+ error: str | None = None
+
+
+class PluginLiveSkill(Result):
+ """One plugin skill usable now through ``skill_view`` (qualified ``<plugin>:<skill>``)."""
+
+ name: str
+ description: str = ""
+
+
+class PluginLiveNow(Result):
+ mcp_servers: list[PluginLiveServer] = Field(default_factory=list)
+ skills: list[PluginLiveSkill] = Field(default_factory=list)
+
+
class PluginActivation(Result):
- """What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``), ``{kind: [names]}``
- with only non-empty kinds present. ``activated_now`` kinds: ``gateway_commands`` (slash names),
- ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in
- the running gateway once it reloaded (``gateway_reloaded``). ``deferred`` kinds: ``tools`` (tool names) and
- ``prompt`` (section ids) apply from the next session; ``mcp_servers`` lists the plugin's mcp.json server
- names (exactly as ``mcp.servers.*`` know them) — not connected until ``mcp.reload``.
- The Desktop "Installed. Connect its servers now" card reads exactly ``deferred.mcp_servers``."""
+ """What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now``
+ kinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``gateway_transforms`` / ``hooks`` (hook
+ names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in the running gateway once it reloaded
+ (``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the
+ error) and skills, usable in every open chat of the profile from its next turn — the chats also get a
+ note listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids)
+ apply from the next session."""
name: str
key: str
activated_now: dict[str, list[str]] = Field(default_factory=dict)
+ live_now: PluginLiveNow | None = None
deferred: dict[str, list[str]] = Field(default_factory=dict)
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 9208e0189eb..fb1720a0606 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -289,6 +289,44 @@ def _mcp_reload_confirm_required() -> bool:
return True
+def _refresh_live_sessions(home=None, *, preserve_prefix: bool = False, note: str = "") -> None:
+ """Rebuild live sessions' cached tool snapshots from the registry and push session.info (agents
+ never re-read the registry). The MCP pool is process-global, so refreshing only the requester
+ would leave sibling sessions on stale tools until /new — and a request without a resolvable
+ session_id (desktop passes ``activeSessionId ?? undefined``) would refresh nothing while still
+ answering "reloaded". ``enabled_override`` re-resolves toolsets so a server enabled this session
+ (config or a just-installed plugin) is in the session's ``tool_call`` scope.
+
+ ``home``: only sessions of that profile home (a session with no ``profile_home`` belongs to the
+ launch home). ``preserve_prefix``: append-only rebuild inside a live conversation. ``note``: queued
+ for each session's next turn on the one-shot turn-note channel (``agent/turn_context.py``)."""
+ from hermes_constants import hermes_home_key
+ want = hermes_home_key(home) if home is not None else None
+ with _sessions_lock:
+ live = [(sid, sess) for sid, sess in _sessions.items() if sess.get("agent") is not None and (
+ want is None or hermes_home_key(sess.get("profile_home") or get_process_hermes_home()) == want)]
+ refresh = _tools_mod("tools.mcp_tool_agent").refresh_agent_mcp_tools
+ for sid, sess in live:
+ agent = sess["agent"]
+ try:
+ with _session_profile_runtime_scope(sess):
+ enabled = _load_enabled_toolsets(getattr(agent, "platform", None))
+ refresh(agent, enabled_override=enabled, quiet_mode=True, preserve_prefix=preserve_prefix)
+ except Exception as _exc:
+ logger.warning("Failed to refresh cached agent tools (session %s): %s", sid, _exc)
+ if note:
+ prior = getattr(agent, "_gateway_turn_context_notes", "") or ""
+ agent._gateway_turn_context_notes = f"{prior}\n\n{note}" if prior else note
+ _emit("session.info", sid, _session_info(agent, sess))
+
+
+def refresh_plugin_sessions(home, note: str) -> None:
+ """A plugin just went live in ``home``: append its MCP tools to that profile's open chats (deferred
+ behind tool_search, so the model-facing tool array is unchanged) and queue ``note`` for their next
+ turn. Called by ``hermes_cli.plugins_activation_live``."""
+ _refresh_live_sessions(home, preserve_prefix=True, note=note)
+
+
@_rpc("reload.mcp", 5015)
def _(rid, params: dict) -> dict:
session = _sessions.get(params.get("session_id", ""))
@@ -315,22 +353,8 @@ def _(rid, params: dict) -> dict:
req_rev = str(params.get("rev") or "")
def _refresh_session_agent() -> None:
- """Rebuild EVERY live session's cached tool snapshot + push session.info (agents never
- re-read the registry). The MCP pool is process-global, so refreshing only the requester
- would leave sibling sessions on stale tools until /new — and a request without a
- resolvable session_id (desktop passes ``activeSessionId ?? undefined``) would refresh
- nothing while still answering "reloaded". Runs under _mcp_reload_lock so a concurrent
- reload can't tear the registry down mid-refresh."""
- with _sessions_lock:
- live = [(sid, sess) for sid, sess in _sessions.items() if sess.get("agent") is not None]
- for sid, sess in live:
- agent = sess["agent"]
- try: # enabled_override re-resolves toolsets so a server enabled in config this session is picked up
- with _session_profile_runtime_scope(sess):
- _mcp_agent.refresh_agent_mcp_tools(agent, enabled_override=_load_enabled_toolsets(), quiet_mode=True)
- except Exception as _exc:
- logger.warning("Failed to refresh cached agent tools after /reload-mcp (session %s): %s", sid, _exc)
- _emit("session.info", sid, _session_info(agent, sess))
+ """Runs under _mcp_reload_lock so a concurrent reload can't tear the registry down mid-refresh."""
+ _refresh_live_sessions()
def _do_full_reload() -> None:
"""shutdown+discover+refresh under the lock, then mark a completed generation. Config
@@ -1558,7 +1582,10 @@ def _ensure_plugin_activation_listener() -> None:
def _with_activation(result: dict, name: str) -> dict:
- """Prefer the summary this process's listener captured over the core's own copy."""
+ """Fill ``activation`` from this process's listener when the core returned none (the core's own
+ copy carries ``live_now``, which the listener's load-time summary cannot)."""
+ if result.get("activation"):
+ return result
for key in (name, result.get("plugin_name"), result.get("name")):
if key and key in _plugin_activations:
result["activation"] = _plugin_activations[key]