Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
*/

import * as assert from 'assert'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import * as sinon from 'sinon'
import { MemoryBankController } from './memoryBankController'
import { MemoryBankPrompts } from './memoryBankPrompts'
Expand Down Expand Up @@ -402,4 +405,133 @@ describe('MemoryBankController', () => {
sinon.assert.calledOnce(mockLogging.error)
})
})

describe('cleanMemoryBankDirectory', () => {
const memoryBankFiles = ['product.md', 'structure.md', 'tech.md', 'guidelines.md']
let tempRoot: string
let workspacePath: string

// A directory link; on Windows a junction, which needs no extra privilege.
const linkDirectory = (target: string, linkPath: string) =>
fs.symlinkSync(target, linkPath, process.platform === 'win32' ? 'junction' : 'dir')

const writeMemoryBankFiles = (folder: string) => {
fs.mkdirSync(folder, { recursive: true })
for (const name of memoryBankFiles) {
fs.writeFileSync(path.join(folder, name), 'old')
}
}

beforeEach(() => {
tempRoot = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'memory-bank-')))
workspacePath = path.join(tempRoot, 'workspace')
fs.mkdirSync(workspacePath)

// The stubbed workspace file system acts on the real temporary folder.
mockFs.exists.callsFake(async (p: string) => fs.existsSync(p))
mockFs.rm = sinon.stub().callsFake((p: string) => fs.promises.rm(p, { recursive: true, force: true }))
mockFs.mkdir.callsFake(async (p: string, options?: fs.MakeDirectoryOptions) => {
await fs.promises.mkdir(p, options)
})
})

afterEach(() => {
fs.rmSync(tempRoot, { recursive: true, force: true })
})

it('removes the memory bank files in the workspace folder and keeps the folder', async () => {
const memoryBankPath = path.join(workspacePath, '.amazonq', 'rules', 'memory-bank')
writeMemoryBankFiles(memoryBankPath)
fs.writeFileSync(path.join(memoryBankPath, 'notes.md'), 'kept')

await controller.cleanMemoryBankDirectory(workspacePath)

assert.deepStrictEqual(fs.readdirSync(memoryBankPath), ['notes.md'])
sinon.assert.callCount(mockFs.rm, memoryBankFiles.length)
sinon.assert.notCalled(mockLogging.warn)
})

it('creates the memory bank folder when it does not exist yet', async () => {
await controller.cleanMemoryBankDirectory(workspacePath)

assert.ok(fs.statSync(path.join(workspacePath, '.amazonq', 'rules', 'memory-bank')).isDirectory())
sinon.assert.notCalled(mockFs.rm)
})

it('removes the files when a link inside the workspace folder leads to the memory bank folder', async () => {
const target = path.join(workspacePath, 'config', 'amazonq')
writeMemoryBankFiles(path.join(target, 'rules', 'memory-bank'))
linkDirectory(target, path.join(workspacePath, '.amazonq'))

await controller.cleanMemoryBankDirectory(workspacePath)

assert.deepStrictEqual(fs.readdirSync(path.join(target, 'rules', 'memory-bank')), [])
sinon.assert.notCalled(mockLogging.warn)
})

it('removes the files when the workspace folder itself is reached through a link', async () => {
const memoryBankPath = path.join(workspacePath, '.amazonq', 'rules', 'memory-bank')
writeMemoryBankFiles(memoryBankPath)
const workspaceAlias = path.join(tempRoot, 'workspace-alias')
linkDirectory(workspacePath, workspaceAlias)

await controller.cleanMemoryBankDirectory(workspaceAlias)

assert.deepStrictEqual(fs.readdirSync(memoryBankPath), [])
})

