tencent cloud

MCP Documentation

Download
Focus Mode
Font Size
Last updated: 2026-09-30 18:15:50
AI-Translated

Overview

MCP (Model Context Protocol) is an open standard that allows CodeBuddy to integrate with external tools and data sources. With MCP, you can extend CodeBuddy's features and connect to various external services, databases, APIs, and more.

Core Concepts

MCP Server

An MCP server is an independent process that provides tools, resources, and prompts. CodeBuddy communicates with these servers through different transport protocols.

MCP Prompts Integration

MCP servers can provide Prompts (prompt templates), which are automatically converted into CodeBuddy slash commands. When an MCP server is connected:
Prompts provided by the server are automatically registered as slash commands.
The command name format is: /server name:prompt name
Supports dynamic parameters and collects user input through an interactive interface.
When a command is executed, the prompts/get API of the MCP server is called to obtain the full content.
Supports real-time monitoring of configuration changes and automatically updates the list of available commands.

Transport Type

STDIO: communicates with local processes through standard input and output.
SSE: communicates with remote services through Server-Sent Events.
HTTP: communicates with remote services through HTTP streaming.

Configuration Scope

user: global user configuration, applied to all projects.
project: project-level configuration, applied to specific projects.
local: local configuration, applied only to the current session or workspace.
For services with the same name (that is, configurations with the same name in multiple scopes), the effective priority is: local > project > user

Security Approval Mechanism

MCP servers in the project scope require user approval upon first connection to ensure security. The system displays the server details, and the user can choose to approve or reject the connection.

Approval in Non-Interactive Mode (-p/--print)

In non-interactive mode (for example, when the -p/--print parameter is used), approval cannot be performed through the UI, so you need to preconfigure allowed MCP servers through the --settings parameter:
# Method 1: Allow all project MCP servers
codebuddy --settings '{"enableAllProjectMcpServers": true}' -p "your prompt"

# Method 2: Allow specific MCP servers
codebuddy --settings '{"enabledMcpjsonServers": ["server-name-1", "server-name-2"]}' -p "your prompt"

Tool Permission Management

MCP tools support a complete permission management system, allowing precise control over which tools can be used:

Permission Rule Types

The permission system supports three rule types (listed by priority):
1. Deny rule (deny) - Prevents the use of specified tools (highest priority).
2. Ask rule (ask) - Requires user confirmation before a tool is used (overrides allow rules).
3. Allow rule (allow) - Allows tools to be used without manual approval.

MCP Permission Rule Format

The format of an MCP tool name is mcp__<server_name>__<tool_name>, with segments separated by double underscores __ (single underscores in names are treated as regular characters). Rules can be written in three ways:
Server-Level Permissions
mcp__<server_name>
Matches all tools with the prefix mcp__<server_name>__, that is, all tools of this server. Equivalent notation: mcp__<server_name>__*.
Tool-Level Permissions
mcp__<server_name>__<tool_name>
Match only this one tool.
All MCP Tools
mcp__*
Matches all MCP tools and is valid only in deny and ask. Placing it in allow has no effect. To allow tools in batches, list them by server.
Note:
Rules are case-insensitive. Symbols such as hyphens and periods are treated as underscores, so mcp__web-search is equivalent to mcp__web_search.
* can only replace the entire last segment. mcp__git* and mcp__github__get_* do not match any tools, and no error is reported.
MCP tools only recognize rules that start with mcp__. A bare * has no effect on them. To deny all MCP tools, write "deny": ["mcp__*"].

Configuration Example

Approving All Tools on the Server
Allow all tools with the prefix mcp__github__.
{
"permissions": {
"allow": [
"mcp__github"
]
}
}
Approving Only Specific Tools
{
"permissions": {
"allow": [
"mcp__github__get_issue",
"mcp__github__list_issues"
]
}
}
Denying Specific Tools
{
"permissions": {
"deny": [
"mcp__dangerous_server__delete_file"
]
}
}
Denying All Tools on a Server
Deny all tools with the prefix mcp__filesystem__.
{
"permissions": {
"deny": [
"mcp__filesystem"
]
}
}
Denying All MCP Tools
{
"permissions": {
"deny": [
"mcp__*"
]
}
}

Configuration Files

Configuration File Location

