Prettier backfill

This commit is contained in:
Matt Rubens
2025-01-17 14:11:28 -05:00
parent 3bcb4ff8c5
commit 60a0a824b9
174 changed files with 15715 additions and 15428 deletions

View File

@@ -40,11 +40,11 @@ const StdioConfigSchema = z.object({
args: z.array(z.string()).optional(),
env: z.record(z.string()).optional(),
alwaysAllow: AlwaysAllowSchema.optional(),
disabled: z.boolean().optional()
disabled: z.boolean().optional(),
})
const McpSettingsSchema = z.object({
mcpServers: z.record(StdioConfigSchema)
mcpServers: z.record(StdioConfigSchema),
})
export class McpHub {
@@ -63,9 +63,7 @@ export class McpHub {
getServers(): McpServer[] {
// Only return enabled servers
return this.connections
.filter((conn) => !conn.server.disabled)
.map((conn) => conn.server)
return this.connections.filter((conn) => !conn.server.disabled).map((conn) => conn.server)
}
async getMcpServersPath(): Promise<string> {
@@ -300,9 +298,9 @@ export class McpHub {
const alwaysAllowConfig = config.mcpServers[serverName]?.alwaysAllow || []
// Mark tools as always allowed based on settings
const tools = (response?.tools || []).map(tool => ({
const tools = (response?.tools || []).map((tool) => ({
...tool,
alwaysAllow: alwaysAllowConfig.includes(tool.name)
alwaysAllow: alwaysAllowConfig.includes(tool.name),
}))
console.log(`[MCP] Fetched tools for ${serverName}:`, tools)
@@ -471,28 +469,28 @@ export class McpHub {
}
// Public methods for server management
public async toggleServerDisabled(serverName: string, disabled: boolean): Promise<void> {
let settingsPath: string
try {
settingsPath = await this.getMcpSettingsFilePath()
// Ensure the settings file exists and is accessible
try {
await fs.access(settingsPath)
} catch (error) {
console.error('Settings file not accessible:', error)
throw new Error('Settings file not accessible')
console.error("Settings file not accessible:", error)
throw new Error("Settings file not accessible")
}
const content = await fs.readFile(settingsPath, "utf-8")
const config = JSON.parse(content)
// Validate the config structure
if (!config || typeof config !== 'object') {
throw new Error('Invalid config structure')
if (!config || typeof config !== "object") {
throw new Error("Invalid config structure")
}
if (!config.mcpServers || typeof config.mcpServers !== 'object') {
if (!config.mcpServers || typeof config.mcpServers !== "object") {
config.mcpServers = {}
}
@@ -500,28 +498,28 @@ export class McpHub {
// Create a new server config object to ensure clean structure
const serverConfig = {
...config.mcpServers[serverName],
disabled
disabled,
}
// Ensure required fields exist
if (!serverConfig.alwaysAllow) {
serverConfig.alwaysAllow = []
}
config.mcpServers[serverName] = serverConfig
// Write the entire config back
const updatedConfig = {
mcpServers: config.mcpServers
mcpServers: config.mcpServers,
}
await fs.writeFile(settingsPath, JSON.stringify(updatedConfig, null, 2))
const connection = this.connections.find(conn => conn.server.name === serverName)
const connection = this.connections.find((conn) => conn.server.name === serverName)
if (connection) {
try {
connection.server.disabled = disabled
// Only refresh capabilities if connected
if (connection.server.status === "connected") {
connection.server.tools = await this.fetchToolsList(serverName)
@@ -540,7 +538,9 @@ export class McpHub {
if (error instanceof Error) {
console.error("Error details:", error.message, error.stack)
}
vscode.window.showErrorMessage(`Failed to update server state: ${error instanceof Error ? error.message : String(error)}`)
vscode.window.showErrorMessage(
`Failed to update server state: ${error instanceof Error ? error.message : String(error)}`,
)
throw error
}
}
@@ -617,12 +617,11 @@ export class McpHub {
await fs.writeFile(settingsPath, JSON.stringify(config, null, 2))
// Update the tools list to reflect the change
const connection = this.connections.find(conn => conn.server.name === serverName)
const connection = this.connections.find((conn) => conn.server.name === serverName)
if (connection) {
connection.server.tools = await this.fetchToolsList(serverName)
await this.notifyWebviewOfServerChanges()
}
} catch (error) {
console.error("Failed to update always allow settings:", error)
vscode.window.showErrorMessage("Failed to update always allow settings")

View File

@@ -1,290 +1,292 @@
import type { McpHub as McpHubType } from '../McpHub'
import type { ClineProvider } from '../../../core/webview/ClineProvider'
import type { ExtensionContext, Uri } from 'vscode'
import type { McpConnection } from '../McpHub'
import type { McpHub as McpHubType } from "../McpHub"
import type { ClineProvider } from "../../../core/webview/ClineProvider"
import type { ExtensionContext, Uri } from "vscode"
import type { McpConnection } from "../McpHub"
const vscode = require('vscode')
const fs = require('fs/promises')
const { McpHub } = require('../McpHub')
const vscode = require("vscode")
const fs = require("fs/promises")
const { McpHub } = require("../McpHub")
jest.mock('vscode')
jest.mock('fs/promises')
jest.mock('../../../core/webview/ClineProvider')
jest.mock("vscode")
jest.mock("fs/promises")
jest.mock("../../../core/webview/ClineProvider")
describe('McpHub', () => {
let mcpHub: McpHubType
let mockProvider: Partial<ClineProvider>
const mockSettingsPath = '/mock/settings/path/cline_mcp_settings.json'
describe("McpHub", () => {
let mcpHub: McpHubType
let mockProvider: Partial<ClineProvider>
const mockSettingsPath = "/mock/settings/path/cline_mcp_settings.json"
beforeEach(() => {
jest.clearAllMocks()
beforeEach(() => {
jest.clearAllMocks()
const mockUri: Uri = {
scheme: 'file',
authority: '',
path: '/test/path',
query: '',
fragment: '',
fsPath: '/test/path',
with: jest.fn(),
toJSON: jest.fn()
}
const mockUri: Uri = {
scheme: "file",
authority: "",
path: "/test/path",
query: "",
fragment: "",
fsPath: "/test/path",
with: jest.fn(),
toJSON: jest.fn(),
}
mockProvider = {
ensureSettingsDirectoryExists: jest.fn().mockResolvedValue('/mock/settings/path'),
ensureMcpServersDirectoryExists: jest.fn().mockResolvedValue('/mock/settings/path'),
postMessageToWebview: jest.fn(),
context: {
subscriptions: [],
workspaceState: {} as any,
globalState: {} as any,
secrets: {} as any,
extensionUri: mockUri,
extensionPath: '/test/path',
storagePath: '/test/storage',
globalStoragePath: '/test/global-storage',
environmentVariableCollection: {} as any,
extension: {
id: 'test-extension',
extensionUri: mockUri,
extensionPath: '/test/path',
extensionKind: 1,
isActive: true,
packageJSON: {
version: '1.0.0'
},
activate: jest.fn(),
exports: undefined
} as any,
asAbsolutePath: (path: string) => path,
storageUri: mockUri,
globalStorageUri: mockUri,
logUri: mockUri,
extensionMode: 1,
logPath: '/test/path',
languageModelAccessInformation: {} as any
} as ExtensionContext
}
mockProvider = {
ensureSettingsDirectoryExists: jest.fn().mockResolvedValue("/mock/settings/path"),
ensureMcpServersDirectoryExists: jest.fn().mockResolvedValue("/mock/settings/path"),
postMessageToWebview: jest.fn(),
context: {
subscriptions: [],
workspaceState: {} as any,
globalState: {} as any,
secrets: {} as any,
extensionUri: mockUri,
extensionPath: "/test/path",
storagePath: "/test/storage",
globalStoragePath: "/test/global-storage",
environmentVariableCollection: {} as any,
extension: {
id: "test-extension",
extensionUri: mockUri,
extensionPath: "/test/path",
extensionKind: 1,
isActive: true,
packageJSON: {
version: "1.0.0",
},
activate: jest.fn(),
exports: undefined,
} as any,
asAbsolutePath: (path: string) => path,
storageUri: mockUri,
globalStorageUri: mockUri,
logUri: mockUri,
extensionMode: 1,
logPath: "/test/path",
languageModelAccessInformation: {} as any,
} as ExtensionContext,
}
// Mock fs.readFile for initial settings
;(fs.readFile as jest.Mock).mockResolvedValue(JSON.stringify({
mcpServers: {
'test-server': {
command: 'node',
args: ['test.js'],
alwaysAllow: ['allowed-tool']
}
}
}))
// Mock fs.readFile for initial settings
;(fs.readFile as jest.Mock).mockResolvedValue(
JSON.stringify({
mcpServers: {
"test-server": {
command: "node",
args: ["test.js"],
alwaysAllow: ["allowed-tool"],
},
},
}),
)
mcpHub = new McpHub(mockProvider as ClineProvider)
})
mcpHub = new McpHub(mockProvider as ClineProvider)
})
describe('toggleToolAlwaysAllow', () => {
it('should add tool to always allow list when enabling', async () => {
const mockConfig = {
mcpServers: {
'test-server': {
command: 'node',
args: ['test.js'],
alwaysAllow: []
}
}
}
describe("toggleToolAlwaysAllow", () => {
it("should add tool to always allow list when enabling", async () => {
const mockConfig = {
mcpServers: {
"test-server": {
command: "node",
args: ["test.js"],
alwaysAllow: [],
},
},
}
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
await mcpHub.toggleToolAlwaysAllow('test-server', 'new-tool', true)
await mcpHub.toggleToolAlwaysAllow("test-server", "new-tool", true)
// Verify the config was updated correctly
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers['test-server'].alwaysAllow).toContain('new-tool')
})
// Verify the config was updated correctly
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers["test-server"].alwaysAllow).toContain("new-tool")
})
it('should remove tool from always allow list when disabling', async () => {
const mockConfig = {
mcpServers: {
'test-server': {
command: 'node',
args: ['test.js'],
alwaysAllow: ['existing-tool']
}
}
}
it("should remove tool from always allow list when disabling", async () => {
const mockConfig = {
mcpServers: {
"test-server": {
command: "node",
args: ["test.js"],
alwaysAllow: ["existing-tool"],
},
},
}
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
await mcpHub.toggleToolAlwaysAllow('test-server', 'existing-tool', false)
await mcpHub.toggleToolAlwaysAllow("test-server", "existing-tool", false)
// Verify the config was updated correctly
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers['test-server'].alwaysAllow).not.toContain('existing-tool')
})
// Verify the config was updated correctly
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers["test-server"].alwaysAllow).not.toContain("existing-tool")
})
it('should initialize alwaysAllow if it does not exist', async () => {
const mockConfig = {
mcpServers: {
'test-server': {
command: 'node',
args: ['test.js']
}
}
}
it("should initialize alwaysAllow if it does not exist", async () => {
const mockConfig = {
mcpServers: {
"test-server": {
command: "node",
args: ["test.js"],
},
},
}
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
await mcpHub.toggleToolAlwaysAllow('test-server', 'new-tool', true)
await mcpHub.toggleToolAlwaysAllow("test-server", "new-tool", true)
// Verify the config was updated with initialized alwaysAllow
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers['test-server'].alwaysAllow).toBeDefined()
expect(writtenConfig.mcpServers['test-server'].alwaysAllow).toContain('new-tool')
})
})
// Verify the config was updated with initialized alwaysAllow
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers["test-server"].alwaysAllow).toBeDefined()
expect(writtenConfig.mcpServers["test-server"].alwaysAllow).toContain("new-tool")
})
})
describe('server disabled state', () => {
it('should toggle server disabled state', async () => {
const mockConfig = {
mcpServers: {
'test-server': {
command: 'node',
args: ['test.js'],
disabled: false
}
}
}
describe("server disabled state", () => {
it("should toggle server disabled state", async () => {
const mockConfig = {
mcpServers: {
"test-server": {
command: "node",
args: ["test.js"],
disabled: false,
},
},
}
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
// Mock reading initial config
;(fs.readFile as jest.Mock).mockResolvedValueOnce(JSON.stringify(mockConfig))
await mcpHub.toggleServerDisabled('test-server', true)
await mcpHub.toggleServerDisabled("test-server", true)
// Verify the config was updated correctly
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers['test-server'].disabled).toBe(true)
})
// Verify the config was updated correctly
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
const writtenConfig = JSON.parse(writeCall[1])
expect(writtenConfig.mcpServers["test-server"].disabled).toBe(true)
})
it('should filter out disabled servers from getServers', () => {
const mockConnections: McpConnection[] = [
{
server: {
name: 'enabled-server',
config: '{}',
status: 'connected',
disabled: false
},
client: {} as any,
transport: {} as any
},
{
server: {
name: 'disabled-server',
config: '{}',
status: 'connected',
disabled: true
},
client: {} as any,
transport: {} as any
}
]
it("should filter out disabled servers from getServers", () => {
const mockConnections: McpConnection[] = [
{
server: {
name: "enabled-server",
config: "{}",
status: "connected",
disabled: false,
},
client: {} as any,
transport: {} as any,
},
{
server: {
name: "disabled-server",
config: "{}",
status: "connected",
disabled: true,
},
client: {} as any,
transport: {} as any,
},
]
mcpHub.connections = mockConnections
const servers = mcpHub.getServers()
mcpHub.connections = mockConnections
const servers = mcpHub.getServers()
expect(servers.length).toBe(1)
expect(servers[0].name).toBe('enabled-server')
})
expect(servers.length).toBe(1)
expect(servers[0].name).toBe("enabled-server")
})
it('should prevent calling tools on disabled servers', async () => {
const mockConnection: McpConnection = {
server: {
name: 'disabled-server',
config: '{}',
status: 'connected',
disabled: true
},
client: {
request: jest.fn().mockResolvedValue({ result: 'success' })
} as any,
transport: {} as any
}
it("should prevent calling tools on disabled servers", async () => {
const mockConnection: McpConnection = {
server: {
name: "disabled-server",
config: "{}",
status: "connected",
disabled: true,
},
client: {
request: jest.fn().mockResolvedValue({ result: "success" }),
} as any,
transport: {} as any,
}
mcpHub.connections = [mockConnection]
mcpHub.connections = [mockConnection]
await expect(mcpHub.callTool('disabled-server', 'some-tool', {}))
.rejects
.toThrow('Server "disabled-server" is disabled and cannot be used')
})
await expect(mcpHub.callTool("disabled-server", "some-tool", {})).rejects.toThrow(
'Server "disabled-server" is disabled and cannot be used',
)
})
it('should prevent reading resources from disabled servers', async () => {
const mockConnection: McpConnection = {
server: {
name: 'disabled-server',
config: '{}',
status: 'connected',
disabled: true
},
client: {
request: jest.fn()
} as any,
transport: {} as any
}
it("should prevent reading resources from disabled servers", async () => {
const mockConnection: McpConnection = {
server: {
name: "disabled-server",
config: "{}",
status: "connected",
disabled: true,
},
client: {
request: jest.fn(),
} as any,
transport: {} as any,
}
mcpHub.connections = [mockConnection]
mcpHub.connections = [mockConnection]
await expect(mcpHub.readResource('disabled-server', 'some/uri'))
.rejects
.toThrow('Server "disabled-server" is disabled')
})
})
await expect(mcpHub.readResource("disabled-server", "some/uri")).rejects.toThrow(
'Server "disabled-server" is disabled',
)
})
})
describe('callTool', () => {
it('should execute tool successfully', async () => {
// Mock the connection with a minimal client implementation
const mockConnection: McpConnection = {
server: {
name: 'test-server',
config: JSON.stringify({}),
status: 'connected' as const
},
client: {
request: jest.fn().mockResolvedValue({ result: 'success' })
} as any,
transport: {
start: jest.fn(),
close: jest.fn(),
stderr: { on: jest.fn() }
} as any
}
describe("callTool", () => {
it("should execute tool successfully", async () => {
// Mock the connection with a minimal client implementation
const mockConnection: McpConnection = {
server: {
name: "test-server",
config: JSON.stringify({}),
status: "connected" as const,
},
client: {
request: jest.fn().mockResolvedValue({ result: "success" }),
} as any,
transport: {
start: jest.fn(),
close: jest.fn(),
stderr: { on: jest.fn() },
} as any,
}
mcpHub.connections = [mockConnection]
mcpHub.connections = [mockConnection]
await mcpHub.callTool('test-server', 'some-tool', {})
await mcpHub.callTool("test-server", "some-tool", {})
// Verify the request was made with correct parameters
expect(mockConnection.client.request).toHaveBeenCalledWith(
{
method: 'tools/call',
params: {
name: 'some-tool',
arguments: {}
}
},
expect.any(Object)
)
})
// Verify the request was made with correct parameters
expect(mockConnection.client.request).toHaveBeenCalledWith(
{
method: "tools/call",
params: {
name: "some-tool",
arguments: {},
},
},
expect.any(Object),
)
})
it('should throw error if server not found', async () => {
await expect(mcpHub.callTool('non-existent-server', 'some-tool', {}))
.rejects
.toThrow('No connection found for server: non-existent-server')
})
})
})
it("should throw error if server not found", async () => {
await expect(mcpHub.callTool("non-existent-server", "some-tool", {})).rejects.toThrow(
"No connection found for server: non-existent-server",
)
})
})
})