const outsideCases = [
{ link: ['.amazonq'], below: ['rules', 'memory-bank'] },
{ link: ['.amazonq', 'rules'], below: ['memory-bank'] },
{ link: ['.amazonq', 'rules', 'memory-bank'], below: [] as string[] },
]
for (const { link, below } of outsideCases) {
it(`leaves the files outside the workspace folder alone when ${link.join('/')} links there`, async () => {
const target = path.join(tempRoot, 'outside')
const outsideMemoryBankPath = path.join(target, ...below)
writeMemoryBankFiles(outsideMemoryBankPath)
fs.mkdirSync(path.join(workspacePath, ...link.slice(0, -1)), { recursive: true })
linkDirectory(target, path.join(workspacePath, ...link))

await controller.cleanMemoryBankDirectory(workspacePath)

for (const name of memoryBankFiles) {
assert.strictEqual(fs.readFileSync(path.join(outsideMemoryBankPath, name), 'utf8'), 'old')
}
sinon.assert.notCalled(mockFs.rm)
sinon.assert.notCalled(mockFs.mkdir)
sinon.assert.calledOnceWithMatch(mockLogging.warn, /outside the workspace folder/)
})
}

it('does not create a memory bank folder through a link that leaves the workspace folder', async () => {
const target = path.join(tempRoot, 'outside')
fs.mkdirSync(target)
linkDirectory(target, path.join(workspacePath, '.amazonq'))

await controller.cleanMemoryBankDirectory(workspacePath)

assert.deepStrictEqual(fs.readdirSync(target), [])
sinon.assert.notCalled(mockFs.mkdir)
})

