Add toggle to enable or disable MCP servers on the system prompt

This commit is contained in:
Daniel Riccio
2025-01-02 18:54:24 -05:00
committed by Matt Rubens
parent 657e2377dd
commit ed358b4e07
8 changed files with 51 additions and 5 deletions

View File

@@ -788,8 +788,10 @@ export class Cline {
throw new Error("MCP hub not available")
}
const mcpEnabled = this.providerRef.deref()?.mcpEnabled ?? true;
const { browserViewportSize, preferredLanguage } = await this.providerRef.deref()?.getState() ?? {}
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false, mcpHub, this.diffStrategy, browserViewportSize) + await addCustomInstructions(this.customInstructions ?? '', cwd, preferredLanguage)
const systemPrompt = await SYSTEM_PROMPT(cwd, this.api.getModel().info.supportsComputerUse ?? false, mcpEnabled, mcpHub, this.diffStrategy, browserViewportSize) + await addCustomInstructions(this.customInstructions ?? '', cwd, preferredLanguage)
// If the previous API request's total token usage is close to the context window, truncate the conversation history to free up space for the new request
if (previousApiReqIndex >= 0) {

View File

@@ -9,6 +9,7 @@ import { McpHub } from "../../services/mcp/McpHub"
export const SYSTEM_PROMPT = async (
cwd: string,
supportsComputerUse: boolean,
mcpEnabled: boolean,
mcpHub: McpHub,
diffStrategy?: DiffStrategy,
browserViewportSize?: string
@@ -146,6 +147,7 @@ Usage:
: ""
}
${mcpEnabled ? `
## use_mcp_tool
Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
Parameters:
@@ -173,7 +175,7 @@ Usage:
<access_mcp_resource>
<server_name>server name here</server_name>
<uri>resource URI here</uri>
</access_mcp_resource>
</access_mcp_resource>` : ''}
## ask_followup_question
Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
@@ -229,6 +231,7 @@ Your final result description here
<line_count>14</line_count>
</write_to_file>
${mcpEnabled ? `
## Example 3: Requesting to use an MCP tool
<use_mcp_tool>
@@ -247,7 +250,7 @@ Your final result description here
<access_mcp_resource>
<server_name>weather-server</server_name>
<uri>weather://san-francisco/current</uri>
</access_mcp_resource>
</access_mcp_resource>` : ''}
# Tool Use Guidelines
@@ -272,6 +275,7 @@ By waiting for and carefully considering the user's response after each tool use
====
${mcpEnabled ? `
MCP SERVERS
The Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.
@@ -675,7 +679,7 @@ However some MCP servers may be running from installed packages rather than a lo
The user may not always request the use or creation of MCP servers. Instead, they might provide tasks that can be completed with existing tools. While using the MCP SDK to extend your capabilities can be useful, it's important to understand that this is just one specialized type of task you can accomplish. You should only implement MCP servers when the user explicitly requests it (e.g., "add a tool that...").
Remember: The MCP documentation and example provided above are to help you understand and work with existing MCP servers or create new ones when requested by the user. You already have access to tools and capabilities that can be used to accomplish a wide range of tasks.
Remember: The MCP documentation and example provided above are to help you understand and work with existing MCP servers or create new ones when requested by the user. You already have access to tools and capabilities that can be used to accomplish a wide range of tasks.` : ''}
====
@@ -693,7 +697,9 @@ CAPABILITIES
? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
: ""
}
${mcpEnabled ? `
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
` : ''}
====

View File

@@ -78,7 +78,7 @@ type GlobalStateKey =
| "preferredLanguage" // Language setting for Cline's communication
| "writeDelayMs"
| "terminalOutputLineLimit"
| "mcpEnabled"
export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
uiMessages: "ui_messages.json",
@@ -96,6 +96,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
private workspaceTracker?: WorkspaceTracker
mcpHub?: McpHub
private latestAnnouncementId = "dec-10-2024" // update to some unique identifier when we add a new announcement
mcpEnabled: boolean = true
constructor(
readonly context: vscode.ExtensionContext,
@@ -130,6 +131,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.workspaceTracker = undefined
this.mcpHub?.dispose()
this.mcpHub = undefined
this.mcpEnabled = true
this.outputChannel.appendLine("Disposed all disposables")
ClineProvider.activeInstances.delete(this)
}
@@ -606,6 +608,11 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
break
}
case "mcpEnabled":
this.mcpEnabled = message.bool ?? true
await this.updateGlobalState("mcpEnabled", this.mcpEnabled)
await this.postStateToWebview()
break
case "playSound":
if (message.audioType) {
const soundPath = path.join(this.context.extensionPath, "audio", `${message.audioType}.wav`)
@@ -1056,6 +1063,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
writeDelayMs,
terminalOutputLineLimit,
fuzzyMatchThreshold,
mcpEnabled,
} = await this.getState()
const allowedCommands = vscode.workspace
@@ -1087,6 +1095,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
writeDelayMs: writeDelayMs ?? 1000,
terminalOutputLineLimit: terminalOutputLineLimit ?? 500,
fuzzyMatchThreshold: fuzzyMatchThreshold ?? 1.0,
mcpEnabled: mcpEnabled ?? true,
}
}
@@ -1188,6 +1197,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
writeDelayMs,
screenshotQuality,
terminalOutputLineLimit,
mcpEnabled,
] = await Promise.all([
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("apiModelId") as Promise<string | undefined>,
@@ -1234,6 +1244,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("writeDelayMs") as Promise<number | undefined>,
this.getGlobalState("screenshotQuality") as Promise<number | undefined>,
this.getGlobalState("terminalOutputLineLimit") as Promise<number | undefined>,
this.getGlobalState("mcpEnabled") as Promise<boolean | undefined>,
])
let apiProvider: ApiProvider
@@ -1324,6 +1335,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// Return mapped language or default to English
return langMap[vscodeLang.split('-')[0]] ?? 'English';
})(),
mcpEnabled: mcpEnabled ?? true,
}
}

