The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a new MCP server reaches a session as a committed policy generation
unsupportedpastels41c58ee5d9bf
diff --git a/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.ts b/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.tsindex e198d4f9b58..21dab0b2261 100644--- a/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.ts+++ b/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.ts@@ -15,6 +15,7 @@ import {import { useI18n } from '@/i18n'import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'import { probeCache, probeKey } from '@/lib/mcp-probe-cache'+import { announceMcpReload, reloadMcp } from '@/lib/mcp-reload'import { getServers, type McpServerEntry, type McpServers } from '@/lib/mcp-servers'import { setDisabledTools, toggleToolInServer } from '@/lib/mcp-tool-filter'import { notify, notifyError } from '@/store/notifications'@@ -151,7 +152,7 @@ export function useMcpServers({ gateway, profile }: UseMcpServersOptions): McpSe}try {- await gateway.request('reload.mcp', { confirm: true, session_id: activeSessionId ?? undefined })+ announceMcpReload(await reloadMcp(gateway, activeSessionId))} catch (err) {notifyError(err, m.reloadFailed)}diff --git a/apps/desktop/src/i18n/ar_boot.ts b/apps/desktop/src/i18n/ar_boot.tsindex 54924b032fa..7827be66ed7 100644--- a/apps/desktop/src/i18n/ar_boot.ts+++ b/apps/desktop/src/i18n/ar_boot.ts@@ -77,6 +77,10 @@ export const arBoot = {promptNotices: {legacySendUnconfirmed:'تعذّر على هذا الخادم تأكيد الإرسال السابق لهذه الرسالة، لذا ربما تم تنفيذها بالفعل. راجع المحادثة قبل إرسالها مرة أخرى.',+ mcpReloadDeferred:+ 'هذه المحادثة مشغولة: يُطبَّق تغيير MCP بعد انتهاء دورها وإعادة تحميل MCP مجددًا، أو عند إعادة فتح المحادثة',+ mcpReloadNotInChat: server => `${server} غير مفعّل في هذه المحادثة`,+ mcpReloadUnavailable: servers => `تعذّر الاتصال: ${servers}`,sessionCommands: arSessionCommands},updates: {diff --git a/apps/desktop/src/i18n/de_notices.ts b/apps/desktop/src/i18n/de_notices.tsindex f33a765ccb9..b9f77a80ea9 100644--- a/apps/desktop/src/i18n/de_notices.ts+++ b/apps/desktop/src/i18n/de_notices.ts@@ -20,6 +20,10 @@ export const deNotices = {promptNotices: {legacySendUnconfirmed:'Dieser Server konnte das frühere Senden dieser Nachricht nicht bestätigen; sie wurde möglicherweise bereits ausgeführt. Prüfe die Unterhaltung, bevor du sie erneut sendest.',+ mcpReloadDeferred:+ 'Dieser Chat ist beschäftigt: Die MCP-Änderung gilt, sobald sein Durchlauf endet und MCP erneut geladen wird, oder wenn du den Chat wieder öffnest',+ mcpReloadNotInChat: server => `${server} ist in diesem Chat nicht aktiviert`,+ mcpReloadUnavailable: servers => `Keine Verbindung: ${servers}`,sessionCommands: deSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/i18n/en_notices.ts b/apps/desktop/src/i18n/en_notices.tsindex 1938b20da46..cbad0c6a8cd 100644--- a/apps/desktop/src/i18n/en_notices.ts+++ b/apps/desktop/src/i18n/en_notices.ts@@ -20,6 +20,10 @@ export const enNotices = {promptNotices: {legacySendUnconfirmed:'This server could not confirm the earlier send of this message, so it may already have run. Check the conversation before sending it again.',+ mcpReloadDeferred:+ 'This chat is busy: the MCP change applies once its turn finishes and MCP reloads again, or when you reopen the chat',+ mcpReloadNotInChat: server => `${server} is not enabled in this chat`,+ mcpReloadUnavailable: servers => `Did not connect: ${servers}`,sessionCommands: enSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/i18n/es_notices.ts b/apps/desktop/src/i18n/es_notices.tsindex abf5112dcfa..e0b9911392f 100644--- a/apps/desktop/src/i18n/es_notices.ts+++ b/apps/desktop/src/i18n/es_notices.ts@@ -20,6 +20,10 @@ export const esNotices = {promptNotices: {legacySendUnconfirmed:'Este servidor no pudo confirmar el envío anterior de este mensaje, así que es posible que ya se haya ejecutado. Revisa la conversación antes de volver a enviarlo.',+ mcpReloadDeferred:+ 'Este chat está ocupado: el cambio de MCP se aplica cuando termine su turno y MCP se recargue de nuevo, o al volver a abrir el chat',+ mcpReloadNotInChat: server => `${server} no está activado en este chat`,+ mcpReloadUnavailable: servers => `No se conectó: ${servers}`,sessionCommands: esSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/i18n/fr_notices.ts b/apps/desktop/src/i18n/fr_notices.tsindex b13120cf1dd..1bcddc6f491 100644--- a/apps/desktop/src/i18n/fr_notices.ts+++ b/apps/desktop/src/i18n/fr_notices.ts@@ -20,6 +20,10 @@ export const frNotices = {promptNotices: {legacySendUnconfirmed:"Ce serveur n'a pas pu confirmer l'envoi précédent de ce message ; il a peut-être déjà été exécuté. Vérifiez la conversation avant de le renvoyer.",+ mcpReloadDeferred:+ 'Cette discussion est occupée : la modification MCP s’applique à la fin de son tour et au prochain rechargement MCP, ou à la réouverture de la discussion',+ mcpReloadNotInChat: server => `${server} n’est pas activé dans cette discussion`,+ mcpReloadUnavailable: servers => `Connexion impossible : ${servers}`,sessionCommands: frSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/i18n/ja_notices.ts b/apps/desktop/src/i18n/ja_notices.tsindex 3e832557ed7..61b95abbe53 100644--- a/apps/desktop/src/i18n/ja_notices.ts+++ b/apps/desktop/src/i18n/ja_notices.ts@@ -20,6 +20,10 @@ export const jaNotices = {promptNotices: {legacySendUnconfirmed:'このサーバーはこのメッセージの前回の送信を確認できなかったため、すでに実行された可能性があります。再送信する前に会話を確認してください。',+ mcpReloadDeferred:+ 'このチャットは処理中です。MCP の変更は現在のターンが終わって MCP を再読み込みしたとき、またはチャットを開き直したときに反映されます',+ mcpReloadNotInChat: server => `${server} はこのチャットでは有効になっていません`,+ mcpReloadUnavailable: servers => `接続できませんでした: ${servers}`,sessionCommands: jaSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/i18n/ru_notices.ts b/apps/desktop/src/i18n/ru_notices.tsindex e154fb9b65a..857327584cc 100644--- a/apps/desktop/src/i18n/ru_notices.ts+++ b/apps/desktop/src/i18n/ru_notices.ts@@ -20,6 +20,10 @@ export const ruNotices = {promptNotices: {legacySendUnconfirmed:'Этот сервер не смог подтвердить предыдущую отправку этого сообщения, поэтому оно, возможно, уже выполнено. Проверьте беседу, прежде чем отправлять его снова.',+ mcpReloadDeferred:+ 'Чат занят: изменение MCP применится, когда завершится текущий ход и MCP будет перезагружен снова, или при повторном открытии чата',+ mcpReloadNotInChat: server => `${server} не включён в этом чате`,+ mcpReloadUnavailable: servers => `Не удалось подключиться: ${servers}`,sessionCommands: ruSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/i18n/types_notices.ts b/apps/desktop/src/i18n/types_notices.tsindex 121e85cc193..6e9302fa943 100644--- a/apps/desktop/src/i18n/types_notices.ts+++ b/apps/desktop/src/i18n/types_notices.ts@@ -13,6 +13,12 @@ export interface NoticeTranslations {promptNotices: {/** An explicit retry of a send whose identityless (legacy) acknowledgement was lost. */legacySendUnconfirmed: string+ /** reload.mcp left the chat's servers as they were: a turn was running or waiting. */+ mcpReloadDeferred: string+ /** A reloaded MCP server the chat does not run (no_mcp, an explicit pick, a platform allowlist). */+ mcpReloadNotInChat: (server: string) => string+ /** Configured MCP servers that did not connect on reload. */+ mcpReloadUnavailable: (servers: string) => string/** Typed /undo /retry /steer /queue lines (the Ink TUI's wording on the same gateway). */sessionCommands: SessionCommandNotices}diff --git a/apps/desktop/src/i18n/zh-hant_boot.ts b/apps/desktop/src/i18n/zh-hant_boot.tsindex 94308fe225e..79ad7cd94e1 100644--- a/apps/desktop/src/i18n/zh-hant_boot.ts+++ b/apps/desktop/src/i18n/zh-hant_boot.ts@@ -79,6 +79,9 @@ export const zhHantBoot = {},promptNotices: {legacySendUnconfirmed: '此伺服器無法確認這則訊息先前的傳送,它可能已經執行過。再次傳送前請先查看對話。',+ mcpReloadDeferred: '此對話正忙:MCP 變更會在目前輪次結束並再次重新載入 MCP 後生效,或在重新開啟對話時生效',+ mcpReloadNotInChat: server => `此對話未啟用 ${server}`,+ mcpReloadUnavailable: servers => `未能連線:${servers}`,sessionCommands: zhHantSessionCommands},diff --git a/apps/desktop/src/i18n/zh_notices.ts b/apps/desktop/src/i18n/zh_notices.tsindex 360c7165538..eaedcd41ad3 100644--- a/apps/desktop/src/i18n/zh_notices.ts+++ b/apps/desktop/src/i18n/zh_notices.ts@@ -18,6 +18,9 @@ export const zhNotices = {},promptNotices: {legacySendUnconfirmed: '此服务器无法确认这条消息之前的发送,它可能已经运行过。再次发送前请先查看对话。',+ mcpReloadDeferred: '此对话正忙:MCP 更改将在当前轮次结束并再次重新加载 MCP 后生效,或在重新打开对话时生效',+ mcpReloadNotInChat: server => `此对话未启用 ${server}`,+ mcpReloadUnavailable: servers => `未能连接:${servers}`,sessionCommands: zhSessionCommands},keepAwakeOffer: {diff --git a/apps/desktop/src/lib/mcp-reload.test.ts b/apps/desktop/src/lib/mcp-reload.test.tsnew file mode 100644index 00000000000..68f53fa7fc9--- /dev/null+++ b/apps/desktop/src/lib/mcp-reload.test.ts@@ -0,0 +1,79 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { announceMcpReload, reloadMcp, reloadMcpFor } from './mcp-reload'++const mocks = vi.hoisted(() => ({ gateway: null as unknown, notify: vi.fn() }))++vi.mock('@/store/gateway', () => ({ $gateway: { get: () => mocks.gateway } }))+vi.mock('@/store/notifications', () => ({ notify: mocks.notify }))++// The Capabilities save path: reload, then tell the user what did not take effect.+const save = async (result: unknown) => {+ const request = vi.fn().mockResolvedValue(result)+ announceMcpReload(await reloadMcp({ request } as never, 's1'))++ return request+}++describe('a saved MCP change reports what the chat got', () => {+ beforeEach(() => mocks.notify.mockReset())++ it('stays quiet when the chat runs the change', async () => {+ const request = await save({ session: 'applied', status: 'reloaded' })++ expect(request).toHaveBeenCalledWith('reload.mcp', { confirm: true, session_id: 's1' })+ expect(mocks.notify).not.toHaveBeenCalled()+ })++ it('says the change is deferred while the chat is busy, and when it applies', async () => {+ await save({ session: 'busy', status: 'reloaded' })++ expect(mocks.notify).toHaveBeenCalledTimes(1)+ expect(mocks.notify).toHaveBeenCalledWith(+ expect.objectContaining({ message: expect.stringMatching(/busy.*(turn|reopen)/i) })+ )+ })++ it('names every server that did not connect beside a partial success', async () => {+ await save({ session: 'applied', status: 'reloaded', unavailable: ['broken', 'gone'] })++ expect(mocks.notify).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'warning', message: expect.stringContaining('broken, gone') })+ )+ })++ it('reports both a deferral and an unavailable server', async () => {+ await save({ session: 'busy', status: 'reloaded', unavailable: ['broken'] })++ expect(mocks.notify).toHaveBeenCalledTimes(2)+ })++ it('lets a refused reload reach the caller', async () => {+ const request = vi.fn().mockRejectedValue(new Error('mcp_servers_unavailable'))++ await expect(reloadMcp({ request } as never, null)).rejects.toThrow('mcp_servers_unavailable')+ expect(request).toHaveBeenCalledWith('reload.mcp', { confirm: true, session_id: undefined })+ })+})++describe('a flow that claims a server is live in the chat', () => {+ const claim = (result: unknown) => {+ mocks.gateway = { request: vi.fn().mockResolvedValue(result) }++ return reloadMcpFor('fixt', 's1')+ }++ beforeEach(() => mocks.notify.mockReset())++ it('resolves once the chat runs the server', async () => {+ await expect(claim({ session: 'applied', session_servers: ['fixt'], status: 'reloaded' })).resolves.toBeUndefined()+ })++ it('refuses when the chat does not run that server (no_mcp, an explicit pick, an allowlist)', async () => {+ await expect(claim({ session: 'unchanged', session_servers: [], status: 'reloaded' })).rejects.toThrow(/fixt/)+ })++ it('keeps the earlier answer from a gateway that does not report the selection', async () => {+ await expect(claim({ session: 'applied', status: 'reloaded' })).resolves.toBeUndefined()+ })+})diff --git a/apps/desktop/src/lib/mcp-reload.ts b/apps/desktop/src/lib/mcp-reload.tsnew file mode 100644index 00000000000..8907dd198be--- /dev/null+++ b/apps/desktop/src/lib/mcp-reload.ts@@ -0,0 +1,84 @@+import type { ReloadMcpResult } from '@hermes/shared'++import type { HermesGateway } from '@/hermes'+import { translateNow } from '@/i18n'+import { $gateway } from '@/store/gateway'+import { notify } from '@/store/notifications'++/**+ * What `reload.mcp` did for the chat that asked. The gateway decides and commits; Desktop only reads its+ * answer, so a successful RPC envelope alone never means the chat got the change.+ */+export interface McpReloadOutcome {+ /** A turn was running or queued: the chat keeps its servers until the turn finishes and MCP reloads+ * again, or until it is reopened. */+ deferred: boolean+ /** Configured servers that did not connect, beside whatever did apply. */+ unavailable: string[]+ /** The MCP servers the chat's committed policy runs; null from a gateway that does not report them. */+ sessionServers: null | string[]+}++/** The change has not reached the chat yet; the user already has the deferral notice. */+export class McpReloadDeferred extends Error {}++export async function reloadMcp(+ gateway: Pick<HermesGateway, 'request'>,+ sessionId: null | string | undefined+): Promise<McpReloadOutcome> {+ const result = await gateway.request<ReloadMcpResult>('reload.mcp', {+ confirm: true,+ session_id: sessionId ?? undefined+ })++ return {+ deferred: result?.session === 'busy',+ sessionServers: result?.session_servers ?? null,+ unavailable: result?.unavailable ?? []+ }+}++/** Tell the user what did not take effect: a deferred chat, and servers (other than `skip`) that did not+ * connect. */+export function announceMcpReload(outcome: McpReloadOutcome, skip: readonly string[] = []): void {+ if (outcome.deferred) {+ notify({ id: 'mcp-reload-deferred', kind: 'info', message: translateNow('promptNotices.mcpReloadDeferred') })+ }++ const unavailable = outcome.unavailable.filter(name => !skip.includes(name))++ if (unavailable.length > 0) {+ notify({+ id: 'mcp-reload-unavailable',+ kind: 'warning',+ message: translateNow('promptNotices.mcpReloadUnavailable', unavailable.join(', ')),+ title: translateNow('settings.mcp.reloadFailed')+ })+ }+}++/** For a flow that claims `server` is live in the chat (connect, reconnect): resolves only once it is;+ * rejects with {@link McpReloadDeferred} while a turn defers it, or an error when it did not connect. */+export async function reloadMcpFor(server: string, sessionId: null | string | undefined): Promise<void> {+ const gateway = $gateway.get()++ if (!gateway) {+ throw new Error(translateNow('settings.mcp.reloadFailed'))+ }++ const outcome = await reloadMcp(gateway, sessionId)+ announceMcpReload(outcome, [server])++ if (outcome.unavailable.includes(server)) {+ throw new Error(translateNow('promptNotices.mcpReloadUnavailable', server))+ }++ if (outcome.deferred) {+ throw new McpReloadDeferred(translateNow('promptNotices.mcpReloadDeferred'))+ }++ // Connected for the profile is not enabled in this chat (no_mcp, an explicit pick, a platform allowlist).+ if (outcome.sessionServers && !outcome.sessionServers.includes(server)) {+ throw new Error(translateNow('promptNotices.mcpReloadNotInChat', server))+ }+}diff --git a/apps/desktop/src/store/suggestion-providers/mcp.test.ts b/apps/desktop/src/store/suggestion-providers/mcp.test.tsindex 51cc49c2802..881e887b1f1 100644--- a/apps/desktop/src/store/suggestion-providers/mcp.test.ts+++ b/apps/desktop/src/store/suggestion-providers/mcp.test.ts@@ -1,7 +1,108 @@-import { describe, expect, it } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { ComposerSuggestion } from '@/store/composer-suggestions'import { buildMcpSuggestionIndex, matchSuggestions } from './mcp'+type DraftProvider = (context: { sessionId: string | null; text: string }) => Promise<ComposerSuggestion[]>++const mocks = vi.hoisted(() => ({+ notify: vi.fn(),+ notifyError: vi.fn(),+ provider: null as DraftProvider | null,+ removeMcpServer: vi.fn(async () => {}),+ request: vi.fn()+}))++vi.mock('@/api/client', () => ({ capabilityScoped: () => undefined }))+vi.mock('@/hermes', () => ({+ addMcpServer: async () => {},+ getMcpCatalog: async () => ({+ entries: [+ {+ auth_type: 'oauth',+ name: 'hosted',+ suggest: { hosts: [], keywords: ['hosted'] },+ transport: 'http',+ url: 'https://mcp.example.test'+ }+ ]+ }),+ listMcpServers: async () => ({ servers: [] }),+ removeMcpServer: mocks.removeMcpServer+}))+vi.mock('@/lib/mcp-dashboard-oauth', () => ({+ completeMcpDesktopOAuth: async () => ({ tools: [] }),+ McpOAuthCancelled: class extends Error {}+}))+vi.mock('@/store/composer-suggestions', () => ({+ registerDraftProvider: (_name: string, provider: DraftProvider) => {+ mocks.provider = provider+ }+}))+vi.mock('@/store/gateway', () => ({ $gateway: { get: () => ({ request: mocks.request }) } }))+vi.mock('@/store/notifications', () => ({ notify: mocks.notify, notifyError: mocks.notifyError }))++describe('connect reads what reload.mcp did for the chat', () => {+ const connect = async () => {+ const [suggestion] = await mocks.provider!({ sessionId: 's1', text: 'use the hosted board ' })++ return suggestion!.invoke({ cancelled: () => false, sessionId: 's1' })+ }++ beforeEach(() => {+ mocks.notify.mockReset()+ mocks.notifyError.mockReset()+ mocks.request.mockReset()+ })++ it('claims success once the chat runs the new server', async () => {+ mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded' })++ await connect()++ expect(mocks.request).toHaveBeenCalledWith('reload.mcp', { confirm: true, session_id: 's1' })+ expect(mocks.notify).not.toHaveBeenCalled()+ expect(mocks.notifyError).not.toHaveBeenCalled()+ })++ it('does not claim the chat has the server while its turn defers the change', async () => {+ mocks.request.mockResolvedValue({ session: 'busy', status: 'reloaded' })++ await expect(connect()).rejects.toThrow()++ expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringMatching(/busy/i) }))+ expect(mocks.notifyError).not.toHaveBeenCalled()+ })++ it('fails when the new server is among those that did not connect', async () => {+ mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded', unavailable: ['hosted'] })++ await expect(connect()).rejects.toThrow(/hosted/)++ expect(mocks.notifyError).toHaveBeenCalled()+ })++ it('fails when the reload is refused', async () => {+ mocks.request.mockRejectedValue(new Error('mcp_servers_unavailable: did not connect: hosted'))++ await expect(connect()).rejects.toThrow()++ expect(mocks.notifyError).toHaveBeenCalled()+ })++ it('succeeds beside another server that did not connect, and names it', async () => {+ mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded', unavailable: ['linear'] })++ await connect()++ expect(mocks.notify).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'warning', message: expect.stringContaining('linear') })+ )+ expect(mocks.notifyError).not.toHaveBeenCalled()+ })+})+it('does not send local-app or non-OAuth catalog suggestions through the hosted OAuth-only composer flow', () => {const hosted = {name: 'hosted',diff --git a/apps/desktop/src/store/suggestion-providers/mcp.ts b/apps/desktop/src/store/suggestion-providers/mcp.tsindex 17fca6c589a..4b5ee9dbdae 100644--- a/apps/desktop/src/store/suggestion-providers/mcp.ts+++ b/apps/desktop/src/store/suggestion-providers/mcp.ts@@ -2,9 +2,9 @@ import { capabilityScoped } from '@/api/client'import { addMcpServer, getMcpCatalog, listMcpServers, removeMcpServer } from '@/hermes'import { translateNow } from '@/i18n'import { completeMcpDesktopOAuth, McpOAuthCancelled } from '@/lib/mcp-dashboard-oauth'+import { McpReloadDeferred, reloadMcpFor } from '@/lib/mcp-reload'import { prettyName } from '@/lib/text'import { type ComposerSuggestion, registerDraftProvider } from '@/store/composer-suggestions'-import { $gateway } from '@/store/gateway'import { notifyError } from '@/store/notifications'import type { McpCatalogEntry } from '@/types/hermes'@@ -201,16 +201,12 @@ async function connect(known: SuggestibleServer, sessionId: string | null, cancethrow error}- // Tools reach the live session before the pill claims success — the- // same write-through the Capabilities tab and the setup card use.- await $gateway- .get()- ?.request('reload.mcp', { confirm: true, session_id: sessionId ?? undefined })- .catch(() => {})-invalidateMcpSuggestionIndex()+ // The pill claims success only once the chat runs the server: not while a+ // turn defers the change, and not when the server did not connect.+ await reloadMcpFor(known.server, sessionId)} catch (error) {- if (!(error instanceof McpOAuthCancelled)) {+ if (!(error instanceof McpOAuthCancelled || error instanceof McpReloadDeferred)) {notifyError(error, translateNow('composer.mcpSuggestions.connectFailed', prettyName(known.server)))}diff --git a/apps/desktop/src/store/suggestion-providers/repair.test.ts b/apps/desktop/src/store/suggestion-providers/repair.test.tsindex 23408798532..771f49454e4 100644--- a/apps/desktop/src/store/suggestion-providers/repair.test.ts+++ b/apps/desktop/src/store/suggestion-providers/repair.test.ts@@ -1,6 +1,28 @@-import { describe, expect, it } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'-import { mcpServerFromToolName, REPAIR_RE } from './repair'+import type { ComposerSuggestion } from '@/store/composer-suggestions'++import { mcpServerFromToolName, REPAIR_RE, reportMcpToolResult } from './repair'++const mocks = vi.hoisted(() => ({+ notify: vi.fn(),+ notifyError: vi.fn(),+ offers: [] as ComposerSuggestion[][],+ request: vi.fn()+}))++vi.mock('@/hermes', () => ({ listMcpServers: async () => ({ servers: [{ name: 'figma' }] }) }))+vi.mock('@/lib/mcp-dashboard-oauth', () => ({+ completeMcpDesktopOAuth: async () => ({ tools: [] }),+ McpOAuthCancelled: class extends Error {}+}))+vi.mock('@/store/composer-suggestions', () => ({+ offerSuggestions: (_sessionId: unknown, _provider: string, suggestions: ComposerSuggestion[]) => {+ mocks.offers.push(suggestions)+ }+}))+vi.mock('@/store/gateway', () => ({ $gateway: { get: () => ({ request: mocks.request }) } }))+vi.mock('@/store/notifications', () => ({ notify: mocks.notify, notifyError: mocks.notifyError }))describe('mcpServerFromToolName', () => {it('extracts the server from a namespaced MCP tool', () => {@@ -42,3 +64,81 @@ describe('REPAIR_RE', () => {expect(REPAIR_RE.test(text)).toBe(false)})})++describe('reconnect reads what reload.mcp did for the chat', () => {+ let session = 0++ // A fresh chat with a failed figma call: the offer it raises.+ const offered = async (): Promise<{ sessionId: string; suggestion: ComposerSuggestion }> => {+ const sessionId = `s${++session}`+ reportMcpToolResult(sessionId, 'mcp__figma__get_design_context', true, 'HTTP 401 Unauthorized')+ await vi.waitFor(() => expect(mocks.offers.at(-1)).toHaveLength(1))++ return { sessionId, suggestion: mocks.offers.at(-1)![0]! }+ }++ const invoke = ({ sessionId, suggestion }: { sessionId: string; suggestion: ComposerSuggestion }) =>+ suggestion.invoke({ cancelled: () => false, sessionId })++ beforeEach(() => {+ mocks.offers.length = 0+ mocks.notify.mockReset()+ mocks.notifyError.mockReset()+ mocks.request.mockReset()+ })++ it('withdraws the offer once the chat runs the reconnected server', async () => {+ const pill = await offered()+ mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded' })++ await invoke(pill)++ expect(mocks.request).toHaveBeenCalledWith('reload.mcp', { confirm: true, session_id: pill.sessionId })+ expect(mocks.offers.at(-1)).toEqual([])+ })++ it('keeps the offer and says so when the chat is busy and the change is deferred', async () => {+ const pill = await offered()+ const before = mocks.offers.length+ mocks.request.mockResolvedValue({ session: 'busy', status: 'reloaded' })++ await expect(invoke(pill)).rejects.toThrow()++ expect(mocks.offers).toHaveLength(before)+ expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringMatching(/busy/i) }))+ expect(mocks.notifyError).not.toHaveBeenCalled()+ })++ it('keeps the offer when the server still did not connect', async () => {+ const pill = await offered()+ const before = mocks.offers.length+ mocks.request.mockResolvedValue({ session: 'applied', status: 'reloaded', unavailable: ['figma'] })++ await expect(invoke(pill)).rejects.toThrow(/figma/)++ expect(mocks.offers).toHaveLength(before)+ expect(mocks.notifyError).toHaveBeenCalled()+ })++ it('keeps the offer when the reload itself is refused', async () => {+ const pill = await offered()+ const before = mocks.offers.length+ mocks.request.mockRejectedValue(new Error('mcp_servers_unavailable: did not connect: figma'))++ await expect(invoke(pill)).rejects.toThrow()++ expect(mocks.offers).toHaveLength(before)+ })++ it('withdraws its own offer but names another server that did not connect', async () => {+ const pill = await offered()+ mocks.request.mockResolvedValue({ session: 'unchanged', status: 'reloaded', unavailable: ['linear'] })++ await invoke(pill)++ expect(mocks.offers.at(-1)).toEqual([])+ expect(mocks.notify).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'warning', message: expect.stringContaining('linear') })+ )+ })+})diff --git a/apps/desktop/src/store/suggestion-providers/repair.ts b/apps/desktop/src/store/suggestion-providers/repair.tsindex 8b0c54d6bfd..c932448a5bd 100644--- a/apps/desktop/src/store/suggestion-providers/repair.ts+++ b/apps/desktop/src/store/suggestion-providers/repair.ts@@ -1,9 +1,9 @@import { listMcpServers } from '@/hermes'import { translateNow } from '@/i18n'import { completeMcpDesktopOAuth, McpOAuthCancelled } from '@/lib/mcp-dashboard-oauth'+import { McpReloadDeferred, reloadMcpFor } from '@/lib/mcp-reload'import { prettyName } from '@/lib/text'import { type ComposerSuggestion, offerSuggestions } from '@/store/composer-suggestions'-import { $gateway } from '@/store/gateway'import { notifyError } from '@/store/notifications'/**@@ -43,15 +43,12 @@ async function reconnect(server: string, sessionId: string | null, cancelled: ()cancelled})- // Fresh tokens reach the live session before the pill claims success.- await $gateway- .get()- ?.request('reload.mcp', { confirm: true, session_id: sessionId ?? undefined })- .catch(() => {})-+ // The offer stays until the chat runs the reconnected server: a deferred+ // change or a server that still did not connect keeps it.+ await reloadMcpFor(server, sessionId)clearMcpFailure(sessionId, server)} catch (error) {- if (!(error instanceof McpOAuthCancelled)) {+ if (!(error instanceof McpOAuthCancelled || error instanceof McpReloadDeferred)) {notifyError(error, translateNow('composer.repairSuggestions.failed', prettyName(server)))}diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 7071a56f6b1..5bd19e218b9 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4041,6 +4041,7 @@ export interface ReloadMcpParams {always?: booleanrev?: string | null}+/** ``session``: what the calling local session's MCP servers did (a new policy generation, nothing to change, or deferred while a turn runs or waits); ``unavailable``: configured servers that did not connect beside what did apply; ``session_servers``: the MCP servers that session's committed policy runs. */export interface ReloadMcpResult {status: ReloadMcpStatusmessage?: string | null@@ -4048,8 +4049,12 @@ export interface ReloadMcpResult {coalesced?: boolean | nullturn_isolation?: boolean | nullhost_ack?: unknown | null+ session?: ReloadMcpSession | null+ unavailable?: string[] | null+ session_servers?: string[] | null}export type ReloadMcpStatus = 'confirm_required' | 'reloaded'+export type ReloadMcpSession = 'applied' | 'unchanged' | 'busy'/** ``query`` is the search text / hub identifier / browse page (digits); ``page`` / ``page_size`` apply to ``browse``. */export interface SkillsManageParams {profile?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 4d8e9967d8d..4659f80afed 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -32146,6 +32146,7 @@},"ReloadMcpResult": {"additionalProperties": false,+ "description": "``session``: what the calling local session's MCP servers did (a new policy generation, nothing to\nchange, or deferred while a turn runs or waits); ``unavailable``: configured servers that did not connect\nbeside what did apply; ``session_servers``: the MCP servers that session's committed policy runs.","properties": {"status": {"$ref": "#/components/schemas/ReloadMcpStatus"@@ -32207,6 +32208,47 @@],"default": null,"title": "Host Ack"+ },+ "session": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/ReloadMcpSession"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "unavailable": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Unavailable"+ },+ "session_servers": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Session Servers"}},"required": [@@ -32215,6 +32257,15 @@"title": "ReloadMcpResult","type": "object"},+ "ReloadMcpSession": {+ "enum": [+ "applied",+ "unchanged",+ "busy"+ ],+ "title": "ReloadMcpSession",+ "type": "string"+ },"ReloadMcpStatus": {"enum": ["confirm_required",diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex eee8cc4ee82..5b75fff23a3 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -665,10 +665,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewaydef _scoped_server_names() -> set:with _lock:- return {- _key_name(key) for key in _servers- if _server_visible_in_scope(key, reload_scope)- }+ return {_key_name(key) for key in _servers if _server_visible_in_scope(key, reload_scope)}old_servers = _scoped_server_names()await self._run_in_executor_with_context(lambda: shutdown_mcp_servers(scope=reload_scope))@@ -694,10 +691,12 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewaylines = [t("gateway.reload_mcp.header")] + [t(key, names=", ".join(sorted(names))) for _label, key, names in changes if names]- if not connected_servers:- lines.append(t("gateway.reload_mcp.none_connected"))- else:- lines.append(t("gateway.reload_mcp.tools_available", tools=len(new_tools), servers=len(connected_servers)))+ from tools.mcp_tool_discovery import mcp_servers_not_connected+ failed = await self._run_in_executor_with_context(mcp_servers_not_connected)+ lines.append(t("gateway.reload_mcp.none_connected") if not connected_servers else t(+ "gateway.reload_mcp.tools_available", tools=len(new_tools), servers=len(connected_servers)))+ if failed: # a configured server that did not connect is named, never passed over as success+ lines.append(t("gateway.reload_mcp.failed", error=f"did not connect: {', '.join(failed)}"))self._mcp_reload_refresh_cached_agents(multiplex, event.source.profile)diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex 0dd46c1e341..9d323e5bc34 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -251,7 +251,11 @@ async def kill_process(connection, ref, params):async def reload_mcp(connection, ref, params):"""Desktop's MCP add / toggle / repair: bring THIS profile's live MCP servers in step with itsconfig (the owner's housekeeping reconcile, run now) and refresh this profile's cached agents.- Never the sidecar's teardown of every server, which cut every chat's in-flight MCP calls."""+ Never the sidecar's teardown of every server, which cut every chat's in-flight MCP calls. The calling+ session's MCP servers then change as a new policy generation when it is idle (``session``: applied,+ unchanged or busy); other sessions take theirs when next attached. A configured server that did not+ connect is named: a refusal when nothing took effect (no server registered or removed, no session+ generation), else ``unavailable`` beside the success."""if set(params) - {'session_id', 'confirm', 'rev', 'profile'}:raise RuntimeStoreError('invalid_params')if 'session:control' not in connection.actor.capabilities:@@ -259,18 +263,60 @@ async def reload_mcp(connection, ref, params):if params.get('confirm') is not True:return {'status': 'confirm_required', 'message': 'Reloading MCP refreshes every chat of this profile.'}from tools.mcp_oauth import suppress_interactive_oauth- from tools.mcp_tool_discovery import reconcile_mcp_servers_with_config+ from tools import mcp_tool_discovery as discoverydef reconcile():with suppress_interactive_oauth():- return reconcile_mcp_servers_with_config()- result = await asyncio.to_thread(reconcile)+ return discovery.reconcile_mcp_servers_with_config(), discovery.mcp_servers_not_connected()+ result, failed = await asyncio.to_thread(reconcile)+ # ``added`` is what reconcile attempted: only those now registered (live or lazy) changed anything.+ result = {**result, 'added': [name for name in result.get('added', []) if name not in failed]}from gateway.session_authorities import served_profile_namerunner = connection.authority.runnermultiplex = bool(getattr(runner.config, 'multiplex_profiles', False))runner._mcp_reload_refresh_cached_agents(multiplex, served_profile_name(connection.authority.profile_id))+ session = await _commit_session_mcp(connection, ref, params)+ if failed and session != 'applied' and not (result.get('removed') or result['added']):+ raise RuntimeStoreError('mcp_servers_unavailable', field='mcp_servers',+ detail=f'did not connect: {", ".join(failed)}')changed = ', '.join(f'{k}: {", ".join(v)}' for k, v in result.items() if v) or 'no server changes'- return {'status': 'reloaded', 'message': f'MCP servers reconciled ({changed})'}+ note = {'applied': '; this chat\'s tools changed for its next turn',+ 'busy': '; this chat is busy: its new tools apply once the turn finishes and reload runs again '+ 'or the chat is reopened'}.get(session or '', '')+ unavailable = f'; did not connect: {", ".join(failed)}' if failed else ''+ selected = {'session_servers': await asyncio.to_thread(_session_servers, connection.authority, ref.session_id)+ } if session else {}+ return {'status': 'reloaded', 'message': f'MCP servers reconciled ({changed}){note}{unavailable}',+ **({'session': session} if session else {}), **({'unavailable': failed} if failed else {}), **selected}+++def _session_servers(authority, sid):+ """The profile MCP servers the session's committed policy runs (its toolsets name them): a server connected+ for the profile is not one a chat with ``no_mcp``, an explicit pick or a platform allowlist enabled."""+ import json+ from gateway.session_policy import restore_policy+ from hermes_cli.tools_config import enabled_mcp_server_names+ from hermes_state_local import local_receipt+ policy = restore_policy(local_receipt(authority.db, sid)['policy'])+ return sorted(set(policy.toolsets) & enabled_mcp_server_names(json.loads(policy.config_json)))+++async def _commit_session_mcp(connection, ref, params):+ """The calling local session's MCP servers as a gateway-committed generation (``commit_refresh``):+ never a running or queued turn's, never another session's."""+ from gateway.config import Platform+ authority, sid = connection.authority, getattr(ref, 'session_id', None)+ live = authority.sessions.get(sid) if sid else None+ if live is None or live.source is None or live.source.platform != Platform.LOCAL:+ return None+ authorize(connection, ref, params, 'session:control')+ from gateway.session_policy_refresh import commit_refresh+ try:+ return 'applied' if await commit_refresh(authority, ref, mcp_only=True) else 'unchanged'+ except RuntimeStoreError as exc:+ if exc.reason not in {'session_busy', 'unknown_execution', 'revision_conflict'}:+ raise+ return 'busy'async def stop_processes(connection, ref, params):diff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.pyindex 6d3cab0198f..3aca9ad97ac 100644--- a/gateway/session_policy_refresh.py+++ b/gateway/session_policy_refresh.py@@ -1,11 +1,11 @@-"""A resumed local session re-reads its config-derived settings (CFG-2).--Main's ``hermes -c`` was a new process: toolsets, ``terminal.backend``, ``max_turns``, checkpoints and the-reasoning default came from the config it started with, while the stored session kept its model/provider.-The owner keeps that line on ``session.resume``: it re-derives exactly those fields from the session-profile's current config and commits them as a new policy generation. The creation flags (request_json),-the model route and a committed ``/reasoning`` pick stay; a session with a turn running or queued keeps the-policy that turn was admitted under.+"""A resumed local session re-reads its config-derived settings (CFG-2); its MCP servers change the same way (CFG-3).++Main's ``hermes -c`` was a new process: toolsets, MCP servers, ``terminal.backend``, ``max_turns``, checkpoints+and the reasoning default came from the config it started with, while the stored session kept its model/provider.+The owner keeps that line on ``session.resume``: it re-derives exactly those fields from the session profile's+current config and commits them as a new policy generation. ``reload.mcp`` commits the MCP part alone for the+calling session. The creation flags (request_json), the model route and a committed ``/reasoning`` or workspace+pick stay; a session with a turn running or queued keeps the policy that turn was admitted under."""import asyncioimport json@@ -24,15 +24,33 @@ def _follow(target, live, key):target.pop(key, None)-def refreshed_policy(policy, live, terminal, *, picked=()):- """``(policy, terminal_secrets)``: *policy* with its config-derived fields from *live* (the profile's- config) and *terminal* (its terminal scope); explicit picks (launch flags, the *picked* policy edits)- stay. *policy* itself when nothing moved."""- from gateway.session_policy import (_extract_config_secrets, _resolve_toolsets, present_sections,- terminal_uses_host_cwd)- request = json.loads(policy.request_json)+def refreshed_policy(policy, live, terminal, *, picked=(), mcp_only=False):+ """``(policy, secrets, replaced)``: *policy* with its config-derived fields from *live* (the profile's+ config) and *terminal* (its terminal scope), or only its MCP servers (*mcp_only*); explicit picks (launch+ flags, the *picked* policy edits) stay. *secrets* are the refreshed sections' private values, *replaced*+ the sections (``None``: terminal) whose stored private values they supersede. *policy* itself when+ nothing moved."""+ from gateway.session_policy import _extract_config_secrets, present_sectionsold, config = json.loads(policy.config_json), json.loads(policy.config_json)- live = present_sections(live)+ live, secrets, replaced = present_sections(live), {}, set()+ if mcp_only:+ toolsets, terminal = policy.toolsets, json.loads(policy.terminal_json)+ else:+ toolsets = _settings(policy, config, live, picked)+ terminal = _terminal(policy, terminal, picked)+ _extract_config_secrets(terminal, secrets, (None,))+ replaced.add(None)+ toolsets = _mcp_servers(policy, config, live, toolsets, secrets, replaced)+ if config == old and toolsets == policy.toolsets and terminal == json.loads(policy.terminal_json):+ return policy, {}, set()+ policy = replace(policy, toolsets=toolsets, config_json=json.dumps(config), terminal_json=json.dumps(terminal))+ return policy, secrets, replaced+++def _settings(policy, config, live, picked):+ """Follow the config-derived settings into *config*; the toolsets they select."""+ from gateway.session_policy import _resolve_toolsets+ request = json.loads(policy.request_json)live_agent = live.get('agent') or {}agent = dict(config.get('agent') or {})keys = [] if 'max_turns' in request else ['max_turns']@@ -53,18 +71,46 @@ def refreshed_policy(policy, live, terminal, *, picked=()):section = config.get('checkpoints')section = dict(section) if isinstance(section, dict) else {'enabled': bool(section)} if section else {}config['checkpoints'] = {**section, 'enabled': True}- terminal, secrets = dict(terminal), {}+ return toolsets+++def _terminal(policy, terminal, picked):+ from gateway.session_policy import terminal_uses_host_cwd+ terminal, request = dict(terminal), json.loads(policy.request_json)# The session's own folder, where it now is, under build_policy's rule; a committed Move to project is# the user's pick on every backend (it rewrote the policy, never the launch request).if request.get('cwd_explicit') is True or 'workspace' in picked or terminal_uses_host_cwd(terminal):terminal['TERMINAL_CWD'] = policy.cwd- _extract_config_secrets(terminal, secrets, (None,))- if config == old and toolsets == policy.toolsets and terminal == json.loads(policy.terminal_json):- return policy, {}- return replace(policy, toolsets=toolsets, config_json=json.dumps(config), terminal_json=json.dumps(terminal)), secrets+ return terminal-def _prepare(authority, session_id):+def _mcp_servers(policy, config, live, toolsets, secrets, replaced):+ """The profile's MCP servers as this session's own selection takes them now (its explicit pick or platform+ allowlist, ``no_mcp`` and disabled entries respected): their definitions into *config*, private values split+ off as build_policy does (a managed worker binds this config, so it connects exactly these), and their+ names into the returned toolsets. An editor-MCP session keeps its frozen servers."""+ from gateway.session_policy import _extract_config_secrets, _resolve_toolsets+ from hermes_cli.tools_config import enabled_mcp_server_names+ from hermes_state_runtime import RuntimeStoreError+ if policy.editor_mcp_json is not None:+ return toolsets+ request = json.loads(policy.request_json)+ try:+ selected = _resolve_toolsets({'toolsets': request['toolsets']} if 'toolsets' in request else {},+ json.loads(json.dumps(live)), policy.source, policy.safe_mode, policy.coding_posture)+ except RuntimeStoreError:+ return toolsets # the launch pick no longer validates against the profile: keep the frozen servers+ sections = [section if isinstance(section, dict) else {} for section in (config.get('mcp_servers'), live.get('mcp_servers'))]+ if 'mcp_servers' in live:+ config['mcp_servers'] = json.loads(json.dumps(live['mcp_servers']))+ _extract_config_secrets(config['mcp_servers'], secrets, ('mcp_servers',))+ else:+ config.pop('mcp_servers', None)+ replaced.add('mcp_servers')+ return tuple(sorted((set(toolsets) - set(sections[0]) - set(sections[1])) | (selected & enabled_mcp_server_names(live))))+++def _prepare(authority, session_id, mcp_only=False):"""Off the owner loop: the stored policy, its refresh from this profile home's files, and the generationit was derived at. None when the session takes no refresh or nothing moved."""from gateway.run import _load_gateway_config@@ -79,41 +125,48 @@ def _prepare(authority, session_id):if old.ignore_user_config or old.source not in SURFACES:return Nonehome = Path(authority.db.db_path).resolve().parent- policy, secrets = refreshed_policy(old, _load_gateway_config(home / 'config.yaml'),- build_profile_terminal_scope(home),- picked=policy_picks(authority.db, session_id))- return None if policy == old else (stored, old, policy, secrets, generation)+ terminal = {} if mcp_only else build_profile_terminal_scope(home)+ policy, secrets, replaced = refreshed_policy(old, _load_gateway_config(home / 'config.yaml'), terminal,+ picked=policy_picks(authority.db, session_id), mcp_only=mcp_only)+ return None if policy == old else (stored, old, policy, secrets, replaced, generation)-def _rebind(authority, session_id, old, policy, terminal_secrets):- """Re-bind the private values like a policy mutation: policy identity covers config and terminal, and- the terminal's own secrets are the profile's current ones."""+def _rebind(authority, session_id, old, policy, fresh, replaced):+ """Re-bind the private values like a policy mutation: policy identity covers config and terminal, and the+ refreshed sections' private values are the profile's current ones."""from gateway.session_policy import bind_launch_key, launch_keyfrom gateway.session_policy_credentials import recover_config_secretssecrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}- secrets = {path: value for path, value in secrets.items() if path[0] is not None}- secrets.update(terminal_secrets)+ secrets = {path: value for path, value in secrets.items() if path[0] not in replaced}+ secrets.update(fresh)return bind_launch_key(authority, session_id, policy, launch_key(authority, old), config_secrets=secrets)+async def commit_refresh(authority, ref, *, mcp_only=False):+ """Commit an idle local session's refresh as its next policy generation: True when one was committed,+ False when nothing moved. Raises the store's refusal (``session_busy`` while a turn runs or waits)."""+ from gateway.session_runtime_workers import tracked_write+ from hermes_state_mutation_prepared import commit_refreshed_policy+ prepared = await asyncio.to_thread(_prepare, authority, ref.session_id, mcp_only)+ if prepared is None:+ return False+ stored, old, policy, secrets, replaced, generation = prepared+ policy = _rebind(authority, ref.session_id, old, policy, secrets, replaced)+ # Compare-and-swap against the receipt as stored (JSON lists), not its restored tuple form. The+ # publication is the commit's own shielded follow-up: a caller cancelled mid-commit cannot leave the+ # stored policy ahead of the live one (restore_local_session refuses that pair).+ await tracked_write(authority, partial(commit_refreshed_policy, authority.db, epoch=authority.epoch,+ session_id=ref.session_id, old=stored, new=asdict(policy),+ generation=generation),+ then=lambda _generation: _publish(authority, ref))+ return True++async def refresh_resumed_policy(authority, ref):"""Commit the config refresh of an idle local session before it is attached. Never fails the resume:a busy session, a revoked launch credential or an unreadable profile keeps the stored policy."""- from gateway.session_runtime_workers import tracked_write- from hermes_state_mutation_prepared import commit_refreshed_policytry:- prepared = await asyncio.to_thread(_prepare, authority, ref.session_id)- if prepared is None:- return- stored, old, policy, secrets, generation = prepared- policy = _rebind(authority, ref.session_id, old, policy, secrets)- # Compare-and-swap against the receipt as stored (JSON lists), not its restored tuple form. The- # publication is the commit's own shielded follow-up: a caller cancelled mid-commit cannot leave the- # stored policy ahead of the live one (restore_local_session refuses that pair).- await tracked_write(authority, partial(commit_refreshed_policy, authority.db, epoch=authority.epoch,- session_id=ref.session_id, old=stored, new=asdict(policy),- generation=generation),- then=lambda _generation: _publish(authority, ref))+ await commit_refresh(authority, ref)except Exception as exc: # health: allow BLE001 -- a refresh is best-effort; the resume itself must proceedlogger.info('Session %s keeps its stored policy on resume: %s', ref.session_id,getattr(exc, 'reason', None) or type(exc).__name__)diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 74220e07dd5..06f05d75bde 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -2432,6 +2432,9 @@"profiles.title","profiles.unsavedChanges","promptNotices.legacySendUnconfirmed",+ "promptNotices.mcpReloadDeferred",+ "promptNotices.mcpReloadNotInChat",+ "promptNotices.mcpReloadUnavailable","promptNotices.sessionCommands.countOne","promptNotices.sessionCommands.countOther","promptNotices.sessionCommands.queueFailed",diff --git a/tests/gateway/test_mcp_reload_new_server.py b/tests/gateway/test_mcp_reload_new_server.pynew file mode 100644index 00000000000..bf9210dccb3--- /dev/null+++ b/tests/gateway/test_mcp_reload_new_server.py@@ -0,0 +1,292 @@+"""CFG-3: an MCP server added to a profile's config after a local session started reaches that session only+through a gateway-committed policy generation (``reload.mcp`` for the calling idle session, or the CFG-2+refresh when a client attaches), definitions and private values included, so a managed worker connects it.+``reload.mcp`` names a configured server that did not connect instead of answering plain success."""+import asyncio+import json+import os+from types import SimpleNamespace++import pytest++from tests.gateway.test_session_resume_config_refresh import _call, _connect, _owner_authority, _runner+from tests.waiting import async_wait_until++CONFIG = ('model: {default: m1, provider: custom, base_url: "http://127.0.0.1:9/v1"}\n'+ 'platform_toolsets: {cli: [terminal]}\nterminal: {backend: local}\n'+ 'mcp_servers: {old: {command: old-mcp}}\n')+ADDED = CONFIG.replace('mcp_servers: {old: {command: old-mcp}}', 'mcp_servers: {old: {command: old-mcp}, '+ 'fixt: {command: fixt-mcp, env: {FIXT_TOKEN: sekret}}, dormant: {command: dormant-mcp, enabled: false}}')+OLD = {'old': {'command': 'old-mcp'}}+++def _home(monkeypatch):+ from gateway import run+ from hermes_constants import get_hermes_home+ home = get_hermes_home()+ home.mkdir(parents=True, exist_ok=True)+ (home / 'config.yaml').write_text(CONFIG)+ monkeypatch.setattr(run, '_hermes_home', home)+ return home+++def _reloadable(authority, monkeypatch):+ """reload.mcp's owner side, with the profile's servers already reconciled."""+ authority.runner.config = SimpleNamespace(multiplex_profiles=False)+ authority.runner._mcp_reload_refresh_cached_agents = lambda multiplex, profile: None+ monkeypatch.setattr('gateway.session_authorities.served_profile_name', lambda profile_id: 'default')+ monkeypatch.setattr('tools.mcp_tool_discovery.reconcile_mcp_servers_with_config',+ lambda: {'removed': [], 'added': ['fixt'], 'pending': []})+ monkeypatch.setattr('tools.mcp_tool_discovery.mcp_servers_not_connected', list)+++def _worker_frame(authority, sid, monkeypatch):+ """The managed-worker bootstrap a turn admitted now would get."""+ from gateway import session_managed_worker as smw+ from gateway.session_contract import SessionRef+ from gateway.session_policy import policy_for_source+ monkeypatch.setattr('gateway.session_worker_construct.construct_inputs', lambda *args: {})+ policy = policy_for_source(authority.runner, authority.sessions[sid].source)+ scope = {'profile_id': authority.profile_id, 'session_id': sid, 'execution_id': 'x', 'generation': 1,+ 'pid': os.getpid(), 'birth': 0, 'secret': 's', 'epoch': 1}+ return smw._bootstrap(authority, SessionRef(authority.profile_id, sid), {'payload': {'text': 'hi'}}, policy, scope)+++def _worker_servers(frame, monkeypatch):+ """What the worker's discovery connects: the servers of its bound config (``bind_worker_policy`` makes+ it every config read) that its toolsets name, as ``discover_mcp_tools`` filters them."""+ from tools.mcp_tool_config import _load_mcp_config+ config, toolsets = json.loads(frame['policy']['config_json']), set(frame['policy']['toolsets'])+ with monkeypatch.context() as bound:+ bound.setattr('hermes_cli.config.load_config', lambda *args, **kwargs: config)+ servers = _load_mcp_config()+ return {name: cfg for name, cfg in servers.items() if name in toolsets}, toolsets+++def _generation(store, sid):+ return store._db.get_session(sid)['runtime_generation']+++async def test_a_new_mcp_server_reaches_a_session_only_through_a_committed_generation(tmp_path, monkeypatch):+ from hermes_state_local import local_receipt+ home = _home(monkeypatch)+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ store, authority = await _owner_authority(home)+ _reloadable(authority, monkeypatch)+ owner, later = _connect(authority), _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='a', source='cli', cwd=str(tmp_path)))['session_id']+ other = (await _call(owner, 'session.create', request_id='b', source='cli', cwd=str(tmp_path)))['session_id']+ generation, other_generation = _generation(store, sid), _generation(store, other)+ (home / 'config.yaml').write_text(ADDED)+ # A turn admitted (or queued) now runs the generation it was admitted under: no capability appears+ # without a committed transition.+ assert 'fixt' not in _worker_frame(authority, sid, monkeypatch)['policy']['toolsets']+ result = await _call(owner, 'reload.mcp', session_id=sid, confirm=True)+ assert result['session'] == 'applied' and 'unavailable' not in result, result+ assert _generation(store, sid) == generation + 1+ servers, toolsets = _worker_servers(_worker_frame(authority, sid, monkeypatch), monkeypatch)+ assert {'terminal', 'old', 'fixt'} <= toolsets and 'dormant' not in toolsets+ assert servers['fixt']['command'] == 'fixt-mcp' and servers['fixt']['env'] == {'FIXT_TOKEN': 'sekret'}+ from gateway.session_policy import policy_for_source+ assert 'fixt' in policy_for_source(authority.runner, authority.sessions[sid].source).toolsets # in process+ assert 'sekret' not in json.dumps(local_receipt(store._db, sid)) # the private value stays private+ # Another session of the profile is not changed implicitly...+ assert 'fixt' not in _worker_frame(authority, other, monkeypatch)['policy']['toolsets']+ assert _generation(store, other) == other_generation+ # ...until a client attaches to it.+ await _call(later, 'session.resume', session_id=other)+ assert _generation(store, other) == other_generation + 1+ servers, toolsets = _worker_servers(_worker_frame(authority, other, monkeypatch), monkeypatch)+ assert set(servers) == {'old', 'fixt'} and servers['fixt']['env'] == {'FIXT_TOKEN': 'sekret'}+ finally:+ for connection in (owner, later):+ await connection.close()+ store.close_all_db_handles()+++async def test_resume_hands_a_worker_the_definition_of_every_server_it_names(tmp_path, monkeypatch):+ """A server added after creation reaches a managed worker with its definition and private values, not+ just its name (discovery filters the bound config's servers by the toolsets)."""+ home = _home(monkeypatch)+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ store, authority = await _owner_authority(home)+ owner, later = _connect(authority), _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='w', source='cli', cwd=str(tmp_path)))['session_id']+ (home / 'config.yaml').write_text(ADDED)+ await _call(later, 'session.resume', session_id=sid)+ servers, toolsets = _worker_servers(_worker_frame(authority, sid, monkeypatch), monkeypatch)+ assert 'fixt' in toolsets+ assert set(servers) == {'old', 'fixt'}, servers+ assert servers['fixt']['env'] == {'FIXT_TOKEN': 'sekret'}+ finally:+ for connection in (owner, later):+ await connection.close()+ store.close_all_db_handles()+++async def test_reload_never_changes_a_running_or_queued_turns_servers(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import SessionRef, Submission+ from gateway.session_policy import policy_for_source+ import hermes_state_runtime as rt+ home = _home(monkeypatch)+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ store = SessionStore(home / 'sessions', GatewayConfig())+ started, release = asyncio.Event(), asyncio.Event()++ async def handle(event):+ started.set()+ await release.wait()+ return 'ok'+ authority = await initialize_session_authority(_runner(store, handle), profile_id=str(home), instance_id='only')+ _reloadable(authority, monkeypatch)+ owner = _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='busy', source='cli', cwd=str(tmp_path)))['session_id']+ turn = await authority.submit(owner.actor, Submission('turn-1', SessionRef(authority.profile_id, sid),+ {'text': 'one'}, 'queue'))+ await asyncio.wait_for(started.wait(), 10)+ (home / 'config.yaml').write_text(ADDED)+ generation = _generation(store, sid)+ busy = await _call(owner, 'reload.mcp', session_id=sid, confirm=True)+ assert busy['session'] == 'busy' and 'once the turn finishes' in busy['message'], busy+ assert _generation(store, sid) == generation+ assert 'fixt' not in policy_for_source(authority.runner, authority.sessions[sid].source).toolsets+ release.set()+ await async_wait_until(lambda: rt.get_session_admission(store._db, admission_id=turn.admission_id)['status']+ == 'terminal', what='turn-1 to settle')+ assert (await _call(owner, 'reload.mcp', session_id=sid, confirm=True))['session'] == 'applied'+ assert 'fixt' in policy_for_source(authority.runner, authority.sessions[sid].source).toolsets+ finally:+ release.set()+ await owner.close()+ store.close_all_db_handles()+++async def test_an_admission_queued_during_a_reload_commit_keeps_the_old_servers(tmp_path, monkeypatch):+ """reload.mcp's session commit is fenced inside its write transaction: a turn queued after the refresh+ read the stored policy refuses it (``session: busy``), and that turn runs without the new server."""+ import hermes_state_runtime as rt+ from hermes_state_local import local_receipt+ from tests.gateway.test_session_resume_config_refresh import admit_during_refresh, hold_refresh_commit+ home = _home(monkeypatch)+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ seen = []++ async def handle(event):+ from gateway.session_policy import policy_for_source+ seen.append('fixt' in policy_for_source(authority.runner, event.source).toolsets)+ return 'ok'+ store, authority = await _owner_authority(home)+ _reloadable(authority, monkeypatch)+ authority.runner._handle_message = handle+ owner = _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='q', source='cli', cwd=str(tmp_path)))['session_id']+ stored = local_receipt(store._db, sid)['policy']+ (home / 'config.yaml').write_text(ADDED)+ barrier = hold_refresh_commit(monkeypatch)+ reload = _call(owner, 'reload.mcp', session_id=sid, confirm=True)+ result, turn = await admit_during_refresh(authority, owner.actor, sid, reload, barrier)+ assert result['session'] == 'busy', result+ assert local_receipt(store._db, sid)['policy'] == stored+ await async_wait_until(lambda: rt.get_session_admission(store._db, admission_id=turn.admission_id)['status']+ == 'terminal', what='the queued turn to run')+ assert seen == [False]+ finally:+ await owner.close()+ store.close_all_db_handles()+++def test_not_connected_names_a_configured_server_in_cooldown(monkeypatch):+ from tools import mcp_tool, mcp_tool_discovery as discovery+ from tools.mcp_tool_scope import _server_key+ monkeypatch.setattr(discovery._config, '_load_mcp_config', lambda: {**OLD, 'fixt': {'command': 'x'}})+ monkeypatch.setattr(discovery, '_connect_cooldown_active', lambda name: True)+ monkeypatch.setitem(mcp_tool._servers, _server_key('old'), object())+ assert discovery.mcp_servers_not_connected() == ['fixt']+ # The housekeeping retry still waits the cooldown out.+ assert discovery.mcp_servers_awaiting_connect() == []+++def test_reload_counts_only_changes_that_took_effect(monkeypatch):+ """reconcile's ``added`` names the servers it ATTEMPTED and ``pending`` unfinished teardowns: neither is an+ applied change. Only a server that registered (live or lazy), a completed removal or a committed session+ generation turns an unavailable server into partial success."""+ from gateway import session_ancillary+ from hermes_state_runtime import RuntimeStoreError+ refreshed = []+ runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=False),+ _mcp_reload_refresh_cached_agents=lambda multiplex, profile: refreshed.append(profile))+ connection = SimpleNamespace(actor=SimpleNamespace(capabilities={'session:control'}),+ authority=SimpleNamespace(runner=runner, profile_id='fixture'))+ reconciled, not_connected = {}, ['broken']+ monkeypatch.setattr('tools.mcp_tool_discovery.reconcile_mcp_servers_with_config', lambda: dict(reconciled))+ monkeypatch.setattr('tools.mcp_tool_discovery.mcp_servers_not_connected', lambda: list(not_connected))+ monkeypatch.setattr('gateway.session_authorities.served_profile_name', lambda profile_id: 'default')++ def reload(**outcome):+ reconciled.update({'removed': [], 'added': [], 'pending': [], **outcome})+ return asyncio.run(session_ancillary.reload_mcp(connection, None, {'confirm': True}))+ # Every attempted addition failed (and a teardown is still unfinished): nothing applied, the named refusal.+ for outcome in ({}, {'added': ['broken']}, {'added': ['broken'], 'pending': ['slow']}):+ with pytest.raises(RuntimeStoreError) as refused:+ reload(**outcome)+ assert refused.value.reason == 'mcp_servers_unavailable' and 'broken' in refused.value.detail, outcome+ assert refreshed == ['default'] * 3+ # A genuine mix: success that names only the server that did not connect, and reports only real changes.+ result = reload(added=['broken', 'fixt'])+ assert result['status'] == 'reloaded' and result['unavailable'] == ['broken'], result+ assert 'added: fixt' in result['message'] and 'did not connect: broken' in result['message'], result+ # A completed removal is an applied change too.+ result = reload(removed=['gone'], added=['broken'])+ assert result['unavailable'] == ['broken'] and 'removed: gone' in result['message']+ assert 'added' not in result['message'], result+ not_connected.clear()+ result = reload(added=['fixt'])+ assert result['status'] == 'reloaded' and 'unavailable' not in result+++def test_messaging_reload_names_a_server_that_did_not_connect():+ from unittest.mock import patch+ from tests.gateway.test_mcp_reload_refreshes_cached_agents import _make_event, _make_runner_with_cached_agents+ runner = _make_runner_with_cached_agents(num_agents=0)+ with (patch('tools.mcp_tool_lifecycle.shutdown_mcp_servers'),+ patch('tools.mcp_tool_discovery.discover_mcp_tools', return_value=[]),+ patch('tools.mcp_tool_discovery.mcp_servers_not_connected', return_value=['fixt']),+ patch.dict('tools.mcp_tool._servers', {}, clear=True)):+ result = asyncio.run(runner._execute_mcp_reload(_make_event()))+ assert 'did not connect: fixt' in result+++async def test_reload_reports_the_servers_the_calling_chat_selects(tmp_path, monkeypatch):+ """A server connected for the profile is not one this chat runs: ``session_servers`` names the calling+ session's committed selection, so a chat created with ``no_mcp`` reports none of them."""+ home = _home(monkeypatch)+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ store, authority = await _owner_authority(home)+ _reloadable(authority, monkeypatch)+ owner = _connect(authority)+ try:+ plain = (await _call(owner, 'session.create', request_id='a', source='cli', cwd=str(tmp_path)))['session_id']+ bare = (await _call(owner, 'session.create', request_id='b', source='cli', cwd=str(tmp_path),+ toolsets=['terminal', 'no_mcp']))['session_id']+ (home / 'config.yaml').write_text(ADDED)+ result = await _call(owner, 'reload.mcp', session_id=plain, confirm=True)+ assert result['session'] == 'applied' and result['session_servers'] == ['fixt', 'old'], result+ result = await _call(owner, 'reload.mcp', session_id=bare, confirm=True)+ assert 'unavailable' not in result and result['session_servers'] == [], result+ # No calling session, no selection to report.+ assert 'session_servers' not in await _call(owner, 'reload.mcp', confirm=True)+ finally:+ await owner.close()+ store.close_all_db_handles()diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.pyindex 66b823a98cc..f2429ce599f 100644--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@ -690,7 +690,7 @@ def reconcile_mcp_servers_with_config() -> dict[str, list[str]]:"pending": sorted(connecting - wanted)}-def _awaiting_connect(wanted: set[str], scope) -> list[str]:+def _unregistered(wanted: set[str], scope) -> set[str]:with _core._lock:# Same resolution ``_select_new_servers`` applies: this scope's own connection OR a shared# one it adopted from another profile counts as live. Owner==scope alone misses the adopted@@ -699,11 +699,27 @@ def _awaiting_connect(wanted: set[str], scope) -> list[str]:known = {name for name in wantedif (key := _resolve_server_key(name, scope, current=False)) in _core._serversor key in _core._server_connecting or key in _core._lazy_server_configs}+ return wanted - known+++def _awaiting_connect(wanted: set[str], scope) -> list[str]:# A configured server that is not live is retried — the only way one whose FIRST connect# failed comes back (#112445) — but only once its connect cooldown lapsed: ``discover_mcp_tools``# would skip it anyway, and entering it takes the cross-process discovery lock (up to 120 s of# waiting when another process holds it) and logs a failed pass, every call, for nothing.- return sorted(name for name in wanted - known if not _connect_cooldown_active(name))+ return sorted(name for name in _unregistered(wanted, scope) if not _connect_cooldown_active(name))+++def _enabled_config_names() -> set[str]:+ with _owner_secret_scope():+ servers = _config._load_mcp_config()+ return {name for name, cfg in servers.items() if mcp_server_enabled(cfg)}+++def mcp_servers_not_connected() -> list[str]:+ """Enabled ``mcp_servers`` entries the current registry scope has no live, connecting or lazy+ registration for, in connect cooldown or not: after a reload, the servers that did not connect."""+ return sorted(_unregistered(_enabled_config_names(), _core._mcp_registry_scope()))def mcp_servers_awaiting_connect() -> list[str]:@@ -711,10 +727,7 @@ def mcp_servers_awaiting_connect() -> list[str]:registration for, whose connect cooldown has lapsed: added to config since the last discoveryrun, or one whose earlier connect failed. Read-only — what the next :func:`discover_mcp_tools`would connect."""- with _owner_secret_scope():- servers = _config._load_mcp_config()- wanted = {name for name, cfg in servers.items() if mcp_server_enabled(cfg)}- return _awaiting_connect(wanted, _core._mcp_registry_scope())+ return _awaiting_connect(_enabled_config_names(), _core._mcp_registry_scope())def _forget_lazy_server(key) -> None:diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 6e112c2f1d2..2e5c0dc27d6 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -128,13 +128,26 @@ class ReloadMcpStatus(WireEnum):reloaded = "reloaded"+class ReloadMcpSession(WireEnum):+ applied = "applied"+ unchanged = "unchanged"+ busy = "busy"++class ReloadMcpResult(Result):+ """``session``: what the calling local session's MCP servers did (a new policy generation, nothing to+ change, or deferred while a turn runs or waits); ``unavailable``: configured servers that did not connect+ beside what did apply; ``session_servers``: the MCP servers that session's committed policy runs."""+status: ReloadMcpStatusmessage: str | None = Noneloaded_rev: str | None = Nonecoalesced: bool | None = Noneturn_isolation: bool | None = Nonehost_ack: JsonValue | None = None+ session: ReloadMcpSession | None = None+ unavailable: list[str] | None = None+ session_servers: list[str] | None = Nonemethod("reload.mcp", params=ReloadMcpParams, result=ReloadMcpResult,