it('logs a warning and changes nothing when the memory bank path cannot be resolved', async function () {
try {
// Two links that point at each other, so the path cannot be resolved
fs.symlinkSync(path.join(workspacePath, 'loop'), path.join(workspacePath, '.amazonq'), 'dir')
fs.symlinkSync(path.join(workspacePath, '.amazonq'), path.join(workspacePath, 'loop'), 'dir')
} catch {
// A directory link on Windows needs a privilege that the test may not have
this.skip()
}

// Memory bank generation goes on: the cleanup does not throw
await controller.cleanMemoryBankDirectory(workspacePath)

sinon.assert.notCalled(mockFs.rm)
sinon.assert.notCalled(mockFs.mkdir)
sinon.assert.calledOnceWithMatch(mockLogging.warn, /outside the workspace folder, or cannot be resolved/)
sinon.assert.notCalled(mockLogging.error)
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { Features } from '@aws/language-server-runtimes/server-interface/server'
import { MemoryBankPrompts } from './memoryBankPrompts'
import { normalizePathFromUri } from '../../tools/mcp/mcpUtils'
import { isInsideFolder } from '../../tools/toolShared'
import { MAX_NUMBER_OF_FILES_FOR_MEMORY_BANK_RANKING } from '../../constants/constants'

const MEMORY_BANK_DIRECTORY = '.amazonq/rules/memory-bank'
Expand Down Expand Up @@ -178,6 +179,17 @@ export class MemoryBankController {
const normalizedWorkspacePath = normalizePathFromUri(workspaceFolderUri, this.features.logging)
const memoryBankPath = `${normalizedWorkspacePath}/${MEMORY_BANK_DIRECTORY}`

// Remove and create files only where the memory bank folder really is. If a symbolic link takes
// it out of the workspace folder, or the path cannot be resolved (for example links that point at
// each other), leave it alone; the agent's later file writes are then checked like any other write
// outside the workspace.
if (!(await isInsideFolder(normalizedWorkspacePath, memoryBankPath))) {
this.features.logging.warn(
`Memory Bank: did not clean ${MEMORY_BANK_DIRECTORY} because it resolves to a location outside the workspace folder, or cannot be resolved`
)
return
}

// Remove all existing memory bank files to ensure clean recreation
const filesToRemove = ['product.md', 'structure.md', 'tech.md', 'guidelines.md']
let removedCount = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,162 @@ describe('McpEventHandler error handling', () => {
expect(result.list.map(group => group.groupName)).to.deep.equal(['Disabled'])
})

describe('saving an edit that cannot be applied', () => {
it('stays on the edit page with the reason and does not add or clean up a server', async () => {
await setupServers(new Map([['srv', { command: 'npx', disabled: false }]]), {
srv: McpServerStatus.ENABLED,
})
const mgr = McpManager.instance
const reason =
'The agent config "default.json" was not saved because it is outside the workspace folder'
sinon.stub(mgr, 'removeServer').rejects(new Error(reason))
const addServer = sinon.stub(mgr, 'addServer').resolves()
const removeFromFile = sinon.stub(mgr, 'removeServerFromConfigFile').resolves()

await eventHandler.onMcpServerClick({ id: 'edit-mcp', title: 'srv' })
const result: any = await eventHandler.onMcpServerClick({
id: 'save-mcp',
optionsValues: {
name: 'srv',
transport: 'stdio',
command: 'npx',
args: [],
env_variables: [],
timeout: '60',
scope: 'global',
},
} as any)

sinon.assert.notCalled(addServer)
sinon.assert.notCalled(removeFromFile)
expect(result.id).to.equal('edit-mcp')
expect(result.header.status).to.deep.equal({ title: reason, icon: 'cancel-circle', status: 'error' })
})

it('does not remove the server when the edited server cannot be saved where it goes', async () => {
await setupServers(new Map([['srv', { command: 'npx', disabled: false }]]), {
srv: McpServerStatus.ENABLED,
})
const mgr = McpManager.instance
const reason =
'The agent config "default.json" was not saved because it is outside the workspace folder'
const check = sinon.stub(mcpUtils, 'checkAgentConfigWrite').rejects(new Error(reason))
const removeServer = sinon.stub(mgr, 'removeServer').resolves()
const addServer = sinon.stub(mgr, 'addServer').resolves()

await eventHandler.onMcpServerClick({ id: 'edit-mcp', title: 'srv' })
const result: any = await eventHandler.onMcpServerClick({
id: 'save-mcp',
optionsValues: {
name: 'srv',
transport: 'stdio',
command: 'npx',
args: [],
env_variables: [],
timeout: '60',
scope: 'workspace',
},
} as any)

sinon.assert.calledOnce(check)
sinon.assert.notCalled(removeServer)
sinon.assert.notCalled(addServer)
expect(result.id).to.equal('edit-mcp')
expect(result.header.status).to.deep.equal({ title: reason, icon: 'cancel-circle', status: 'error' })
})

it('checks the agent config next to the mcp.json when a legacy server is edited', async () => {
await setupServers(
new Map([['srv', { command: 'npx', disabled: false, __configPath__: 'ws/.amazonq/mcp.json' }]]),
{ srv: McpServerStatus.ENABLED }
)
const mgr = McpManager.instance
const check = sinon.stub(mcpUtils, 'checkAgentConfigWrite').rejects(new Error('not saved'))
const removeServer = sinon.stub(mgr, 'removeServer').resolves()

await eventHandler.onMcpServerClick({ id: 'edit-mcp', title: 'srv' })
await eventHandler.onMcpServerClick({
id: 'save-mcp',
optionsValues: {
name: 'srv',
transport: 'stdio',
command: 'npx',
args: [],
env_variables: [],
timeout: '60',
scope: 'global',
},
} as any)

sinon.assert.calledOnceWithMatch(
check,
sinon.match.any,
sinon.match.any,
mcpUtils.getAgentConfigPathForMcpConfig(
mcpUtils.getGlobalMcpConfigPath(features.workspace.fs.getUserHomeDir())
)
)
sinon.assert.notCalled(removeServer)
})

it('does not remove a registry server when the updated server cannot be saved where it goes', async () => {
await setupServers(new Map([['srv', { url: 'https://example.com/mcp', disabled: false }]]), {
srv: McpServerStatus.ENABLED,
})
const mgr = McpManager.instance
sinon.stub(mgr, 'getRegistryService').returns({
isRegistryActive: () => true,
getServerByName: () => ({
name: 'srv',
version: '1.0.0',
remotes: [{ type: 'streamable-http', url: 'https://example.com/mcp' }],
}),
} as any)
const reason = 'The agent config was not saved because it is outside the workspace folder'
const check = sinon.stub(mcpUtils, 'checkAgentConfigWrite').rejects(new Error(reason))
const removeServer = sinon.stub(mgr, 'removeServer').resolves()
const addRegistryServer = sinon.stub(mgr, 'addRegistryServer').resolves()

const result: any = await eventHandler.onMcpServerClick({
id: 'save-mcp',
title: 'srv',
optionsValues: { name: 'srv', timeout: '60', scope: 'workspace', additional_headers: [] },
} as any)

sinon.assert.calledOnce(check)
sinon.assert.notCalled(removeServer)
sinon.assert.notCalled(addRegistryServer)
expect(result.header.status.title).to.include(reason)
})

it('stays on the add form with the reason and does not add a server that cannot be saved', async () => {
await setupServers(new Map(), {})
const mgr = McpManager.instance
const reason =
'The agent config "default.json" was not saved because it is outside the workspace folder'
const check = sinon.stub(mcpUtils, 'checkAgentConfigWrite').rejects(new Error(reason))
const addServer = sinon.stub(mgr, 'addServer').resolves()

const result: any = await eventHandler.onMcpServerClick({
id: 'save-mcp',
optionsValues: {
name: 'my server',
transport: 'stdio',
command: 'npx',
args: [],
env_variables: [],
timeout: '60',
scope: 'workspace',
},
} as any)

sinon.assert.calledOnce(check)
sinon.assert.notCalled(addServer)
expect(result.id).to.equal('add-new-mcp')
expect(result.header.status).to.deep.equal({ title: reason, icon: 'cancel-circle', status: 'error' })
})
})

describe('servers held back by the workspace trust check', () => {
const trustHoldCases = [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
} from '@aws/language-server-runtimes/protocol'

import {
checkAgentConfigWrite,
getAgentConfigPathForMcpConfig,
getGlobalAgentConfigPath,
getWorkspaceAgentConfigPaths,
sanitizeName,
Expand Down Expand Up @@ -947,6 +949,12 @@ export class McpEventHandler {
const isLegacyMcpServer = serverConfig?.__configPath__?.endsWith('mcp.json') ?? false
const configPath = isLegacyMcpServer ? await this.#getMcpConfigPath(isGlobal) : agentPath
try {
// The edited server must be savable where it goes before the old one is removed
await checkAgentConfigWrite(
this.#features.workspace,
this.#features.logging,
isLegacyMcpServer ? getAgentConfigPathForMcpConfig(configPath) : configPath
)
await McpManager.instance.removeServer(serverToRemove)
await McpManager.instance.addServer(serverName, config, configPath, isLegacyMcpServer)
} catch (error) {
Expand All @@ -956,6 +964,8 @@ export class McpEventHandler {
} else {
// Create new server
try {
// A new server that cannot be saved where it goes is not added
await checkAgentConfigWrite(this.#features.workspace, this.#features.logging, agentPath)
await McpManager.instance.addServer(serverName, config, agentPath)
} catch (error) {
this.#features.logging.error(`McpManager not initialized for addServer: ${error}`)
Expand All @@ -965,6 +975,16 @@ export class McpEventHandler {
}
} catch (error) {
this.#features.logging.error(`Failed to enable MCP server: ${error}`)
// The change did not go through, for example because the agent config may not be written where the server
// is saved: stay on the form and show why, as for an invalid form
const message = error instanceof Error ? error.message : String(error)
this.#releaseProgrammaticAfterDebounce()
if (isEditMode && originalServerName) {
params.id = 'edit-mcp'
return this.#handleEditMcpServer({ ...params, title: originalServerName }, message)
}
params.id = 'add-new-mcp'
return this.#handleAddNewMcp(params, message)
}

this.#currentEditingServerName = undefined
Expand Down Expand Up @@ -2269,6 +2289,8 @@ export class McpEventHandler {
this.#isProgrammaticChange = true

try {
// The updated server must be savable where it goes before the old one is removed
await checkAgentConfigWrite(this.#features.workspace, this.#features.logging, agentPath)
await McpManager.instance.removeServer(sanitizedServerName)
await McpManager.instance.addRegistryServer(
sanitizedServerName,
Expand Down
Loading
Loading