View File

@@ -255,6 +255,7 @@ describe('ClineProvider', () => {
writeDelayMs: 1000,
browserViewportSize: "900x600",
fuzzyMatchThreshold: 1.0,
mcpEnabled: true,
}
const message: ExtensionMessage = {

View File

@@ -62,6 +62,7 @@ export interface ExtensionState {
preferredLanguage: string
writeDelayMs: number
terminalOutputLineLimit?: number
mcpEnabled: boolean
}
export interface ClineMessage {

View File

@@ -49,6 +49,7 @@ export interface WebviewMessage {
| "draggedImages"
| "deleteMessage"
| "terminalOutputLineLimit"
| "mcpEnabled"
text?: string
disabled?: boolean
askResponse?: ClineAskResponse

View File

@@ -48,6 +48,8 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
setScreenshotQuality,
terminalOutputLineLimit,
setTerminalOutputLineLimit,
mcpEnabled,
setMcpEnabled,
} = useExtensionState()
const [apiErrorMessage, setApiErrorMessage] = useState<string | undefined>(undefined)
const [modelIdErrorMessage, setModelIdErrorMessage] = useState<string | undefined>(undefined)
@@ -79,6 +81,7 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
vscode.postMessage({ type: "writeDelayMs", value: writeDelayMs })
vscode.postMessage({ type: "screenshotQuality", value: screenshotQuality ?? 75 })
vscode.postMessage({ type: "terminalOutputLineLimit", value: terminalOutputLineLimit ?? 500 })
vscode.postMessage({ type: "mcpEnabled", bool: mcpEnabled })
onDone()
}
}
@@ -211,6 +214,21 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
}}>
These instructions are added to the end of the system prompt sent with every request. Custom instructions set in .clinerules and .cursorrules in the working directory are also included.
</p>
<div style={{ marginBottom: 5 }}>
<VSCodeCheckbox
checked={mcpEnabled}
onChange={(e: any) => setMcpEnabled(e.target.checked)}>
<span style={{ fontWeight: "500" }}>Enable MCP Servers</span>
</VSCodeCheckbox>
<p style={{
fontSize: "12px",
marginTop: "5px",
color: "var(--vscode-descriptionForeground)",
}}>
When enabled, Cline will be able to interact with MCP servers for advanced functionality.
</p>
</div>
</div>
<div style={{ marginBottom: 5 }}>
@@ -558,6 +576,7 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
</div>
</div>
{IS_DEV && (
<>
<div style={{ marginTop: "10px", marginBottom: "4px" }}>Debug</div>

View File

@@ -41,6 +41,8 @@ export interface ExtensionStateContextType extends ExtensionState {
setScreenshotQuality: (value: number) => void
terminalOutputLineLimit?: number
setTerminalOutputLineLimit: (value: number) => void
mcpEnabled: boolean
setMcpEnabled: (value: boolean) => void
}
export const ExtensionStateContext = createContext<ExtensionStateContextType | undefined>(undefined)
@@ -61,6 +63,7 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
browserViewportSize: "900x600",
screenshotQuality: 75,
terminalOutputLineLimit: 500,
mcpEnabled: true,
})
const [didHydrateState, setDidHydrateState] = useState(false)
const [showWelcome, setShowWelcome] = useState(false)
@@ -180,6 +183,7 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
setWriteDelayMs: (value) => setState((prevState) => ({ ...prevState, writeDelayMs: value })),
setScreenshotQuality: (value) => setState((prevState) => ({ ...prevState, screenshotQuality: value })),
setTerminalOutputLineLimit: (value) => setState((prevState) => ({ ...prevState, terminalOutputLineLimit: value })),
setMcpEnabled: (value) => setState((prevState) => ({ ...prevState, mcpEnabled: value })),
}
return <ExtensionStateContext.Provider value={contextValue}>{children}</ExtensionStateContext.Provider>