Configuration files use a priority mechanism. The system searches for the first existing file in priority order and reads it. When writing, if a file already exists, the system writes to the first existing file. If none exist, the system creates the file with the highest priority.

USER Scope

Priority order (from highest to lowest):
1. ~/.codebuddy/.mcp.json (recommended)
2. ~/.codebuddy/mcp.json (deprecated)
3. ~/.codebuddy.json (legacy configuration file)
Read rules: The system searches for the first existing file in the order described above and reads its content.
Write rules:
If any of the above files exist, write to the first existing file.
If none exist, create ~/.codebuddy/.mcp.json (highest priority).

PROJECT Scope

Priority order (from highest to lowest):
1. <project_root>/.mcp.json (recommended)
2. <project_root>/mcp.json (deprecated)
Read rules: The system searches for the first existing file in the order described above and reads its content.
Write rules:
If any of the above files exist, write to the first existing file.
If none exist, create <project_root>/.mcp.json (highest priority).

LOCAL Scope

Configurations in the local scope are actually stored in the configuration file of the user scope, where the projects field is used to distinguish local configurations of different projects.
File path: ~/.codebuddy.json#/projects/<workspace_path>
#/projects/<workspace_path> uses JSON Pointer syntax to point to a specific location in a JSON document. For details about JSON Pointer, see https://datatracker.ietf.org/doc/html/rfc6901.
Note:
The system does not merge the content of multiple configuration files in the same scope. Instead, it uses only the first existing file.
For an example, see the configuration file format description below.

Configuration File Format

MCP configuration files support the JSONC (JSON with Comments) format, allowing comments to be added to configurations to improve readability and maintainability.

Features Supported by JSONC

Single-line comments: Use // to add inline or end-of-line comments.
Multi-line comments: Use /* */ to add block comments.
Trailing commas: A comma can be added after the last element of an array or object.

Basic Configuration Format

{
// MCP server configuration
"mcpServers": {
"server-name": {
"type": "stdio|sse|http",
"command": "Command path",
"args": ["parameter1", "parameter2"],
"env": {
"ENV_VAR": "value"
},
"url": "http://example.com/mcp",
"headers": {
"Authorization": "Bearer token"
},
"description": "Server description"
}
},
// The projects field is valid only in files within the user scope and is used to identify configurations in the local scope.
"projects": {
"/path/to/project": {
"mcpServers": {
"local-server": {
"type": "stdio",
"command": "./local-tool"
}
}
}
}
}

Complete Annotated Example

{
// MCP Server Configuration for CodeBuddy
// This file configures the MCP servers used by the project.
"mcpServers": {
/*
* Filesystem Server
* Provides file system access capabilities.
* Documentation: https://github.com/modelcontextprotocol/servers
*/
"filesystem": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/path/to/workspace", // Workspace directory path
],
"env": {
"DEBUG": "true", // Enable debug mode
},
},
// HTTP API server example
"api-server": {
"type": "http",
"url": "http://localhost:3000/mcp", // Local development server
"headers": {
"Authorization": "Bearer your-token",
},
},
},
// List of disabled servers (for reference)
"disabledMcpServers": [
"deprecated-server",
],
}
Note:
Standard JSON format files remain fully compatible.
A clear error message is provided when a parsing error occurs.

**Note**: The `type` field is optional. If not specified, the system automatically infers it based on the configuration content:
- When the `command` field is included, the type is inferred as `stdio`.
- When the `url` field is included, the type is inferred as `http`.

It is recommended to explicitly specify the `type` field to ensure configuration accuracy.

### Environment variable expansion

MCP configuration supports environment variable expansion, allowing you to reference system environment variables in the configuration. This is particularly useful for sharing configurations across teams, managing sensitive information such as API keys and tokens, and supporting environment-specific configurations for development, testing, and production.

#### Supported Syntax

- **`${VAR_NAME}`** - Expands to the value of the environment variable VAR_NAME.
- **`${VAR_NAME:-default_value}`** - If VAR_NAME is not set, the default value is used.

#### Variable Naming Rules

- Variable names must start with an uppercase letter or an underscore `[A-Z_]`.
- Subsequent characters can only be uppercase letters, digits, or underscores `[A-Z0-9_]*`.
- Variables that are lowercase, mixed-case, or start with a digit are not expanded.

#### Supported Configuration Fields

Environment variables can be expanded in the following configuration fields:

