Skip to content
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

feat: support MCP server and client #4335

Merged
merged 40 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
9bd7924
feat: mcp server client poc
life2015 Jan 21, 2025
65e12be
feat: introduce MCP tools contribution
life2015 Jan 21, 2025
b99e11d
fix: 修复 mcp sdk 引入类型问题
ensorrow Jan 22, 2025
9520f4c
feat: add builtin MCP server
life2015 Jan 22, 2025
c54b20f
fix: mcp types fix
life2015 Jan 22, 2025
83fc2b7
fix: mcp types fix2
life2015 Jan 22, 2025
bafda53
feat: sumi mcp builtin sever
life2015 Jan 23, 2025
301df94
feat: code optimization
life2015 Jan 24, 2025
6d94523
feat: support llm tool call streaming and ui, more mcp tools
life2015 Feb 7, 2025
5de2d5e
feat: enhance language model error handling and streaming
ensorrow Feb 10, 2025
96b3331
feat: mcp tools grouped by clientId, add mcp tools panel
life2015 Feb 10, 2025
c4e719c
feat: add openai compatible api preferences
ensorrow Feb 11, 2025
04e954a
feat: support chat history in language model request
life2015 Feb 11, 2025
fa713fd
feat: add MCP server configuration support via preferences
life2015 Feb 11, 2025
7703231
feat: implement readfile & readdir tools
ensorrow Feb 11, 2025
67c8b2b
fix: tool impl bugs
ensorrow Feb 11, 2025
384c73d
Merge branch 'feat/mcp-server-client-poc-2' of https://github.com/ope…
ensorrow Feb 11, 2025
d56fdce
refactor: use design system variables in ChatToolRender styles
life2015 Feb 11, 2025
e00b72f
refactor: improve logging and revert some unnecessary optimization
life2015 Feb 12, 2025
15e612e
fix: logger not work in node.js
life2015 Feb 12, 2025
e120ad5
fix: mcp tool render fix
life2015 Feb 12, 2025
8aec9b2
feat: add MCP and custom LLM config
life2015 Feb 13, 2025
8ddda06
Merge branch 'main' into feat/mcp-server-client-poc-2
life2015 Feb 13, 2025
830a403
fix: build error fix
life2015 Feb 13, 2025
590818a
fix: lint fix
life2015 Feb 13, 2025
4752a83
fix: lint fix
life2015 Feb 13, 2025
027284e
fix: lint error fix
life2015 Feb 13, 2025
08374f2
feat: format the tool call error message
ensorrow Feb 14, 2025
3cf5bc5
feat: add doc, lint fix, create file tool fix
life2015 Feb 17, 2025
8eb3a83
Merge branch 'main' into feat/mcp-server-client-poc-2
life2015 Feb 17, 2025
533c1af
fix: lint fix
life2015 Feb 17, 2025
4777ed7
feat: add llmcontext service (#4374)
Aaaaash Feb 17, 2025
0fd9e82
feat: update chat agent prompt provider to use serialized context
Aaaaash Feb 17, 2025
328dadf
fix: build error
Aaaaash Feb 17, 2025
b236396
feat: close selector when click outside
Aaaaash Feb 17, 2025
4037afd
chore: import order
Aaaaash Feb 17, 2025
86efa1a
Merge branch 'main' into feat/mcp-server-client-poc-2
life2015 Feb 18, 2025
c942832
Merge branch 'main' into feat/mcp-server-client-poc-2
life2015 Feb 18, 2025
956b3db
feat: run terminal cmd tool (#4383)
Aaaaash Feb 18, 2025
50a4f78
feat: add some unit tests
life2015 Feb 18, 2025
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,5 @@ tools/workspace
# jupyter
.ipynb_checkpoints

*.tsbuildinfo
*.tsbuildinfo
.env
6 changes: 3 additions & 3 deletions configs/ts/tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@
{
"path": "./references/tsconfig.design.json"
},
{
"path": "./references/tsconfig.addons.json"
},
{
"path": "./references/tsconfig.ai-native.json"
},
Expand All @@ -174,9 +177,6 @@
{
"path": "./references/tsconfig.outline.json"
},
{
"path": "./references/tsconfig.addons.json"
},
{
"path": "./references/tsconfig.startup.json"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/addons/src/browser/file-search.contribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ export class FileSearchQuickCommandHandler {
return results;
}

protected async getQueryFiles(fileQuery: string, alreadyCollected: Set<string>, token: CancellationToken) {
async getQueryFiles(fileQuery: string, alreadyCollected: Set<string>, token: CancellationToken) {
const roots = await this.workspaceService.roots;
const rootUris: string[] = roots.map((stat) => new URI(stat.uri).codeUri.fsPath);
const files = await this.fileSearchService.find(
Expand Down
225 changes: 225 additions & 0 deletions packages/ai-native/MCP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
# Model Control Protocol (MCP) Documentation

## Overview

The Model Control Protocol (MCP) is an integration layer that enables IDE capabilities to be exposed to AI models through a standardized interface. It provides a set of tools that allow AI models to interact with the IDE environment, manipulate files, and perform various operations.

## Architecture

Component Relationships:

```
┌─────────────────────┐
│ MCPServerManager │
│ (Per Browser Tab) │
└─────────┬───────────┘
│ manages
┌─────────────────────┐ ┌───────────────────┐
│ MCPServerRegistry │◄──────────┤ Builtin/External │
│ (Frontend Proxy) │ register │ MCP Servers │
└─────────┬───────────┘ tools └───────────────────┘
│ forwards
┌─────────────────────┐ ┌─────────────────────────────┐
│ SumiMCPServerBackend│◄──────────┤ ToolInvocationRegistryManager│
│ (Browser<->Node.js)│ uses │ (Registry per Client) │
└─────────┬───────────┘ └─────────────┬───────────────┘
│ │
│ executes │ manages
▼ ▼
┌─────────────────────┐ ┌─────────────────────────┐
│ Tool Handlers │ │ ToolInvocationRegistry │
│ (Implementation) │ │ (Available Tools) │
└─────────────────────┘ └─────────────────────────┘
```

### Core Components

1. **MCPServerManager**

- Manages multiple MCP servers
- Handles tool registration and invocation
- Maintains server lifecycle (start/stop)
- Each browser tab has its own MCPServerManager instance

2. **MCPServerRegistry**

- Frontend proxy service for MCP
- Registers and manages MCP tools
- Handles tool invocations

3. **SumiMCPServerBackend**

- Backend service that bridges browser and Node.js layers
- Manages tool registration and invocation
- Handles communication between frontend and backend

4. **ToolInvocationRegistry**

- Registry for all available function calls for agents
- Manages tool registration and lookup
- Maintains a map of tool IDs to their implementations
- Supports tool registration, retrieval, and unregistration

5. **ToolInvocationRegistryManager**
- Manages multiple ToolInvocationRegistry instances
- Each instance is associated with a specific clientId
- Provides registry creation, retrieval, and removal
- Ensures isolation between different client contexts

### Server Types

1. **Builtin MCP Server**

- Provides core IDE capabilities
- Integrated directly into the IDE

2. **External MCP Servers**
- Can be added dynamically
- Configured with name, command, args, and environment variables

## Available Tools

The MCP system provides several built-in tools for file and IDE operations:

### File Operations

- `readFile`: Read contents of a file with line range support
- `listDir`: List contents of a directory
- `createNewFileWithText`: Create a new file with specified content
- `findFilesByNameSubstring`: Search for files by name
- `getFileTextByPath`: Get the content of a file by path
- `replaceOpenEditorFile`: Replace content in the current editor
- `replaceOpenEditorFileByDiffPreviewer`: Replace content with diff preview

### Editor Operations

- `getCurrentFilePath`: Get path of current open file
- `getSelectedText`: Get currently selected text
- `getOpenEditorFileText`: Get text from open editor

### Diagnostics

- `getDiagnosticsByPath`: Get diagnostics for a specific file
- `getOpenEditorFileDiagnostics`: Get diagnostics for open editor

## Tool Structure

Each MCP tool follows a standard structure:

```typescript
interface MCPTool {
name: string;
description: string;
inputSchema: any;
providerName: string;
}

interface MCPToolDefinition {
name: string;
description: string;
inputSchema: any;
handler: (
args: any,
logger: MCPLogger,
) => Promise<{
content: { type: string; text: string }[];
isError?: boolean;
}>;
}
```

## Usage Examples

### Registering a New Tool

```typescript
@Domain(MCPServerContribution)
export class MyCustomTool implements MCPServerContribution {
registerMCPServer(registry: IMCPServerRegistry): void {
registry.registerMCPTool({
name: 'my_custom_tool',
description: 'Description of what the tool does',
inputSchema: zodToJsonSchema(myInputSchema),
handler: async (args, logger) => {
// Tool implementation
return {
content: [{ type: 'text', text: 'Result' }],
};
},
});
}
}
```

### Adding External MCP Server - Configuration

You can add external MCP servers through the `ai.native.mcp.servers` configuration in IDE settings. The configuration format is as follows:

```json
{
"ai.native.mcp.servers": [
{
"name": "server-name",
"command": "command-to-execute",
"args": ["command-arguments"],
"env": {
"ENV_VAR_NAME": "env-var-value"
}
}
]
}
```

Example configuration:

```json
{
"ai.native.mcp.servers": [
{
"name": "filesystem",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/workspace"],
"env": {}
}
]
}
```

## Best Practices

1. **Tool Implementation**

- Always validate input using schemas (e.g., Zod)
- Provide clear error messages
- Use the logger for debugging and tracking
- Handle errors gracefully

2. **Server Management**

- Initialize servers only when needed
- Clean up resources when servers are stopped
- Handle server lifecycle events properly

3. **Tool Usage**
- Check tool availability before use
- Handle tool invocation errors
- Use appropriate tools for specific tasks
- Consider performance implications (e.g., reading entire files vs. line ranges)

## Error Handling

Tools should return errors in a standardized format:

```typescript
{
content: [{
type: 'text',
text: 'Error: <error message>'
}],
isError: true
}
```
Loading
Loading