-
Notifications
You must be signed in to change notification settings - Fork 448
feat: add terminal command execution tool with user approval #4398
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ada2905
feat: add terminal command execution tool with user approval
Aaaaash 4d98c5e
fix: types
Aaaaash c66eb52
chore: improve style
Aaaaash 61ad7ed
chore: i18n
Aaaaash 7e7e3aa
chore: i18n
Aaaaash 1d3487f
Merge branch 'main' into feat/add-run-cmd-tool-view
Aaaaash File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
97 changes: 97 additions & 0 deletions
97
packages/ai-native/src/browser/mcp/tools/components/Terminal.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import React, { memo, useCallback, useMemo, useState } from 'react'; | ||
|
|
||
| import { useInjectable } from '@opensumi/ide-core-browser'; | ||
| import { Button, Icon } from '@opensumi/ide-core-browser/lib/components'; | ||
| import { localize } from '@opensumi/ide-core-common'; | ||
|
|
||
| import { IMCPServerToolComponentProps } from '../../../types'; | ||
| import { RunCommandHandler } from '../handlers/RunCommand'; | ||
|
|
||
| import styles from './index.module.less'; | ||
|
|
||
| function getResult(raw: string) { | ||
| const result: { | ||
| isError?: boolean; | ||
| text?: string; | ||
| } = {}; | ||
|
|
||
| try { | ||
| const data: { | ||
| content: { type: string; text: string }[]; | ||
| isError?: boolean; | ||
| } = JSON.parse(raw); | ||
| if (data.isError) { | ||
| result.isError = data.isError; | ||
| } | ||
|
|
||
| if (data.content) { | ||
| result.text = data.content.map((item) => item.text).join('\n'); | ||
| } | ||
|
|
||
| return result; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| export const TerminalToolComponent = memo((props: IMCPServerToolComponentProps) => { | ||
| const { args, toolCallId } = props; | ||
| const handler = useInjectable<RunCommandHandler>(RunCommandHandler); | ||
| const [disabled, toggleDisabled] = useState(false); | ||
|
|
||
| const handleClick = useCallback((approval: boolean) => { | ||
| if (!toolCallId) { | ||
| return; | ||
| } | ||
| handler.handleApproval(toolCallId, approval); | ||
| toggleDisabled(true); | ||
| }, []); | ||
|
|
||
| const output = useMemo(() => { | ||
| if (props.result) { | ||
| return getResult(props.result); | ||
| } | ||
| return null; | ||
| }, [props]); | ||
|
|
||
| return ( | ||
| <div className={styles.run_cmd_tool}> | ||
| {props.state === 'result' && ( | ||
| <div> | ||
| <div className={styles.command_title}> | ||
| <Icon icon='terminal' /> | ||
| <span>{localize('ai.native.mcp.terminal.output')}</span> | ||
| </div> | ||
| {output ? ( | ||
| <div className={styles.command_content}> | ||
| <code>{output.text}</code> | ||
| </div> | ||
| ) : ( | ||
| '' | ||
| )} | ||
| </div> | ||
| )} | ||
|
|
||
| {props.state === 'complete' && args?.require_user_approval && ( | ||
| <div> | ||
| <div className={styles.command_title}> | ||
| <Icon icon='terminal' /> | ||
| <span>{localize('ai.native.ncp.terminal.allow-question')}</span> | ||
| </div> | ||
| <p className={styles.command_content}> | ||
| <code>$ {args.command}</code> | ||
| </p> | ||
| <p className={styles.comand_description}>{args.explanation}</p> | ||
| <div className={styles.cmmand_footer}> | ||
| <Button type='link' size='small' disabled={disabled} onClick={() => handleClick(true)}> | ||
| {localize('ai.native.mcp.terminal.allow')} | ||
| </Button> | ||
| <Button type='link' size='small' disabled={disabled} onClick={() => handleClick(false)}> | ||
| {localize('ai.native.mcp.terminal.deny')} | ||
| </Button> | ||
| </div> | ||
| </div> | ||
| )} | ||
| </div> | ||
| ); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
packages/ai-native/src/browser/mcp/tools/handlers/RunCommand.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| import z from 'zod'; | ||
|
|
||
| import { Autowired, Injectable } from '@opensumi/di'; | ||
| import { AppConfig } from '@opensumi/ide-core-browser'; | ||
| import { ITerminalController, ITerminalGroupViewService } from '@opensumi/ide-terminal-next'; | ||
| import { Deferred } from '@opensumi/ide-utils/lib/promises'; | ||
|
|
||
| import { MCPLogger } from '../../../types'; | ||
|
|
||
| const color = { | ||
| italic: '\x1b[3m', | ||
| reset: '\x1b[0m', | ||
| }; | ||
|
|
||
| export const inputSchema = z.object({ | ||
| command: z.string().describe('The terminal command to execute'), | ||
| is_background: z.boolean().describe('Whether the command should be run in the background'), | ||
| explanation: z | ||
| .string() | ||
| .describe('One sentence explanation as to why this command needs to be run and how it contributes to the goal.'), | ||
| require_user_approval: z | ||
| .boolean() | ||
| .describe( | ||
| "Whether the user must approve the command before it is executed. Only set this to false if the command is safe and if it matches the user's requirements for commands that should be executed automatically.", | ||
| ), | ||
| }); | ||
|
Aaaaash marked this conversation as resolved.
|
||
|
|
||
| @Injectable() | ||
| export class RunCommandHandler { | ||
| @Autowired(ITerminalController) | ||
| protected readonly terminalController: ITerminalController; | ||
|
|
||
| @Autowired(AppConfig) | ||
| protected readonly appConfig: AppConfig; | ||
|
|
||
| @Autowired(ITerminalGroupViewService) | ||
| protected readonly terminalView: ITerminalGroupViewService; | ||
|
|
||
| private approvalDeferredMap = new Map<string, Deferred<boolean>>(); | ||
|
Aaaaash marked this conversation as resolved.
|
||
|
|
||
| private terminalId = 0; | ||
|
|
||
| getShellLaunchConfig(command: string) { | ||
| return { | ||
| name: `MCP:Terminal_${this.terminalId++}`, | ||
| cwd: this.appConfig.workspaceDir, | ||
| args: ['-c', command], | ||
| }; | ||
| } | ||
|
|
||
| async handler(args: z.infer<typeof inputSchema> & { toolCallId: string }, logger: MCPLogger) { | ||
| if (args.require_user_approval) { | ||
| const def = new Deferred<boolean>(); | ||
| this.approvalDeferredMap.set(args.toolCallId, def); | ||
| const approval = await def.promise; | ||
| if (!approval) { | ||
| return { | ||
| isError: false, | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: 'User rejection', | ||
| }, | ||
| ], | ||
| }; | ||
| } | ||
| } | ||
|
Aaaaash marked this conversation as resolved.
|
||
| const terminalClient = await this.terminalController.createTerminalWithWidget({ | ||
| config: this.getShellLaunchConfig(args.command), | ||
| closeWhenExited: false, | ||
| }); | ||
|
|
||
| this.terminalController.showTerminalPanel(); | ||
|
|
||
| const result: { type: string; text: string }[] = []; | ||
| const def = new Deferred<{ isError?: boolean; content: { type: string; text: string }[] }>(); | ||
|
|
||
| terminalClient.onOutput((e) => { | ||
| result.push({ | ||
| type: 'text', | ||
| text: e.data.toString(), | ||
| }); | ||
| }); | ||
|
|
||
| terminalClient.onExit((e) => { | ||
| const isError = e.code !== 0; | ||
| def.resolve({ | ||
| isError, | ||
| content: result, | ||
| }); | ||
|
|
||
| terminalClient.term.writeln( | ||
| `\n${color.italic}> Command ${args.command} executed successfully. Terminal will close in ${ | ||
| 3000 / 1000 | ||
| } seconds.${color.reset}\n`, | ||
| ); | ||
|
|
||
| setTimeout(() => { | ||
| terminalClient.dispose(); | ||
| this.terminalView.removeWidget(terminalClient.id); | ||
| }, 3000); | ||
| }); | ||
|
|
||
| return def.promise; | ||
| } | ||
|
Aaaaash marked this conversation as resolved.
|
||
|
|
||
| handleApproval(callId: string, approval: boolean) { | ||
| if (!this.approvalDeferredMap.has(callId)) { | ||
| return; | ||
| } | ||
|
|
||
| const def = this.approvalDeferredMap.get(callId); | ||
| def?.resolve(approval); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.