**STDIO Type Configuration**:
- `command` - Path to the executable file or the command.
- `args` - Each parameter in the command line parameter list.
- `env` - Environment variable values (keys are not expanded).

**SSE/HTTP/Remote Type Configuration**:
- `url` - Service endpoint URL.
- `headers` - HTTP request header values (keys are not expanded).

#### Error Handling

**Behavior When Environment Variables Are Not Set**:
- If the environment variable is not set and has a default value, the default value is used.
- If the environment variable is not set and has no default value, keep the original placeholder (`${VAR}`) and report a WARNING message in diagnostics.

This means that the configuration does not fail due to missing environment variables. Instead, it retains the placeholders and issues a warning.

#### Example Configuration

**Example 1: STDIO Type Server Using Environment Variables**
```json
{
"mcpServers": {
"python-tools": {
"type": "stdio",
"command": "${PYTHON_PATH:-python}",
"args": [
"-m",
"my_mcp_server",
"--config",
"${CONFIG_DIR:-/etc/config}"
],
"env": {
"PYTHONPATH": "${PYTHON_LIB_PATH}",
"DEBUG": "${DEBUG_MODE:-false}",
"API_KEY": "${API_KEY}"
}
}
}
}
Example 2: HTTP Type Server Using Environment Variables and Default Values
{
"mcpServers": {
"api-server": {
"type": "http",
"url": "${API_BASE_URL:-https://api.example.com}/mcp",
"headers": {
"Authorization": "Bearer ${API_TOKEN}",
"X-API-Version": "${API_VERSION:-v1}",
"User-Agent": "CodeBuddy/${CODEBUDDY_VERSION:-1.0}"
}
}
}
}

Common Use Cases

1. Team Shared Configuration
# Using Environment Variables in .mcp.json
# Each team member sets environment variables locally.
export API_TOKEN="their-personal-token"
export LOCAL_TOOL_PATH="/home/user/tools"
2. Environment-Specific Configuration
# Development Environment
export API_BASE_URL="http://localhost:3000"

# Production Environment
export API_BASE_URL="https://api.production.com"
3. Manage sensitive information
{
"headers": {
"Authorization": "Bearer ${MY_API_KEY}"
}
}
Store the API key in an environment variable instead of writing it directly in the configuration file.

Diagnosis and Debugging

When environment variables in the configuration are expanded, you can view the expansion results in the following ways:
1. If an environment variable is not set and has no default value, the system issues a WARNING diagnostic.
2. You can use the /mcp command to view MCP server configuration and diagnostic information.
3. All missing environment variables are listed in the diagnostic message.
Sample diagnostic message:
Missing environment variables: API_TOKEN, DATABASE_URL

Detailed Configuration Structure

MCP server configurations have different structures depending on the transport type:

STDIO Configuration

Communicate with local processes through standard input and output.
Field
Type
Required
Description
type
string
Yes
Fixed value "stdio"
command
string
Yes
Executable file path or command
args
Array&lt;string&gt;
No
Command-line argument list
env
Object
No
Environment variable key-value pairs
defer_loading
boolean
No
Whether to lazily load tools (default: false)
tools
Object
No
Tool-level configuration that can override server-level settings
Example:
{
"type": "stdio",
"command": "python",
"args": ["-m", "my_mcp_server"],
"env": {
"PYTHONPATH": "/path/to/tools",
"DEBUG": "true"
}
}

SSE Configuration

Communicate with remote services through Server-Sent Events.
Field
Type
Required
Description
type
string
Yes
Fixed value "sse"
url
string
Yes
SSE endpoint URL
headers
Object
No
HTTP request header key-value pairs
defer_loading
boolean
No
Whether to lazily load tools (default: false)
tools
Object
No
Tool-level configuration that can override server-level settings
Example:
{
"type": "sse",
"url": "https://api.example.com/mcp/sse",
"headers": {
"Authorization": "Bearer your-api-token",
"X-API-Version": "v1"
}
}

HTTP Configuration

Communicate with remote services through HTTP streaming.
Field
Type
Required
Description
type
string
Yes
Fixed value "http"
url
string
Yes
HTTP endpoint URL
headers
Object
No
HTTP request header key-value pairs
defer_loading
boolean
No
Whether to lazily load tools (default: false)
tools
Object
No
Tool-level configuration that can override server-level settings
Example:
{
"type": "http",
"url": "https://mcp.example.com/api/v1",
"headers": {
"Authorization": "Bearer secret-token",
"Content-Type": "application/json"
}
}

Deferred Loading (defer_loading)

When an MCP server provides a large number of tools, you can use the defer_loading configuration to lazy-load tools, reducing context consumption and improving the accuracy of model tool selection.

Working Principles

Tools with defer_loading: true are not loaded into the model context during the initial request.
The model can search for these lazy-loaded tools through the ToolSearch tool.
Searched tools are activated and become available in subsequent requests.
The activated state is maintained for the current session.

Server-Level Configuration

Set all tools on the server to lazy loading:
{
"mcpServers": {
"my-server": {
"type": "stdio",
"command": "my-mcp-server",
"defer_loading": true
}
}
}

Tool-Level Configuration

You can override server-level settings for individual tools:
{
"mcpServers": {
"my-server": {
"type": "stdio",
"command": "my-mcp-server",
"defer_loading": true,
"tools": {
"frequently_used_tool": {
"defer_loading": false
}
}
}
}
}

Inheritance Rules

Server defer_loading
Tool defer_loading
Final Result
true
Not set
true (inherited)
true
false
false (overridden)
false/Not set
Not set
false
false/Not set
true
true (overridden)

Session-Level / Proxy-Level Overrides

In addition to the static defer_loading in the MCP configuration, you can use the Defer(...) / NoDefer(...) modifiers in the --tools parameter or custom agent frontmatter to temporarily change the lazy-loading state of a tool or a group of tools:
# Temporarily put the entire set of GitHub MCP tools into lazy loading
codebuddy --tools "default,Defer(mcp__github__*)"

# Force the MCP tool to be directly available this time, even if it is lazy-loaded by default.
codebuddy --tools "default,NoDefer(mcp__time__current_time)"
Modifiers take precedence over the static defer_loading configuration in MCP, and NoDefer always overrides Defer. For details, see Tool Lazy Loading Override.

Application Scenarios

Large number of tools: When an MCP server provides more than 30 tools.
Reduce Costs: Reduce token consumption per request.
Improve accuracy: Enable the model to make more accurate choices among fewer tools.

Command Line Usage

Adding an MCP Server

STDIO Server

# Add a local executable file
codebuddy mcp add --scope user my-tool -- /path/to/tool arg1 arg2

# Add a Python script
codebuddy mcp add --scope project python-tool -- python /path/to/script.py

SSE Server

# Add an SSE server
codebuddy mcp add --scope user --transport sse sse-server https://example.com/mcp/sse

HTTP Server

# Add an HTTP streaming server
codebuddy mcp add --scope project --transport http http-server https://example.com/mcp/http

Adding a Server with JSON Configuration

# Add a STDIO server
codebuddy mcp add-json --scope user my-server '{"type":"stdio","command":"/usr/local/bin/tool","args":["--verbose"]}'

# Add an HTTP server
codebuddy mcp add-json --scope user http-server '{"type":"http","url":"https://example.com/mcp","headers":{"Authorization":"Bearer token"}}'

# Add an SSE server
codebuddy mcp add-json --scope project sse-server '{"type":"sse","url":"https://api.example.com/mcp/sse","headers":{"X-API-Key":"your-api-key"}}'

# Add a STDIO server with environment variables
codebuddy mcp add-json --scope user python-tool '{"type":"stdio","command":"python","args":["-m","my_mcp_server"],"env":{"PYTHONPATH":"/path/to/tools"}}'

Managing MCP Servers

Listing All Servers

# List servers in all scopes
codebuddy mcp list

Viewing Server Details

# View information for a specific server
codebuddy mcp get my-server

Remove Server

# Remove a specific server
codebuddy mcp remove my-server

# Remove servers in a specific scope
codebuddy mcp remove my-server --scope user

Best Practices

1. Scope Selection

Use the user scope to store personal tools and global services.
Use the project scope to store project-specific tools.
Use the local scope to store temporary or experimental tools.

2. Security Considerations

Avoid storing sensitive information in configuration files.
Use environment variables to pass authentication information: Use the MCP environment variable extension feature (${API_TOKEN} or ${API_TOKEN:-default}) to manage sensitive data such as API keys and tokens.
Regularly review and update server configurations.
MCP servers in the project scope require user approval before they can be connected, ensuring security.
The OAuth authorization URL is verified for security before it is opened, and only the http/https protocols are supported.
Commit configuration files that contain environment variable references to the version control system, but exclude the actual environment variable files in .gitignore.

3. Performance Optimization

Configure a reasonable server timeout.
Avoid running too many STDIO servers at the same time.
Use a caching mechanism to reduce repeated connections.

4. Error Handling

Monitor server connection status.
Implement a reconnection mechanism.
Record and analyze error logs.

Troubleshooting

FAQs

Server Connection Failure

1. Check whether the command path is correct.
2. Verify parameters and environment variables.
3. Confirm the network connection (for remote servers).
4. View the server log output.

Tool Unavailable

1. Confirm that the server is connected successfully.
2. Check the tool permission settings.
3. Verify tool compatibility.

Configuration Not Taking Effect

1. Check the configuration file syntax.
2. Confirm the scope priority.
3. Restart the CodeBuddy application.

Sample Configuration

Python Tool Server

{
"mcpServers": {
"python-tools": {
"type": "stdio",
"command": "python",
"args": ["-m", "my_mcp_server"],
"env": {
"PYTHONPATH": "/path/to/tools"
},
"description": "A collection of Python tools"
}
}
}

Remote API Server

{
"mcpServers": {
"api-server": {
"type": "sse",
"url": "https://api.example.com/mcp/sse",
"headers": {
"Authorization": "Bearer your-token",
"X-API-Version": "v1"
},
"description": "Remote API service"
}
}
}

Node.js Local Server

{
"mcpServers": {
"node-server": {
"type": "stdio",
"command": "node",
"args": ["./mcp-server.js"],
"env": {
"NODE_ENV": "production"
},
"description": "Node.js MCP server"
}
}
}

Extension Development

Creating a Custom MCP Server

1. Select the implementation language: Python, Node.js, Go, and so on.
2. Implement the MCP protocol: Use the official SDK or implement it yourself.
3. Define the tool interface: Describe the tool features and parameters.
4. Handle requests: Receive and process requests from CodeBuddy.
5. Return the result: Return the execution result in MCP format.

SDKs and Libraries

Python: FastMCP
TypeScript/JavaScript: @modelcontextprotocol/sdk
Other languages: Refer to the official documentation for implementation.

Configuration Example

TAPD

codebuddy mcp add --scope user --transport http --header "X-Tapd-Access-Token: TAPD_ACCESS_TOKEN" -- tapd_mcp_http https://mcp-oa.tapd.woa.com/mcp

Chrome Devtools

codebuddy mcp add --scope user chrome-devtools -- npx -y chrome-devtools-mcp@latest

iWiki

codebuddy mcp add --scope user iwiki -- npx -y mcp-remote@latest https://prod.mcp.it.woa.com/app_iwiki_mcp/mcp3

Handling Oversized Responses

When the content returned by an MCP tool exceeds MAX_MCP_OUTPUT_TOKENS (default: 20000 tokens, approximately 80KB of characters), CodeBuddy automatically processes it to avoid consuming too much context:
Default behavior (write to disk): Save the complete response to ~/.codebuddy/projects/<project-hash>/<session-id>/tool-results/mcp-<server>-<tool>-<timestamp>-<rand>.txt in the current session, and return a read guide to the model (including the file path, format description, and segmented reading requirements). The model can read the complete content in segments by using the Read tool with the offset / limit parameters, or perform structured queries on the JSON structure by using jq.
Truncation fallback: In the following scenarios, content is directly truncated to the MAX_MCP_OUTPUT_TOKENS * 4 character limit without being written to disk:
The response includes image blocks (to avoid losing image rendering when base64 payloads are written to .txt files).
There is no session context currently, which prevents orphan files from being created.
Failed to write to disk (the directory is not writable, the disk is full, and so on).
Set the environment variable CODEBUDDY_DISABLE_MCP_LARGE_OUTPUT_FILES=1.
When truncation occurs, a [OUTPUT TRUNCATED - exceeded N token limit] marker is appended to the end of the content, and the model is informed of which types of blocks were dropped (for example, [Dropped 2 audio blocks due to size limit]), so that the model can retry with pagination or filtering parameters.

Related Links



Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback