Skip to content

Commit c8c5ea9

Browse files
committed
fix(mcp): disable token-goat MCP tools when hooks are available
1 parent 183883e commit c8c5ea9

5 files changed

Lines changed: 176 additions & 28 deletions

File tree

‎src/bridges/copilot_cli_install.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@ import { projectScopeRoot, withInstallScope } from './project_scope_guard.js'
1212
import { loadConfig } from '../config.js'
1313
import { copilotCliCacheRoot, copilotCliMcpToolsDir, copilotCliUserRoot } from '../copilot_home.js'
1414
import { copilotHooksOwnersPath, HOOKS_CONFIG_FILE, readCopilotHooksOwners, type CopilotHooksOwner } from './copilot_hooks_owners.js'
15-
import { copilotMcpConfigPath, installCopilotMcpServer, uninstallCopilotMcpServer } from './copilot_mcp_install.js'
15+
import {
16+
copilotMcpConfigPath,
17+
isCopilotMcpServerInstalled,
18+
uninstallCopilotMcpServer,
19+
} from './copilot_mcp_install.js'
1620
import { syncVisualStudioProjectGuidance } from './visualstudio_install.js'
1721
import { stripBom } from '../jsonc_text.js'
1822

@@ -198,9 +202,9 @@ export interface CopilotCliInstallResult {
198202
readonly scriptPath: string
199203
/** Path to the copilot-instructions.md that received the token-goat routing block. */
200204
readonly instructionsPath: string
201-
/** `<COPILOT_HOME>/mcp-config.json`, which received the `token-goat` MCP server entry; undefined for a `--local` install, since Copilot reads MCP servers only from the user-scope file. */
205+
/** Legacy MCP config path when the managed entry remains installed; normally absent because user-scope installs remove it. */
202206
readonly mcpConfigPath?: string
203-
/** True when the shim script, the hook config, the instructions block and the MCP entry were all already up to date (no write needed). */
207+
/** True when hooks and instructions were already up to date and no legacy MCP entry needed removal. */
204208
readonly alreadyInstalled: boolean
205209
}
206210

@@ -314,7 +318,9 @@ function installCopilotCliScoped(opts: CopilotCliScopeOptions): CopilotCliInstal
314318
// Checked before the MCP step, which is the first write and makes the Copilot home when there is none.
315319
const scopeDir = path.dirname(instructionsPath)
316320
const scopeDirExisted = fs.existsSync(scopeDir)
317-
const mcpChanged = userScope ? installCopilotMcpServer() : false
321+
// Copilot CLI has native hooks available, so token-goat does not load or install MCP for it.
322+
// If an MCP entry was previously installed, remove it so Copilot CLI uses hooks instead of MCP.
323+
const mcpChanged = userScope && isCopilotMcpServerInstalled() ? uninstallCopilotMcpServer() : false
318324
if (!scopeDirExisted && fs.existsSync(scopeDir)) recordCreatedConfig(scopeDir)
319325
const { hooks, instructionsChanged: scopeInstructionsChanged } = syncCopilotHooksAndInstructions(opts)
320326
let instructionsChanged = scopeInstructionsChanged
@@ -333,7 +339,7 @@ function installCopilotCliScoped(opts: CopilotCliScopeOptions): CopilotCliInstal
333339
configPath: hooks.configPath,
334340
scriptPath: hooks.scriptPath,
335341
instructionsPath,
336-
...(userScope ? { mcpConfigPath: copilotMcpConfigPath() } : {}),
342+
...(userScope && isCopilotMcpServerInstalled() ? { mcpConfigPath: copilotMcpConfigPath() } : {}),
337343
alreadyInstalled: !hooks.changed && !instructionsChanged && !mcpChanged,
338344
}
339345
}

‎src/bridges/guidance_block.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export function buildGuidanceBody(fallbackToolClause: string, opts: GuidanceOpti
3838
'- paging a function/file or receiving a `[tg]` range denial → stop range reads; run its exact command, `read "file" "symbol"` for a definition, `read "file" "start-end"` for a window, `skeleton file` for structure, or `grep "<pattern>" file -C 15 --symbol` for an excerpt',
3939
'- reading a symbol plus chasing its callers and containing doc section as separate reads → `brief "file::symbol"`',
4040
'- reading one heading of a large doc → `section "file" "Heading"`',
41-
'- searching for a symbol\\'s callers → `refs "file::symbol" --callers`',
41+
"- searching for a symbol's callers → `refs \"file::symbol\" --callers`",
4242
'- searching across symbols, headings, text, and concepts concurrently → `search "<query>"`',
4343
'- searching for a *concept* rather than a literal string → `semantic "description"`',
4444
'- re-reading output you already captured → `bash-output`/`web-output`/`mcp-output` by ID',

‎src/mcp_jsonrpc.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { z } from 'zod'
44

5+
import { detectHarness } from './bridges/registry.js'
56
import { answeringMcpToolCall } from './mcp_client_text.js'
67
import { displaySafeText } from './paths.js'
78

@@ -146,6 +147,7 @@ export class McpServer {
146147
private readonly info: { name: string; version: string }
147148
private readonly tools = new Map<string, RegisteredTool>()
148149
private readonly handlers = new Map<string, ErasedHandler>()
150+
private hooksAvailable = false
149151
private transport: McpTransport | undefined
150152
/** Set by the caller to learn when the peer hung up; `mcp-serve` waits on exactly this. */
151153
onclose: (() => void) | undefined
@@ -213,9 +215,25 @@ export class McpServer {
213215
const params = (message.params ?? {}) as Record<string, unknown>
214216
try {
215217
switch (method) {
216-
case 'initialize':
218+
case 'initialize': {
219+
const clientInfo = params['clientInfo'] as Record<string, unknown> | undefined
220+
const clientNameValue = clientInfo?.['name']
221+
const clientName = typeof clientNameValue === 'string' ? clientNameValue.toLowerCase() : ''
222+
const harness = detectHarness()
223+
if (
224+
harness === 'copilot_cli' ||
225+
harness === 'claudecode' ||
226+
clientName.includes('copilot') ||
227+
clientName.includes('claude') ||
228+
process.env['COPILOT_HOME'] !== undefined ||
229+
process.env['CLAUDE_CODE_SESSION_ID'] !== undefined ||
230+
process.env['TERM_PROGRAM'] === 'claude-code'
231+
) {
232+
this.hooksAvailable = true
233+
}
217234
await this.send({ jsonrpc: '2.0', id, result: this.initializeResult(params) })
218235
return
236+
}
219237
case 'ping':
220238
await this.send({ jsonrpc: '2.0', id, result: {} })
221239
return
@@ -254,6 +272,7 @@ export class McpServer {
254272
}
255273

256274
private listTools(): Record<string, unknown>[] {
275+
if (this.hooksAvailable) return []
257276
return [...this.tools.values()].map((tool) => ({
258277
name: tool.name,
259278
...(tool.description !== undefined ? { description: tool.description } : {}),
@@ -266,6 +285,9 @@ export class McpServer {
266285
}
267286

268287
private async callTool(params: Record<string, unknown>): Promise<CallToolResult> {
288+
if (this.hooksAvailable) {
289+
return errorText('token-goat MCP tools are disabled because hooks are available for this harness')
290+
}
269291
const name = params['name']
270292
if (typeof name !== 'string') return errorText('Invalid params: tools/call requires a string "name"')
271293
const tool = this.tools.get(name)

‎tests/install_copilot_mcp.test.ts‎

Lines changed: 67 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/** `token-goat install --copilot` registers token-goat's MCP server in Copilot CLI's user MCP config, `<COPILOT_HOME>/mcp-config.json`, and `uninstall --copilot` takes it out again. Before this, the README told Copilot users to write that entry by hand, in a shape Copilot does not write itself. PROVENANCE: CAPTURE. tests/fixtures/copilot_cli_1_0_88_mcp/ holds what GitHub Copilot CLI 1.0.88 itself wrote on Windows, recorded on 2026-09-28 in an isolated COPILOT_HOME, with the console output in transcript.txt beside it: `copilot mcp add other -- echo hi`, then `copilot mcp add token-goat -- "C:/Program Files/nodejs/node.exe" C:/x/dist/token-goat.mjs mcp-serve` (mcp-config-after-add.json), then `copilot mcp remove token-goat` (mcp-config-after-remove.json). The entry token-goat writes must have the key set Copilot gives its own `token-goat` entry, and uninstalling from Copilot's after-add file must leave what Copilot's own remove left. */
1+
/** Copilot CLI now uses native hooks instead of token-goat MCP. These tests cover removal of legacy MCP entries by the CLI installer/uninstaller and retain direct coverage of the MCP compatibility helpers. PROVENANCE: CAPTURE. tests/fixtures/copilot_cli_1_0_88_mcp/ holds what GitHub Copilot CLI 1.0.88 itself wrote on Windows, recorded on 2026-09-28 in an isolated COPILOT_HOME, with the console output in transcript.txt beside it: `copilot mcp add other -- echo hi`, then `copilot mcp add token-goat -- "C:/Program Files/nodejs/node.exe" C:/x/dist/token-goat.mjs mcp-serve` (mcp-config-after-add.json), then `copilot mcp remove token-goat` (mcp-config-after-remove.json). */
22
import * as fs from 'node:fs'
33
import * as path from 'node:path'
44

@@ -17,7 +17,12 @@ vi.mock('node:os', async (importOriginal) => {
1717
import * as os from 'node:os'
1818

1919
import { copilotCliConfigPath, installCopilotCli, uninstallCopilotCli } from '../src/bridges/copilot_cli_install.js'
20-
import { copilotMcpConfigPath, isCopilotMcpServerInstalled } from '../src/bridges/copilot_mcp_install.js'
20+
import {
21+
copilotMcpConfigPath,
22+
installCopilotMcpServer,
23+
isCopilotMcpServerInstalled,
24+
uninstallCopilotMcpServer,
25+
} from '../src/bridges/copilot_mcp_install.js'
2126

2227
const FIXTURES = path.join(__dirname, 'fixtures', 'copilot_cli_1_0_88_mcp')
2328
const AFTER_ADD = fs.readFileSync(path.join(FIXTURES, 'mcp-config-after-add.json'), 'utf8')
@@ -54,10 +59,35 @@ function seed(text: string): void {
5459
}
5560

5661
describe('Copilot CLI MCP registration (CAPTURE copilot mcp add/remove, 1.0.88)', () => {
57-
it('writes <COPILOT_HOME>/mcp-config.json with the entry shape Copilot writes for its own local servers', () => {
62+
it('does not install MCP for Copilot CLI', () => {
5863
const result = installCopilotCli()
5964
expect(copilotMcpConfigPath()).toBe(path.join(TMP, 'copilot-home', 'mcp-config.json'))
60-
expect(result.mcpConfigPath).toBe(copilotMcpConfigPath())
65+
expect(result.mcpConfigPath).toBeUndefined()
66+
expect(fs.existsSync(copilotMcpConfigPath())).toBe(false)
67+
expect(isCopilotMcpServerInstalled()).toBe(false)
68+
expect(installCopilotCli().alreadyInstalled).toBe(true)
69+
})
70+
71+
it('removes a previously installed MCP entry during a user-scope hooks install', () => {
72+
seed(AFTER_ADD)
73+
const result = installCopilotCli()
74+
expect(result.mcpConfigPath).toBeUndefined()
75+
expect(isCopilotMcpServerInstalled()).toBe(false)
76+
expect(fs.readFileSync(copilotMcpConfigPath(), 'utf8').trim()).toBe(AFTER_REMOVE.trim())
77+
})
78+
79+
it('does not add an MCP entry beside a server Copilot already holds', () => {
80+
seed(AFTER_REMOVE)
81+
const result = installCopilotCli()
82+
expect(result.mcpConfigPath).toBeUndefined()
83+
const after = servers()
84+
expect(Object.keys(after)).toEqual(['other'])
85+
expect(after['other']).toEqual((JSON.parse(AFTER_REMOVE) as { mcpServers: Record<string, unknown> }).mcpServers['other'])
86+
})
87+
88+
it('writes the captured entry shape only when installCopilotMcpServer is called directly', () => {
89+
expect(installCopilotMcpServer()).toBe(true)
90+
expect(copilotMcpConfigPath()).toBe(path.join(TMP, 'copilot-home', 'mcp-config.json'))
6191
const ours = servers()['token-goat']!
6292
const copilots = (JSON.parse(AFTER_ADD) as { mcpServers: Record<string, Record<string, unknown>> }).mcpServers['token-goat']!
6393
expect(Object.keys(ours).sort()).toEqual(Object.keys(copilots).sort())
@@ -68,69 +98,86 @@ describe('Copilot CLI MCP registration (CAPTURE copilot mcp add/remove, 1.0.88)'
6898
expect(path.basename((ours['args'] as string[])[0]!)).toBe('token-goat.mjs')
6999
expect((ours['args'] as string[])[1]).toBe('mcp-serve')
70100
expect(isCopilotMcpServerInstalled()).toBe(true)
71-
expect(installCopilotCli().alreadyInstalled).toBe(true)
101+
expect(installCopilotMcpServer()).toBe(false)
72102
})
73103

74-
it('adds itself beside a server Copilot already holds and leaves that server as Copilot wrote it', () => {
104+
it('adds the directly installed MCP entry beside a server Copilot already holds', () => {
75105
seed(AFTER_REMOVE)
76-
installCopilotCli()
106+
expect(installCopilotMcpServer()).toBe(true)
77107
const after = servers()
78108
expect(Object.keys(after).sort()).toEqual(['other', 'token-goat'])
79109
expect(after['other']).toEqual((JSON.parse(AFTER_REMOVE) as { mcpServers: Record<string, unknown> }).mcpServers['other'])
80110
})
81111

82-
it('uninstalls to exactly what `copilot mcp remove token-goat` leaves', () => {
112+
it('uninstalls the direct MCP installation to exactly what Copilot leaves', () => {
83113
seed(AFTER_REMOVE)
84-
installCopilotCli()
85-
uninstallCopilotCli()
114+
expect(installCopilotMcpServer()).toBe(true)
115+
expect(uninstallCopilotMcpServer()).toBe(true)
86116
expect(JSON.parse(fs.readFileSync(copilotMcpConfigPath(), 'utf8'))).toEqual(JSON.parse(AFTER_REMOVE))
87117
})
88118

89-
it('removes the entry Copilot itself wrote for `copilot mcp add token-goat -- node token-goat.mjs mcp-serve`, as Copilot would', () => {
119+
it('uninstall --copilot removes a legacy MCP entry Copilot itself wrote', () => {
90120
seed(AFTER_ADD)
91121
expect(uninstallCopilotCli()).toBe(true)
92122
expect(fs.readFileSync(copilotMcpConfigPath(), 'utf8').trim()).toBe(AFTER_REMOVE.trim())
93123
})
94124

125+
it('direct MCP uninstall removes the entry Copilot itself wrote', () => {
126+
seed(AFTER_ADD)
127+
expect(uninstallCopilotMcpServer()).toBe(true)
128+
expect(fs.readFileSync(copilotMcpConfigPath(), 'utf8').trim()).toBe(AFTER_REMOVE.trim())
129+
})
130+
95131
it('deletes the file on uninstall when install created it and nothing else is left', () => {
96-
installCopilotCli()
132+
installCopilotMcpServer()
97133
expect(fs.existsSync(copilotMcpConfigPath())).toBe(true)
98-
uninstallCopilotCli()
134+
expect(uninstallCopilotMcpServer()).toBe(true)
99135
expect(fs.existsSync(copilotMcpConfigPath())).toBe(false)
100136
})
101137

102138
it('refreshes an entry that names a different Node binary instead of refusing it', () => {
103139
const stale = JSON.parse(AFTER_ADD) as { mcpServers: Record<string, Record<string, unknown>> }
104140
stale.mcpServers['token-goat']!['args'] = [path.join(TMP, 'old', 'dist', 'token-goat.mjs'), 'mcp-serve']
105141
seed(JSON.stringify(stale, null, 2))
106-
installCopilotCli()
142+
installCopilotMcpServer()
107143
expect(servers()['token-goat']!['command']).toBe(process.execPath)
108144
expect(servers()['other']).toEqual(stale.mcpServers['other'])
109145
})
110146

111147
it('replaces the hand-written entry the README used to show', () => {
112148
seed(JSON.stringify({ mcpServers: { 'token-goat': { command: 'token-goat', args: ['mcp-serve'] } } }, null, 2))
113-
installCopilotCli()
149+
installCopilotMcpServer()
114150
expect(servers()['token-goat']!['type']).toBe('local')
115151
expect(isCopilotMcpServerInstalled()).toBe(true)
116152
})
117153

118-
it('refuses a token-goat entry it did not write, before writing anything', () => {
154+
it('leaves a foreign MCP entry alone while installing Copilot hooks', () => {
119155
const foreign = JSON.stringify({ mcpServers: { 'token-goat': { type: 'http', url: 'https://example.invalid/mcp' } } }, null, 2)
120156
seed(foreign)
121-
expect(() => installCopilotCli()).toThrow(/did not write/)
157+
const result = installCopilotCli()
158+
expect(result.mcpConfigPath).toBeUndefined()
159+
expect(fs.readFileSync(copilotMcpConfigPath(), 'utf8')).toBe(foreign)
160+
expect(isCopilotMcpServerInstalled()).toBe(false)
161+
})
162+
163+
it('refuses a foreign MCP entry when the direct MCP installer is called', () => {
164+
const foreign = JSON.stringify({ mcpServers: { 'token-goat': { type: 'http', url: 'https://example.invalid/mcp' } } }, null, 2)
165+
seed(foreign)
166+
expect(() => installCopilotMcpServer()).toThrow(/did not write/)
122167
expect(fs.readFileSync(copilotMcpConfigPath(), 'utf8')).toBe(foreign)
123168
expect(fs.existsSync(copilotCliConfigPath())).toBe(false)
124169
})
125170

126-
it('leaves mcp-config.json alone on a --local install, since Copilot reads it only at user scope', () => {
171+
it('leaves a user-scope MCP entry alone on a --local hooks install', () => {
172+
seed(AFTER_ADD)
127173
const result = installCopilotCli({ local: true })
128174
expect(result.mcpConfigPath).toBeUndefined()
129-
expect(fs.existsSync(copilotMcpConfigPath())).toBe(false)
175+
expect(fs.readFileSync(copilotMcpConfigPath(), 'utf8').trim()).toBe(AFTER_ADD.trim())
176+
expect(isCopilotMcpServerInstalled()).toBe(true)
130177
})
131178

132179
it('keeps the entry on `uninstall --copilot --local`, which narrows removal to the project', () => {
133-
installCopilotCli()
180+
installCopilotMcpServer()
134181
installCopilotCli({ local: true })
135182
uninstallCopilotCli({ local: true })
136183
expect(isCopilotMcpServerInstalled()).toBe(true)

0 commit comments

Comments
 (0)