mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-19 09:33:53 +00:00
docs: Add documentation for Sub Agents feature and update user guides
- Introduced a new documentation file for Sub Agents, detailing their purpose, benefits, configuration, and usage examples. - Updated the overview and quickstart guides to improve clarity and remove outdated information. - Created a comprehensive command reference document for Qwen Code, detailing slash commands, at commands, and exclamation commands for better user guidance. - Enhanced the formatting and organization of existing documentation for improved readability and usability.
This commit is contained in:
@@ -49,7 +49,6 @@ how is authentication handled?
|
|||||||
> - Ask about coding conventions and patterns used in the project
|
> - Ask about coding conventions and patterns used in the project
|
||||||
> - Request a glossary of project-specific terms
|
> - Request a glossary of project-specific terms
|
||||||
|
|
||||||
|
|
||||||
### Find relevant code
|
### Find relevant code
|
||||||
|
|
||||||
Suppose you need to locate code related to a specific feature or functionality.
|
Suppose you need to locate code related to a specific feature or functionality.
|
||||||
@@ -185,15 +184,15 @@ Then select "Create New subagent" and follow the prompts to define:
|
|||||||
|
|
||||||
> [!tip] Tips:
|
> [!tip] Tips:
|
||||||
>
|
>
|
||||||
> - Create project-specific subagents in `.qwen-code/agents/` for team sharing
|
> - Create project-specific subagents in `.qwen/agents/` for team sharing
|
||||||
> - Use descriptive `description` fields to enable automatic delegation
|
> - Use descriptive `description` fields to enable automatic delegation
|
||||||
> - Limit tool access to what each subagent actually needs
|
> - Limit tool access to what each subagent actually needs
|
||||||
> - Check the [subagents documentation](/sub-agents) for detailed examples
|
> - Know more [Sub Agents](/sub-agents)
|
||||||
|
|
||||||
|
|
||||||
## Use Plan Mode for safe code analysis
|
## Use Plan Mode for safe code analysis
|
||||||
|
|
||||||
Plan Mode instructs Claude to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely.
|
Plan Mode instructs Qwen Code to create a plan by analyzing the codebase with read-only operations, perfect for exploring codebases, planning complex changes, or reviewing code safely.
|
||||||
|
|
||||||
### When to use Plan Mode
|
### When to use Plan Mode
|
||||||
|
|
||||||
@@ -219,10 +218,10 @@ To start a new session in Plan Mode, use the `/approval-mode` then select `plan`
|
|||||||
|
|
||||||
**Run "headless" queries in Plan Mode**
|
**Run "headless" queries in Plan Mode**
|
||||||
|
|
||||||
You can also run a query in Plan Mode directly with `-p` (that is, in ["headless mode"](/en/headless)):
|
You can also run a query in Plan Mode directly with `-p` or `prompt`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
/approval-mode plan -p "Analyze the authentication system and suggest improvements"
|
qwen --prompt "What is machine learning?"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Example: Planning a complex refactor
|
### Example: Planning a complex refactor
|
||||||
@@ -245,7 +244,7 @@ How should we handle database migration?
|
|||||||
### Configure Plan Mode as default
|
### Configure Plan Mode as default
|
||||||
|
|
||||||
```json
|
```json
|
||||||
// .qwen-code/settings.json
|
// .qwen/settings.json
|
||||||
{
|
{
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"defaultMode": "plan"
|
"defaultMode": "plan"
|
||||||
@@ -253,8 +252,6 @@ How should we handle database migration?
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
See [settings documentation](/en/settings#available-settings) for more configuration options.
|
|
||||||
|
|
||||||
## Work with tests
|
## Work with tests
|
||||||
|
|
||||||
Suppose you need to add tests for uncovered code.
|
Suppose you need to add tests for uncovered code.
|
||||||
@@ -335,7 +332,7 @@ improve the generated documentation with more context and examples
|
|||||||
|
|
||||||
4. Verify documentation
|
4. Verify documentation
|
||||||
```
|
```
|
||||||
> check if the documentation follows our project standards
|
check if the documentation follows our project standards
|
||||||
```
|
```
|
||||||
|
|
||||||
> [!tip] Tips:
|
> [!tip] Tips:
|
||||||
@@ -354,9 +351,9 @@ You can use any of these methods:
|
|||||||
|
|
||||||
1) Drag and drop an image into the Qwen Code window
|
1) Drag and drop an image into the Qwen Code window
|
||||||
2) Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v)
|
2) Copy an image and paste it into the CLI with ctrl+v (Do not use cmd+v)
|
||||||
3) Provide an image path to Claude. E.g., "Analyze this image: /path/to/your/image. png"
|
3) Provide an image path to Qwen Code. E.g., "Analyze this image: /path/to/your/image. png"
|
||||||
|
|
||||||
3. Ask Claude to analyze the image
|
4. Ask Qwen Code to analyze the image
|
||||||
```
|
```
|
||||||
What does this image show?
|
What does this image show?
|
||||||
```
|
```
|
||||||
@@ -394,7 +391,6 @@ What HTML structure would recreate this component?
|
|||||||
> - You can work with multiple images in a conversation
|
> - You can work with multiple images in a conversation
|
||||||
> - Image analysis works with diagrams, screenshots, mockups, and more
|
> - Image analysis works with diagrams, screenshots, mockups, and more
|
||||||
|
|
||||||
|
|
||||||
## Reference files and directories
|
## Reference files and directories
|
||||||
|
|
||||||
Use `@` to quickly include files or directories without waiting for Qwen Code to read them.
|
Use `@` to quickly include files or directories without waiting for Qwen Code to read them.
|
||||||
@@ -418,7 +414,7 @@ This provides a directory listing with file information.
|
|||||||
Show me the data from @github: repos/owner/repo/issues
|
Show me the data from @github: repos/owner/repo/issues
|
||||||
```
|
```
|
||||||
|
|
||||||
This fetches data from connected MCP servers using the format @server: resource. See [MCP resources](/en/mcp#use-mcp-resources) for details.
|
This fetches data from connected MCP servers using the format @server: resource. See [MCP](/mcp) for details.
|
||||||
|
|
||||||
> [!tip] Tips:
|
> [!tip] Tips:
|
||||||
>
|
>
|
||||||
@@ -432,10 +428,6 @@ This fetches data from connected MCP servers using the format @server: resource.
|
|||||||
|
|
||||||
Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning.
|
Suppose you're working on complex architectural decisions, challenging bugs, or planning multi-step implementations that require deep reasoning.
|
||||||
|
|
||||||
> [!note]
|
|
||||||
>
|
|
||||||
> [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is disabled by default in Qwen Code. You can enable it on-demand by using `Tab` to toggle Thinking on, or by using prompts like "think" or "think hard". You can also enable it permanently by setting the [`MAX_THINKING_TOKENS` environment variable](/en/settings#environment-variables) in your settings.
|
|
||||||
|
|
||||||
1. Provide context and ask Qwen Code to think
|
1. Provide context and ask Qwen Code to think
|
||||||
```
|
```
|
||||||
I need to implement a new authentication system using OAuth 2 for our API. Think deeply about the best approach for implementing this in our codebase.
|
I need to implement a new authentication system using OAuth 2 for our API. Think deeply about the best approach for implementing this in our codebase.
|
||||||
@@ -444,6 +436,7 @@ I need to implement a new authentication system using OAuth 2 for our API. Think
|
|||||||
Qwen Code gathers relevant information from your codebase and uses extended thinking, which is visible in the interface.
|
Qwen Code gathers relevant information from your codebase and uses extended thinking, which is visible in the interface.
|
||||||
|
|
||||||
2. Refine the thinking with follow-up prompts
|
2. Refine the thinking with follow-up prompts
|
||||||
|
|
||||||
```
|
```
|
||||||
think about potential security vulnerabilities in this approach
|
think about potential security vulnerabilities in this approach
|
||||||
```
|
```
|
||||||
@@ -452,26 +445,6 @@ think about potential security vulnerabilities in this approach
|
|||||||
think hard about edge cases we should handle
|
think hard about edge cases we should handle
|
||||||
```
|
```
|
||||||
|
|
||||||
> [!tip]
|
|
||||||
> Tips to get the most value out of extended thinking:
|
|
||||||
>
|
|
||||||
> [Extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) is most valuable for complex tasks such as:
|
|
||||||
>
|
|
||||||
> - Planning complex architectural changes
|
|
||||||
> - Debugging intricate issues
|
|
||||||
> - Creating implementation plans for new features
|
|
||||||
> - Understanding complex codebases
|
|
||||||
> - Evaluating tradeoffs between different approaches
|
|
||||||
>
|
|
||||||
> Use `Tab` to toggle Thinking on and off during a session.
|
|
||||||
>
|
|
||||||
> The way you prompt for thinking results in varying levels of thinking depth:
|
|
||||||
>
|
|
||||||
> - "think" triggers basic extended thinking
|
|
||||||
> - intensifying phrases such as "keep hard", "think more", "think a lot", or "think longer" triggers deeper thinking
|
|
||||||
>
|
|
||||||
> For more extended thinking prompting tips, see [Extended thinking tips](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/extended-thinking-tips).
|
|
||||||
|
|
||||||
> [!note]
|
> [!note]
|
||||||
> Qwen Code displays its thinking process as italic gray text above the response.
|
> Qwen Code displays its thinking process as italic gray text above the response.
|
||||||
|
|
||||||
@@ -575,7 +548,7 @@ qwen
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
5. Run Claude in another worktree
|
5. Run Qwen Code in another worktree
|
||||||
```bash
|
```bash
|
||||||
cd ../project-bugfix
|
cd ../project-bugfix
|
||||||
qwen
|
qwen
|
||||||
@@ -594,7 +567,7 @@ git worktree remove ../project-feature-a
|
|||||||
> [!tip] Tips:
|
> [!tip] Tips:
|
||||||
>
|
>
|
||||||
> - Each worktree has its own independent file state, making it perfect for parallel Qwen Code sessions
|
> - Each worktree has its own independent file state, making it perfect for parallel Qwen Code sessions
|
||||||
> - Changes made in one worktree won't affect others, preventing Claude instances from interfering with each other
|
> - Changes made in one worktree won't affect others, preventing Qwen Code instances from interfering with each other
|
||||||
> - All worktrees share the same Git history and remote connections
|
> - All worktrees share the same Git history and remote connections
|
||||||
> - For long-running tasks, you can have Qwen Code working in one worktree while you continue development in another
|
> - For long-running tasks, you can have Qwen Code working in one worktree while you continue development in another
|
||||||
> - Use descriptive directory names to easily identify which task each worktree is for
|
> - Use descriptive directory names to easily identify which task each worktree is for
|
||||||
@@ -604,9 +577,9 @@ git worktree remove ../project-feature-a
|
|||||||
> - Other languages: Following your project's standard setup process
|
> - Other languages: Following your project's standard setup process
|
||||||
|
|
||||||
|
|
||||||
## Use Claude as a unix-style utility
|
## Use Qwen Code as a unix-style utility
|
||||||
|
|
||||||
### Add Claude to your verification process
|
### Add Qwen Code to your verification process
|
||||||
|
|
||||||
Suppose you want to use Qwen Code as a linter or code reviewer.
|
Suppose you want to use Qwen Code as a linter or code reviewer.
|
||||||
|
|
||||||
@@ -634,7 +607,7 @@ Suppose you want to use Qwen Code as a linter or code reviewer.
|
|||||||
|
|
||||||
Suppose you want to pipe data into Qwen Code, and get back data in a structured format.
|
Suppose you want to pipe data into Qwen Code, and get back data in a structured format.
|
||||||
|
|
||||||
**Pipe data through Claude:**
|
**Pipe data through Qwen Code:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cat build-error.txt | qwen-code -p 'concisely explain the root cause of this build error' > output.txt
|
cat build-error.txt | qwen-code -p 'concisely explain the root cause of this build error' > output.txt
|
||||||
@@ -676,102 +649,10 @@ This outputs a series of JSON objects in real-time as Qwen Code processes the re
|
|||||||
|
|
||||||
> [!tip] Tips:
|
> [!tip] Tips:
|
||||||
>
|
>
|
||||||
> - Use `--output-format text` for simple integrations where you just need Claude's response
|
> - Use `--output-format text` for simple integrations where you just need Qwen Code's response
|
||||||
> - Use `--output-format json` when you need the full conversation log
|
> - Use `--output-format json` when you need the full conversation log
|
||||||
> - Use `--output-format stream-json` for real-time output of each conversation turn
|
> - Use `--output-format stream-json` for real-time output of each conversation turn
|
||||||
|
|
||||||
## Create custom slash commands
|
|
||||||
|
|
||||||
Qwen Code supports custom slash commands that you can create to quickly execute specific prompts or tasks.
|
|
||||||
|
|
||||||
For more details, see the [Slash commands](/en/slash-commands) reference page.
|
|
||||||
|
|
||||||
### Create project-specific commands
|
|
||||||
|
|
||||||
Suppose you want to create reusable slash commands for your project that all team members can use.
|
|
||||||
|
|
||||||
1. Create a commands directory in your project
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mkdir -p .qwen-code/commands
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Create a Markdown file for each command
|
|
||||||
```bash
|
|
||||||
echo "Analyze the performance of this code and suggest three specific optimizations: " > .qwen-code/commands/optimize.md
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Use your custom command in Qwen Code
|
|
||||||
```
|
|
||||||
> /optimize
|
|
||||||
```
|
|
||||||
|
|
||||||
> [!tip] Tips:
|
|
||||||
>
|
|
||||||
> - Command names are derived from the filename (for example, `optimize.md` becomes `/optimize`)
|
|
||||||
> - You can organize commands in subdirectories (for example, `.qwen-code/commands/frontend/component.md` creates `/component` with " (project:frontend)" shown in the description)
|
|
||||||
> - Project commands are available to everyone who clones the repository
|
|
||||||
> - The Markdown file content becomes the prompt sent to Claude when the command is invoked
|
|
||||||
|
|
||||||
### Add command arguments with \$ARGUMENTS
|
|
||||||
|
|
||||||
Suppose you want to create flexible slash commands that can accept additional input from users.
|
|
||||||
|
|
||||||
1. Create a command file with the $ARGUMENTS placeholder
|
|
||||||
```bash
|
|
||||||
echo 'Find and fix issue #$ARGUMENTS. Follow these steps:
|
|
||||||
1.Understand the issue described in the ticket
|
|
||||||
2. Locate the relevant code in
|
|
||||||
our codebase
|
|
||||||
3. Implement a solution that addresses the root cause
|
|
||||||
4. Add
|
|
||||||
appropriate tests
|
|
||||||
5. Prepare a concise PR description' >
|
|
||||||
.qwen-code/commands/fix-issue.md
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Use the command with an issue number
|
|
||||||
In your Claude session, use the command with arguments.
|
|
||||||
|
|
||||||
```
|
|
||||||
> /fix-issue 123
|
|
||||||
```
|
|
||||||
|
|
||||||
This replaces \$ARGUMENTS with "123" in the prompt.
|
|
||||||
|
|
||||||
> [!tip] Tips:
|
|
||||||
>
|
|
||||||
> - The \$ARGUMENTS placeholder is replaced with any text that follows the command
|
|
||||||
> - You can position \$ARGUMENTS anywhere in your command template
|
|
||||||
> - Other useful applications: generating test cases for specific functions, creating documentation for components, reviewing code in particular files, or translating content to specified languages
|
|
||||||
|
|
||||||
### Create personal slash commands
|
|
||||||
|
|
||||||
Suppose you want to create personal slash commands that work across all your projects.
|
|
||||||
|
|
||||||
1. Create a commands directory in your home folder
|
|
||||||
```bash
|
|
||||||
mkdir -p ~/.qwen-code/commands
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Create a Markdown file for each command
|
|
||||||
```bash
|
|
||||||
echo "Review this code for security vulnerabilities, focusing on: " >
|
|
||||||
~/.qwen-code/commands/security-review.md
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Use your personal custom command
|
|
||||||
```
|
|
||||||
> /security-review
|
|
||||||
```
|
|
||||||
|
|
||||||
> [!tip] Tips:
|
|
||||||
>
|
|
||||||
> - Personal commands show " (user)" in their description when listed with `/help`
|
|
||||||
> - Personal commands are only available to you and not shared with your team
|
|
||||||
> - Personal commands work across all your projects
|
|
||||||
> - You can use these for consistent workflows across different codebases
|
|
||||||
|
|
||||||
## Ask Qwen Code about its capabilities
|
## Ask Qwen Code about its capabilities
|
||||||
|
|
||||||
Qwen Code has built-in access to its documentation and can answer questions about its own features and limitations.
|
Qwen Code has built-in access to its documentation and can answer questions about its own features and limitations.
|
||||||
@@ -802,6 +683,7 @@ how do I configure Qwen Code for Amazon Bedrock?
|
|||||||
what are the limitations of Qwen Code?
|
what are the limitations of Qwen Code?
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
> [!note]
|
> [!note]
|
||||||
>
|
>
|
||||||
> Qwen Code provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above.
|
> Qwen Code provides documentation-based answers to these questions. For executable examples and hands-on demonstrations, refer to the specific workflow sections above.
|
||||||
@@ -811,9 +693,3 @@ what are the limitations of Qwen Code?
|
|||||||
> - Qwen Code always has access to the latest Qwen Code documentation, regardless of the version you're using
|
> - Qwen Code always has access to the latest Qwen Code documentation, regardless of the version you're using
|
||||||
> - Ask specific questions to get detailed answers
|
> - Ask specific questions to get detailed answers
|
||||||
> - Qwen Code can explain complex features like MCP integration, enterprise configurations, and advanced workflows
|
> - Qwen Code can explain complex features like MCP integration, enterprise configurations, and advanced workflows
|
||||||
|
|
||||||
## Next steps
|
|
||||||
|
|
||||||
<Card title="Qwen Code reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer
|
|
||||||
Clone our development container reference implementation.
|
|
||||||
</Card>
|
|
||||||
|
|||||||
@@ -0,0 +1,586 @@
|
|||||||
|
# MCP servers with Qwen Code
|
||||||
|
|
||||||
|
This document provides a guide to configuring and using Model Context Protocol (MCP) servers with Qwen Code.
|
||||||
|
|
||||||
|
## What is an MCP server?
|
||||||
|
|
||||||
|
An MCP server is an application that exposes tools and resources to the CLI through the Model Context Protocol, allowing it to interact with external systems and data sources. MCP servers act as a bridge between the model and your local environment or other services like APIs.
|
||||||
|
|
||||||
|
An MCP server enables the CLI to:
|
||||||
|
|
||||||
|
- **Discover tools:** List available tools, their descriptions, and parameters through standardized schema definitions.
|
||||||
|
- **Execute tools:** Call specific tools with defined arguments and receive structured responses.
|
||||||
|
- **Access resources:** Read data from specific resources (though the CLI primarily focuses on tool execution).
|
||||||
|
|
||||||
|
With an MCP server, you can extend the CLI’s capabilities to perform actions beyond its built-in features, such as interacting with databases, APIs, custom scripts, or specialized workflows.
|
||||||
|
|
||||||
|
## Core Integration Architecture
|
||||||
|
Qwen Code integrates with MCP servers through a sophisticated discovery and execution system built into the core package (`packages/core/src/tools/`):
|
||||||
|
|
||||||
|
### Discovery Layer (`mcp-client.ts`)
|
||||||
|
|
||||||
|
The discovery process is orchestrated by `discoverMcpTools()`, which:
|
||||||
|
|
||||||
|
1. **Iterates through configured servers** from your `settings.json` `mcpServers` configuration
|
||||||
|
2. **Establishes connections** using appropriate transport mechanisms (Stdio, SSE, or Streamable HTTP)
|
||||||
|
3. **Fetches tool definitions** from each server using the MCP protocol
|
||||||
|
4. **Sanitizes and validates** tool schemas for compatibility with the Qwen API
|
||||||
|
5. **Registers tools** in the global tool registry with conflict resolution
|
||||||
|
|
||||||
|
### Execution Layer (`mcp-tool.ts`)
|
||||||
|
|
||||||
|
Each discovered MCP tool is wrapped in a `DiscoveredMCPTool` instance that:
|
||||||
|
|
||||||
|
- **Handles confirmation logic** based on server trust settings and user preferences
|
||||||
|
- **Manages tool execution** by calling the MCP server with proper parameters
|
||||||
|
- **Processes responses** for both the LLM context and user display
|
||||||
|
- **Maintains connection state** and handles timeouts
|
||||||
|
|
||||||
|
### Transport Mechanisms
|
||||||
|
The CLI supports three MCP transport types:
|
||||||
|
|
||||||
|
- **Stdio Transport:** Spawns a subprocess and communicates via stdin/stdout
|
||||||
|
- **SSE Transport:** Connects to Server-Sent Events endpoints
|
||||||
|
- **Streamable HTTP Transport:** Uses HTTP streaming for communication
|
||||||
|
|
||||||
|
## How to set up your MCP server
|
||||||
|
|
||||||
|
Qwen Code uses the `mcpServers` configuration in your `settings.json` file to locate and connect to MCP servers. This configuration supports multiple servers with different transport mechanisms.
|
||||||
|
|
||||||
|
### Configure the MCP server in settings.json
|
||||||
|
|
||||||
|
You can configure MCP servers in your `settings.json` file in two main ways: through the top-level `mcpServers`object for specific server definitions, and through the `mcp` object for global settings that control server discovery and execution.
|
||||||
|
|
||||||
|
#### Global MCP Settings (`mcp`)
|
||||||
|
The `mcp` object in your `settings.json` allows you to define global rules for all MCP servers.
|
||||||
|
|
||||||
|
- **`mcp.serverCommand`** (string): A global command to start an MCP server.
|
||||||
|
- **`mcp.allowed`** (array of strings): A list of MCP server names to allow. If this is set, only servers from this list (matching the keys in the `mcpServers` object) will be connected to.
|
||||||
|
- **`mcp.excluded`** (array of strings): A list of MCP server names to exclude. Servers in this list will not be connected to.
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
|
||||||
|
`{ "mcp": { "allowed": ["my-trusted-server"], "excluded": ["experimental-server"] }}`
|
||||||
|
|
||||||
|
#### Server-Specific Configuration (`mcpServers`)
|
||||||
|
The `mcpServers` object is where you define each individual MCP server you want the CLI to connect to.
|
||||||
|
|
||||||
|
### Configuration Structure
|
||||||
|
Add an `mcpServers` object to your `settings.json` file:
|
||||||
|
|
||||||
|
`{ ...file contains other config objects "mcpServers": { "serverName": { "command": "path/to/server", "args": ["--arg1", "value1"], "env": { "API_KEY": "$MY_API_TOKEN" }, "cwd": "./server-directory", "timeout": 30000, "trust": false } }}`
|
||||||
|
|
||||||
|
### Configuration Properties
|
||||||
|
|
||||||
|
Each server configuration supports the following properties:
|
||||||
|
|
||||||
|
#### Required (one of the following)
|
||||||
|
|
||||||
|
- **`command`** (string): Path to the executable for Stdio transport
|
||||||
|
- **`url`** (string): SSE endpoint URL (e.g., `"http://localhost:8080/sse"`)
|
||||||
|
- **`httpUrl`** (string): HTTP streaming endpoint URL
|
||||||
|
|
||||||
|
#### Optional
|
||||||
|
|
||||||
|
- **`args`** (string[]): Command-line arguments for Stdio transport
|
||||||
|
- **`headers`** (object): Custom HTTP headers when using `url` or `httpUrl`
|
||||||
|
- **`env`** (object): Environment variables for the server process. Values can reference environment variables using `$VAR_NAME` or `${VAR_NAME}` syntax
|
||||||
|
- **`cwd`** (string): Working directory for Stdio transport
|
||||||
|
- **`timeout`** (number): Request timeout in milliseconds (default: 600,000ms = 10 minutes)
|
||||||
|
- **`trust`** (boolean): When `true`, bypasses all tool call confirmations for this server (default: `false`)
|
||||||
|
- **`includeTools`** (string[]): List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (allowlist behavior). If not specified, all tools from the server are enabled by default.
|
||||||
|
- **`excludeTools`** (string[]): List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. **Note:** `excludeTools` takes precedence over `includeTools` - if a tool is in both lists, it will be excluded.
|
||||||
|
- **`targetAudience`** (string): The OAuth Client ID allowlisted on the IAP-protected application you are trying to access. Used with `authProviderType: 'service_account_impersonation'`.
|
||||||
|
- **`targetServiceAccount`** (string): The email address of the Google Cloud Service Account to impersonate. Used with `authProviderType: 'service_account_impersonation'`.
|
||||||
|
|
||||||
|
### OAuth Support for Remote MCP Servers
|
||||||
|
|
||||||
|
Qwen Code supports OAuth 2.0 authentication for remote MCP servers using SSE or HTTP transports. This enables secure access to MCP servers that require authentication.
|
||||||
|
|
||||||
|
#### Automatic OAuth Discovery
|
||||||
|
|
||||||
|
For servers that support OAuth discovery, you can omit the OAuth configuration and let the CLI discover it automatically:
|
||||||
|
|
||||||
|
`{ "mcpServers": { "discoveredServer": { "url": "https://api.example.com/sse" } }}`
|
||||||
|
|
||||||
|
The CLI will automatically:
|
||||||
|
|
||||||
|
- Detect when a server requires OAuth authentication (401 responses)
|
||||||
|
- Discover OAuth endpoints from server metadata
|
||||||
|
- Perform dynamic client registration if supported
|
||||||
|
- Handle the OAuth flow and token management
|
||||||
|
|
||||||
|
#### Authentication Flow
|
||||||
|
|
||||||
|
When connecting to an OAuth-enabled server:
|
||||||
|
|
||||||
|
1. **Initial connection attempt** fails with 401 Unauthorized
|
||||||
|
2. **OAuth discovery** finds authorization and token endpoints
|
||||||
|
3. **Browser opens** for user authentication (requires local browser access)
|
||||||
|
4. **Authorization code** is exchanged for access tokens
|
||||||
|
5. **Tokens are stored** securely for future use
|
||||||
|
6. **Connection retry** succeeds with valid tokens
|
||||||
|
|
||||||
|
#### Browser Redirect Requirements
|
||||||
|
|
||||||
|
**Important:** OAuth authentication requires that your local machine can:
|
||||||
|
|
||||||
|
- Open a web browser for authentication
|
||||||
|
- Receive redirects on `http://localhost:7777/oauth/callback`
|
||||||
|
|
||||||
|
This feature will not work in:
|
||||||
|
|
||||||
|
- Headless environments without browser access
|
||||||
|
- Remote SSH sessions without X11 forwarding
|
||||||
|
- Containerized environments without browser support
|
||||||
|
|
||||||
|
#### Managing OAuth Authentication
|
||||||
|
|
||||||
|
Use the `/mcp auth` command to manage OAuth authentication:
|
||||||
|
|
||||||
|
`# List servers requiring authentication/mcp auth # Authenticate with a specific server/mcp auth serverName # Re-authenticate if tokens expire/mcp auth serverName`
|
||||||
|
|
||||||
|
#### OAuth Configuration Properties
|
||||||
|
|
||||||
|
- **`enabled`** (boolean): Enable OAuth for this server
|
||||||
|
- **`clientId`** (string): OAuth client identifier (optional with dynamic registration)
|
||||||
|
- **`clientSecret`** (string): OAuth client secret (optional for public clients)
|
||||||
|
- **`authorizationUrl`** (string): OAuth authorization endpoint (auto-discovered if omitted)
|
||||||
|
- **`tokenUrl`** (string): OAuth token endpoint (auto-discovered if omitted)
|
||||||
|
- **`scopes`** (string[]): Required OAuth scopes
|
||||||
|
- **`redirectUri`** (string): Custom redirect URI (defaults to `http://localhost:7777/oauth/callback`)
|
||||||
|
- **`tokenParamName`** (string): Query parameter name for tokens in SSE URLs
|
||||||
|
- **`audiences`** (string[]): Audiences the token is valid for
|
||||||
|
|
||||||
|
#### Token Management
|
||||||
|
|
||||||
|
OAuth tokens are automatically:
|
||||||
|
|
||||||
|
- **Stored securely** in `~/.qwen/mcp-oauth-tokens.json`
|
||||||
|
- **Refreshed** when expired (if refresh tokens are available)
|
||||||
|
- **Validated** before each connection attempt
|
||||||
|
- **Cleaned up** when invalid or expired
|
||||||
|
|
||||||
|
#### Authentication Provider Type
|
||||||
|
|
||||||
|
You can specify the authentication provider type using the `authProviderType` property:
|
||||||
|
|
||||||
|
- **`authProviderType`** (string): Specifies the authentication provider. Can be one of the following:
|
||||||
|
- **`dynamic_discovery`** (default): The CLI will automatically discover the OAuth configuration from the server.
|
||||||
|
- **`google_credentials`**: The CLI will use the Google Application Default Credentials (ADC) to authenticate with the server. When using this provider, you must specify the required scopes.
|
||||||
|
- **`service_account_impersonation`**: The CLI will impersonate a Google Cloud Service Account to authenticate with the server. This is useful for accessing IAP-protected services (this was specifically designed for Cloud Run services).
|
||||||
|
|
||||||
|
#### Google Credentials
|
||||||
|
|
||||||
|
`{ "mcpServers": { "googleCloudServer": { "httpUrl": "https://my-gcp-service.run.app/mcp", "authProviderType": "google_credentials", "oauth": { "scopes": ["https://www.googleapis.com/auth/userinfo.email"] } } }}`
|
||||||
|
|
||||||
|
#### Service Account Impersonation
|
||||||
|
|
||||||
|
To authenticate with a server using Service Account Impersonation, you must set the `authProviderType` to `service_account_impersonation` and provide the following properties:
|
||||||
|
|
||||||
|
- **`targetAudience`** (string): The OAuth Client ID allowslisted on the IAP-protected application you are trying to access.
|
||||||
|
- **`targetServiceAccount`** (string): The email address of the Google Cloud Service Account to impersonate.
|
||||||
|
|
||||||
|
The CLI will use your local Application Default Credentials (ADC) to generate an OIDC ID token for the specified service account and audience. This token will then be used to authenticate with the MCP server.
|
||||||
|
|
||||||
|
#### Setup Instructions
|
||||||
|
|
||||||
|
1. **[Create](https://cloud.google.com/iap/docs/oauth-client-creation) or use an existing OAuth 2.0 client ID.** To use an existing OAuth 2.0 client ID, follow the steps in [How to share OAuth Clients](https://cloud.google.com/iap/docs/sharing-oauth-clients) .
|
||||||
|
2. **Add the OAuth ID to the allowlist for [programmatic access](https://cloud.google.com/iap/docs/sharing-oauth-clients#programmatic_access) for the application.** Since Cloud Run is not yet a supported resource type in gcloud iap, you must allowlist the Client ID on the project.
|
||||||
|
3. **Create a service account.** [Documentation](https://cloud.google.com/iam/docs/service-accounts-create#creating) , [Cloud Console Link](https://console.cloud.google.com/iam-admin/serviceaccounts)
|
||||||
|
4. **Add both the service account and users to the IAP Policy** in the “Security” tab of the Cloud Run service itself or via gcloud.
|
||||||
|
5. **Grant all users and groups** who will access the MCP Server the necessary permissions to [impersonate the service account](https://cloud.google.com/docs/authentication/use-service-account-impersonation) (i.e., `roles/iam.serviceAccountTokenCreator`).
|
||||||
|
6. **[Enable](https://console.cloud.google.com/apis/library/iamcredentials.googleapis.com) the IAM Credentials API** for your project.
|
||||||
|
|
||||||
|
### Example Configurations
|
||||||
|
|
||||||
|
#### Python MCP Server (Stdio)
|
||||||
|
|
||||||
|
`{ "mcpServers": { "pythonTools": { "command": "python", "args": ["-m", "my_mcp_server", "--port", "8080"], "cwd": "./mcp-servers/python", "env": { "DATABASE_URL": "$DB_CONNECTION_STRING", "API_KEY": "${EXTERNAL_API_KEY}" }, "timeout": 15000 } }}`
|
||||||
|
|
||||||
|
#### Node.js MCP Server (Stdio)
|
||||||
|
|
||||||
|
`{ "mcpServers": { "nodeServer": { "command": "node", "args": ["dist/server.js", "--verbose"], "cwd": "./mcp-servers/node", "trust": true } }}`
|
||||||
|
|
||||||
|
#### Docker-based MCP Server
|
||||||
|
|
||||||
|
`{ "mcpServers": { "dockerizedServer": { "command": "docker", "args": [ "run", "-i", "--rm", "-e", "API_KEY", "-v", "${PWD}:/workspace", "my-mcp-server:latest" ], "env": { "API_KEY": "$EXTERNAL_SERVICE_TOKEN" } } }}`
|
||||||
|
|
||||||
|
#### HTTP-based MCP Server
|
||||||
|
|
||||||
|
`{ "mcpServers": { "httpServer": { "httpUrl": "http://localhost:3000/mcp", "timeout": 5000 } }}`
|
||||||
|
|
||||||
|
#### HTTP-based MCP Server with Custom Headers
|
||||||
|
|
||||||
|
`{ "mcpServers": { "httpServerWithAuth": { "httpUrl": "http://localhost:3000/mcp", "headers": { "Authorization": "Bearer your-api-token", "X-Custom-Header": "custom-value", "Content-Type": "application/json" }, "timeout": 5000 } }}`
|
||||||
|
|
||||||
|
#### MCP Server with Tool Filtering
|
||||||
|
|
||||||
|
`{ "mcpServers": { "filteredServer": { "command": "python", "args": ["-m", "my_mcp_server"], "includeTools": ["safe_tool", "file_reader", "data_processor"], // "excludeTools": ["dangerous_tool", "file_deleter"], "timeout": 30000 } }}`
|
||||||
|
|
||||||
|
### SSE MCP Server with SA Impersonation
|
||||||
|
|
||||||
|
`{ "mcpServers": { "myIapProtectedServer": { "url": "https://my-iap-service.run.app/sse", "authProviderType": "service_account_impersonation", "targetAudience": "YOUR_IAP_CLIENT_ID.apps.googleusercontent.com", "targetServiceAccount": "your-sa@your-project.iam.gserviceaccount.com" } }}`
|
||||||
|
|
||||||
|
## Discovery Process Deep Dive
|
||||||
|
|
||||||
|
When Qwen Code starts, it performs MCP server discovery through the following detailed process:
|
||||||
|
|
||||||
|
### 1. Server Iteration and Connection
|
||||||
|
|
||||||
|
For each configured server in `mcpServers`:
|
||||||
|
|
||||||
|
1. **Status tracking begins:** Server status is set to `CONNECTING`
|
||||||
|
2. **Transport selection:** Based on configuration properties:
|
||||||
|
- `httpUrl` → `StreamableHTTPClientTransport`
|
||||||
|
- `url` → `SSEClientTransport`
|
||||||
|
- `command` → `StdioClientTransport`
|
||||||
|
3. **Connection establishment:** The MCP client attempts to connect with the configured timeout
|
||||||
|
4. **Error handling:** Connection failures are logged and the server status is set to `DISCONNECTED`
|
||||||
|
|
||||||
|
### 2. Tool Discovery
|
||||||
|
|
||||||
|
Upon successful connection:
|
||||||
|
|
||||||
|
1. **Tool listing:** The client calls the MCP server’s tool listing endpoint
|
||||||
|
2. **Schema validation:** Each tool’s function declaration is validated
|
||||||
|
3. **Tool filtering:** Tools are filtered based on `includeTools` and `excludeTools` configuration
|
||||||
|
4. **Name sanitization:** Tool names are cleaned to meet Qwen API requirements:
|
||||||
|
- Invalid characters (non-alphanumeric, underscore, dot, hyphen) are replaced with underscores
|
||||||
|
- Names longer than 63 characters are truncated with middle replacement (`___`)
|
||||||
|
|
||||||
|
### 3. Conflict Resolution
|
||||||
|
|
||||||
|
When multiple servers expose tools with the same name:
|
||||||
|
|
||||||
|
1. **First registration wins:** The first server to register a tool name gets the unprefixed name
|
||||||
|
2. **Automatic prefixing:** Subsequent servers get prefixed names: `serverName__toolName`
|
||||||
|
3. **Registry tracking:** The tool registry maintains mappings between server names and their tools
|
||||||
|
|
||||||
|
### 4. Schema Processing
|
||||||
|
|
||||||
|
Tool parameter schemas undergo sanitization for API compatibility:
|
||||||
|
|
||||||
|
- **`$schema` properties** are removed
|
||||||
|
- **`additionalProperties`** are stripped
|
||||||
|
- **`anyOf` with `default`** have their default values removed (Vertex AI compatibility)
|
||||||
|
- **Recursive processing** applies to nested schemas
|
||||||
|
|
||||||
|
### 5. Connection Management
|
||||||
|
|
||||||
|
After discovery:
|
||||||
|
|
||||||
|
- **Persistent connections:** Servers that successfully register tools maintain their connections
|
||||||
|
- **Cleanup:** Servers that provide no usable tools have their connections closed
|
||||||
|
- **Status updates:** Final server statuses are set to `CONNECTED` or `DISCONNECTED`
|
||||||
|
|
||||||
|
## Tool Execution Flow
|
||||||
|
|
||||||
|
When the model decides to use an MCP tool, the following execution flow occurs:
|
||||||
|
|
||||||
|
### 1. Tool Invocation
|
||||||
|
|
||||||
|
The model generates a `FunctionCall` with:
|
||||||
|
|
||||||
|
- **Tool name:** The registered name (potentially prefixed)
|
||||||
|
- **Arguments:** JSON object matching the tool’s parameter schema
|
||||||
|
|
||||||
|
### 2. Confirmation Process
|
||||||
|
|
||||||
|
Each `DiscoveredMCPTool` implements sophisticated confirmation logic:
|
||||||
|
|
||||||
|
#### Trust-based Bypass
|
||||||
|
|
||||||
|
`if (this.trust) { return false; // No confirmation needed}`
|
||||||
|
|
||||||
|
#### Dynamic Allow-listing
|
||||||
|
|
||||||
|
The system maintains internal allow-lists for:
|
||||||
|
|
||||||
|
- **Server-level:** `serverName` → All tools from this server are trusted
|
||||||
|
- **Tool-level:** `serverName.toolName` → This specific tool is trusted
|
||||||
|
|
||||||
|
#### User Choice Handling
|
||||||
|
|
||||||
|
When confirmation is required, users can choose:
|
||||||
|
|
||||||
|
- **Proceed once:** Execute this time only
|
||||||
|
- **Always allow this tool:** Add to tool-level allow-list
|
||||||
|
- **Always allow this server:** Add to server-level allow-list
|
||||||
|
- **Cancel:** Abort execution
|
||||||
|
|
||||||
|
### 3. Execution
|
||||||
|
|
||||||
|
Upon confirmation (or trust bypass):
|
||||||
|
|
||||||
|
1. **Parameter preparation:** Arguments are validated against the tool’s schema
|
||||||
|
|
||||||
|
2. **MCP call:** The underlying `CallableTool` invokes the server with:
|
||||||
|
|
||||||
|
`const functionCalls = [ { name: this.serverToolName, // Original server tool name args: params, },];`
|
||||||
|
|
||||||
|
3. **Response processing:** Results are formatted for both LLM context and user display
|
||||||
|
|
||||||
|
|
||||||
|
### 4. Response Handling
|
||||||
|
|
||||||
|
The execution result contains:
|
||||||
|
|
||||||
|
- **`llmContent`:** Raw response parts for the language model’s context
|
||||||
|
- **`returnDisplay`:** Formatted output for user display (often JSON in markdown code blocks)
|
||||||
|
|
||||||
|
## How to interact with your MCP server
|
||||||
|
|
||||||
|
### Using the `/mcp` Command
|
||||||
|
|
||||||
|
The `/mcp` command provides comprehensive information about your MCP server setup:
|
||||||
|
|
||||||
|
`/mcp`
|
||||||
|
|
||||||
|
This displays:
|
||||||
|
|
||||||
|
- **Server list:** All configured MCP servers
|
||||||
|
- **Connection status:** `CONNECTED`, `CONNECTING`, or `DISCONNECTED`
|
||||||
|
- **Server details:** Configuration summary (excluding sensitive data)
|
||||||
|
- **Available tools:** List of tools from each server with descriptions
|
||||||
|
- **Discovery state:** Overall discovery process status
|
||||||
|
|
||||||
|
### Example `/mcp` Output
|
||||||
|
|
||||||
|
`MCP Servers Status:📡 pythonTools (CONNECTED) Command: python -m my_mcp_server --port 8080 Working Directory: ./mcp-servers/python Timeout: 15000ms Tools: calculate_sum, file_analyzer, data_processor🔌 nodeServer (DISCONNECTED) Command: node dist/server.js --verbose Error: Connection refused🐳 dockerizedServer (CONNECTED) Command: docker run -i --rm -e API_KEY my-mcp-server:latest Tools: docker__deploy, docker__statusDiscovery State: COMPLETED`
|
||||||
|
|
||||||
|
### Tool Usage
|
||||||
|
|
||||||
|
Once discovered, MCP tools are available to the Qwen model like built-in tools. The model will automatically:
|
||||||
|
|
||||||
|
1. **Select appropriate tools** based on your requests
|
||||||
|
2. **Present confirmation dialogs** (unless the server is trusted)
|
||||||
|
3. **Execute tools** with proper parameters
|
||||||
|
4. **Display results** in a user-friendly format
|
||||||
|
|
||||||
|
## Status Monitoring and Troubleshooting
|
||||||
|
|
||||||
|
### Connection States
|
||||||
|
|
||||||
|
The MCP integration tracks several states:
|
||||||
|
|
||||||
|
#### Server Status (`MCPServerStatus`)
|
||||||
|
|
||||||
|
- **`DISCONNECTED`:** Server is not connected or has errors
|
||||||
|
- **`CONNECTING`:** Connection attempt in progress
|
||||||
|
- **`CONNECTED`:** Server is connected and ready
|
||||||
|
|
||||||
|
#### Discovery State (`MCPDiscoveryState`)
|
||||||
|
|
||||||
|
- **`NOT_STARTED`:** Discovery hasn’t begun
|
||||||
|
- **`IN_PROGRESS`:** Currently discovering servers
|
||||||
|
- **`COMPLETED`:** Discovery finished (with or without errors)
|
||||||
|
|
||||||
|
### Common Issues and Solutions
|
||||||
|
|
||||||
|
#### Server Won’t Connect
|
||||||
|
|
||||||
|
**Symptoms:** Server shows `DISCONNECTED` status
|
||||||
|
|
||||||
|
**Troubleshooting:**
|
||||||
|
|
||||||
|
1. **Check configuration:** Verify `command`, `args`, and `cwd` are correct
|
||||||
|
2. **Test manually:** Run the server command directly to ensure it works
|
||||||
|
3. **Check dependencies:** Ensure all required packages are installed
|
||||||
|
4. **Review logs:** Look for error messages in the CLI output
|
||||||
|
5. **Verify permissions:** Ensure the CLI can execute the server command
|
||||||
|
|
||||||
|
#### No Tools Discovered
|
||||||
|
|
||||||
|
**Symptoms:** Server connects but no tools are available
|
||||||
|
|
||||||
|
**Troubleshooting:**
|
||||||
|
|
||||||
|
1. **Verify tool registration:** Ensure your server actually registers tools
|
||||||
|
2. **Check MCP protocol:** Confirm your server implements the MCP tool listing correctly
|
||||||
|
3. **Review server logs:** Check stderr output for server-side errors
|
||||||
|
4. **Test tool listing:** Manually test your server’s tool discovery endpoint
|
||||||
|
|
||||||
|
#### Tools Not Executing
|
||||||
|
|
||||||
|
**Symptoms:** Tools are discovered but fail during execution
|
||||||
|
|
||||||
|
**Troubleshooting:**
|
||||||
|
|
||||||
|
1. **Parameter validation:** Ensure your tool accepts the expected parameters
|
||||||
|
2. **Schema compatibility:** Verify your input schemas are valid JSON Schema
|
||||||
|
3. **Error handling:** Check if your tool is throwing unhandled exceptions
|
||||||
|
4. **Timeout issues:** Consider increasing the `timeout` setting
|
||||||
|
|
||||||
|
#### Sandbox Compatibility
|
||||||
|
|
||||||
|
**Symptoms:** MCP servers fail when sandboxing is enabled
|
||||||
|
|
||||||
|
**Solutions:**
|
||||||
|
|
||||||
|
1. **Docker-based servers:** Use Docker containers that include all dependencies
|
||||||
|
2. **Path accessibility:** Ensure server executables are available in the sandbox
|
||||||
|
3. **Network access:** Configure sandbox to allow necessary network connections
|
||||||
|
4. **Environment variables:** Verify required environment variables are passed through
|
||||||
|
|
||||||
|
### Debugging Tips
|
||||||
|
|
||||||
|
1. **Enable debug mode:** Run the CLI with `--debug` for verbose output
|
||||||
|
2. **Check stderr:** MCP server stderr is captured and logged (INFO messages filtered)
|
||||||
|
3. **Test isolation:** Test your MCP server independently before integrating
|
||||||
|
4. **Incremental setup:** Start with simple tools before adding complex functionality
|
||||||
|
5. **Use `/mcp` frequently:** Monitor server status during development
|
||||||
|
|
||||||
|
## Important Notes
|
||||||
|
|
||||||
|
### Security Considerations
|
||||||
|
|
||||||
|
- **Trust settings:** The `trust` option bypasses all confirmation dialogs. Use cautiously and only for servers you completely control
|
||||||
|
- **Access tokens:** Be security-aware when configuring environment variables containing API keys or tokens
|
||||||
|
- **Sandbox compatibility:** When using sandboxing, ensure MCP servers are available within the sandbox environment
|
||||||
|
- **Private data:** Using broadly scoped personal access tokens can lead to information leakage between repositories
|
||||||
|
|
||||||
|
### Performance and Resource Management
|
||||||
|
|
||||||
|
- **Connection persistence:** The CLI maintains persistent connections to servers that successfully register tools
|
||||||
|
- **Automatic cleanup:** Connections to servers providing no tools are automatically closed
|
||||||
|
- **Timeout management:** Configure appropriate timeouts based on your server’s response characteristics
|
||||||
|
- **Resource monitoring:** MCP servers run as separate processes and consume system resources
|
||||||
|
|
||||||
|
### Schema Compatibility
|
||||||
|
|
||||||
|
- **Property stripping:** The system automatically removes certain schema properties (`$schema`, `additionalProperties`) for Qwen API compatibility
|
||||||
|
- **Name sanitization:** Tool names are automatically sanitized to meet API requirements
|
||||||
|
- **Conflict resolution:** Tool name conflicts between servers are resolved through automatic prefixing
|
||||||
|
|
||||||
|
This comprehensive integration makes MCP servers a powerful way to extend the CLI’s capabilities while maintaining security, reliability, and ease of use.
|
||||||
|
|
||||||
|
## Returning Rich Content from Tools
|
||||||
|
|
||||||
|
MCP tools are not limited to returning simple text. You can return rich, multi-part content, including text, images, audio, and other binary data in a single tool response. This allows you to build powerful tools that can provide diverse information to the model in a single turn.
|
||||||
|
|
||||||
|
All data returned from the tool is processed and sent to the model as context for its next generation, enabling it to reason about or summarize the provided information.
|
||||||
|
|
||||||
|
### How It Works
|
||||||
|
|
||||||
|
To return rich content, your tool’s response must adhere to the MCP specification for a [`CallToolResult`](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result). The `content` field of the result should be an array of `ContentBlock` objects. The CLI will correctly process this array, separating text from binary data and packaging it for the model.
|
||||||
|
|
||||||
|
You can mix and match different content block types in the `content` array. The supported block types include:
|
||||||
|
|
||||||
|
- `text`
|
||||||
|
- `image`
|
||||||
|
- `audio`
|
||||||
|
- `resource` (embedded content)
|
||||||
|
- `resource_link`
|
||||||
|
|
||||||
|
### Example: Returning Text and an Image
|
||||||
|
|
||||||
|
Here is an example of a valid JSON response from an MCP tool that returns both a text description and an image:
|
||||||
|
|
||||||
|
`{ "content": [ { "type": "text", "text": "Here is the logo you requested." }, { "type": "image", "data": "BASE64_ENCODED_IMAGE_DATA_HERE", "mimeType": "image/png" }, { "type": "text", "text": "The logo was created in 2025." } ]}`
|
||||||
|
|
||||||
|
When Qwen Code receives this response, it will:
|
||||||
|
|
||||||
|
1. Extract all the text and combine it into a single `functionResponse` part for the model.
|
||||||
|
2. Present the image data as a separate `inlineData` part.
|
||||||
|
3. Provide a clean, user-friendly summary in the CLI, indicating that both text and an image were received.
|
||||||
|
|
||||||
|
This enables you to build sophisticated tools that can provide rich, multi-modal context to the Qwen model.
|
||||||
|
|
||||||
|
## MCP Prompts as Slash Commands
|
||||||
|
|
||||||
|
In addition to tools, MCP servers can expose predefined prompts that can be executed as slash commands within Qwen Code. This allows you to create shortcuts for common or complex queries that can be easily invoked by name.
|
||||||
|
|
||||||
|
### Defining Prompts on the Server
|
||||||
|
|
||||||
|
Here’s a small example of a stdio MCP server that defines prompts:
|
||||||
|
|
||||||
|
``import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import { z } from 'zod'; const server = new McpServer({ name: 'prompt-server', version: '1.0.0',}); server.registerPrompt( 'poem-writer', { title: 'Poem Writer', description: 'Write a nice haiku', argsSchema: { title: z.string(), mood: z.string().optional() }, }, ({ title, mood }) => ({ messages: [ { role: 'user', content: { type: 'text', text: `Write a haiku${mood ? ` with the mood ${mood}` : ''} called ${title}. Note that a haiku is 5 syllables followed by 7 syllables followed by 5 syllables `, }, }, ], }),); const transport = new StdioServerTransport();await server.connect(transport);``
|
||||||
|
|
||||||
|
This can be included in `settings.json` under `mcpServers` with:
|
||||||
|
|
||||||
|
`{ "mcpServers": { "nodeServer": { "command": "node", "args": ["filename.ts"] } }}`
|
||||||
|
|
||||||
|
### Invoking Prompts
|
||||||
|
|
||||||
|
Once a prompt is discovered, you can invoke it using its name as a slash command. The CLI will automatically handle parsing arguments.
|
||||||
|
|
||||||
|
`/poem-writer --title="Qwen Code" --mood="reverent"`
|
||||||
|
|
||||||
|
or, using positional arguments:
|
||||||
|
|
||||||
|
`/poem-writer "Qwen Code" reverent`
|
||||||
|
|
||||||
|
When you run this command, the CLI executes the `prompts/get` method on the MCP server with the provided arguments. The server is responsible for substituting the arguments into the prompt template and returning the final prompt text. The CLI then sends this prompt to the model for execution. This provides a convenient way to automate and share common workflows.
|
||||||
|
|
||||||
|
## Managing MCP Servers with `qwen mcp`
|
||||||
|
|
||||||
|
While you can always configure MCP servers by manually editing your `settings.json` file, the CLI provides a convenient set of commands to manage your server configurations programmatically. These commands streamline the process of adding, listing, and removing MCP servers without needing to directly edit JSON files.
|
||||||
|
|
||||||
|
### Adding a Server (`qwen mcp add`)
|
||||||
|
|
||||||
|
The `add` command configures a new MCP server in your `settings.json`. Based on the scope (`-s, --scope`), it will be added to either the user config `~/.qwen/settings.json` or the project config `.qwen/settings.json`file.
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
|
||||||
|
`qwen mcp add [options] <name> <commandOrUrl> [args...]`
|
||||||
|
|
||||||
|
- `<name>`: A unique name for the server.
|
||||||
|
- `<commandOrUrl>`: The command to execute (for `stdio`) or the URL (for `http`/`sse`).
|
||||||
|
- `[args...]`: Optional arguments for a `stdio` command.
|
||||||
|
|
||||||
|
**Options (Flags):**
|
||||||
|
|
||||||
|
- `-s, --scope`: Configuration scope (user or project). [default: “project”]
|
||||||
|
- `-t, --transport`: Transport type (stdio, sse, http). [default: “stdio”]
|
||||||
|
- `-e, --env`: Set environment variables (e.g. -e KEY=value).
|
||||||
|
- `-H, --header`: Set HTTP headers for SSE and HTTP transports (e.g. -H “X-Api-Key: abc123” -H “Authorization: Bearer abc123”).
|
||||||
|
- `--timeout`: Set connection timeout in milliseconds.
|
||||||
|
- `--trust`: Trust the server (bypass all tool call confirmation prompts).
|
||||||
|
- `--description`: Set the description for the server.
|
||||||
|
- `--include-tools`: A comma-separated list of tools to include.
|
||||||
|
- `--exclude-tools`: A comma-separated list of tools to exclude.
|
||||||
|
|
||||||
|
#### Adding an stdio server
|
||||||
|
|
||||||
|
This is the default transport for running local servers.
|
||||||
|
|
||||||
|
`# Basic syntaxqwen mcp add <name> <command> [args...] # Example: Adding a local serverqwen mcp add my-stdio-server -e API_KEY=123 /path/to/server arg1 arg2 arg3 # Example: Adding a local python serverqwen mcp add python-server python server.py --port 8080`
|
||||||
|
|
||||||
|
#### Adding an HTTP server
|
||||||
|
|
||||||
|
This transport is for servers that use the streamable HTTP transport.
|
||||||
|
|
||||||
|
`# Basic syntaxqwen mcp add --transport http <name> <url> # Example: Adding an HTTP serverqwen mcp add --transport http http-server https://api.example.com/mcp/ # Example: Adding an HTTP server with an authentication headerqwen mcp add --transport http secure-http https://api.example.com/mcp/ --header "Authorization: Bearer abc123"`
|
||||||
|
|
||||||
|
#### Adding an SSE server
|
||||||
|
|
||||||
|
This transport is for servers that use Server-Sent Events (SSE).
|
||||||
|
|
||||||
|
`# Basic syntaxqwen mcp add --transport sse <name> <url> # Example: Adding an SSE serverqwen mcp add --transport sse sse-server https://api.example.com/sse/ # Example: Adding an SSE server with an authentication headerqwen mcp add --transport sse secure-sse https://api.example.com/sse/ --header "Authorization: Bearer abc123"`
|
||||||
|
|
||||||
|
### Listing Servers (`qwen mcp list`)
|
||||||
|
|
||||||
|
To view all MCP servers currently configured, use the `list` command. It displays each server’s name, configuration details, and connection status.
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
|
||||||
|
`qwen mcp list`
|
||||||
|
|
||||||
|
**Example Output:**
|
||||||
|
|
||||||
|
`✓ stdio-server: command: python3 server.py (stdio) - Connected✓ http-server: https://api.example.com/mcp (http) - Connected✗ sse-server: https://api.example.com/sse (sse) - Disconnected`
|
||||||
|
|
||||||
|
### Removing a Server (`qwen mcp remove`)
|
||||||
|
|
||||||
|
To delete a server from your configuration, use the `remove` command with the server’s name.
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
|
||||||
|
`qwen mcp remove <name>`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
|
||||||
|
`qwen mcp remove my-server`
|
||||||
|
|
||||||
|
This will find and delete the “my-server” entry from the `mcpServers` object in the appropriate `settings.json`file based on the scope (`-s, --scope`).
|
||||||
@@ -1,108 +1,71 @@
|
|||||||
# Subagents
|
# Sub Agents
|
||||||
|
Sub Agents are specialized AI assistants that handle specific types of tasks within Qwen Code. They allow you to delegate focused work to AI agents that are configured with task-specific prompts, tools, and behaviors.
|
||||||
Subagents are specialized AI assistants that handle specific types of tasks within Qwen Code. They allow you to delegate focused work to AI agents that are configured with task-specific prompts, tools, and behaviors.
|
## What are Sub Agents?
|
||||||
|
Sub Agents are independent AI assistants that:
|
||||||
## What are Subagents?
|
- **Specialize in specific tasks** - Each Sub Agents is configured with a focused system prompt for particular types of work
|
||||||
|
- **Have separate context** - They maintain their own conversation history, separate from your main chat
|
||||||
Subagents are independent AI assistants that:
|
- **Use controlled tools** - You can configure which tools each Sub Agents has access to
|
||||||
|
- **Work autonomously** - Once given a task, they work independently until completion or failure
|
||||||
- **Specialize in specific tasks** - Each subagent is configured with a focused system prompt for particular types of work
|
- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time
|
||||||
- **Have separate context** - They maintain their own conversation history, separate from your main chat
|
|
||||||
- **Use controlled tools** - You can configure which tools each subagent has access to
|
|
||||||
- **Work autonomously** - Once given a task, they work independently until completion or failure
|
|
||||||
- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time
|
|
||||||
|
|
||||||
## Key Benefits
|
## Key Benefits
|
||||||
|
|
||||||
- **Task Specialization**: Create agents optimized for specific workflows (testing, documentation, refactoring, etc.)
|
- **Task Specialization**: Create agents optimized for specific workflows (testing, documentation, refactoring, etc.)
|
||||||
- **Context Isolation**: Keep specialized work separate from your main conversation
|
- **Context Isolation**: Keep specialized work separate from your main conversation
|
||||||
- **Reusability**: Save and reuse agent configurations across projects and sessions
|
- **Reusability**: Save and reuse agent configurations across projects and sessions
|
||||||
- **Controlled Access**: Limit which tools each agent can use for security and focus
|
- **Controlled Access**: Limit which tools each agent can use for security and focus
|
||||||
- **Progress Visibility**: Monitor agent execution with real-time progress updates
|
- **Progress Visibility**: Monitor agent execution with real-time progress updates
|
||||||
|
|
||||||
## How Subagents Work
|
## How Sub Agents Work
|
||||||
|
1. **Configuration**: You create Sub Agents configurations that define their behavior, tools, and system prompts
|
||||||
1. **Configuration**: You create subagent configurations that define their behavior, tools, and system prompts
|
2. **Delegation**: The main AI can automatically delegate tasks to appropriate Sub Agents
|
||||||
2. **Delegation**: The main AI can automatically delegate tasks to appropriate subagents
|
3. **Execution**: Sub Agents work independently, using their configured tools to complete tasks
|
||||||
3. **Execution**: Subagents work independently, using their configured tools to complete tasks
|
|
||||||
4. **Results**: They return results and execution summaries back to the main conversation
|
4. **Results**: They return results and execution summaries back to the main conversation
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
### Quick Start
|
### Quick Start
|
||||||
|
1. **Create your first Sub Agents**:
|
||||||
|
|
||||||
1. **Create your first subagent**:
|
`/agents create`
|
||||||
|
|
||||||
```
|
|
||||||
/agents create
|
|
||||||
```
|
|
||||||
|
|
||||||
Follow the guided wizard to create a specialized agent.
|
Follow the guided wizard to create a specialized agent.
|
||||||
|
|
||||||
2. **Manage existing agents**:
|
2. **Manage existing agents**:
|
||||||
|
|
||||||
```
|
`/agents manage`
|
||||||
/agents manage
|
|
||||||
```
|
|
||||||
|
|
||||||
View and manage your configured subagents.
|
View and manage your configured Sub Agents.
|
||||||
|
|
||||||
3. **Use subagents automatically**:
|
3. **Use Sub Agents automatically**: Simply ask the main AI to perform tasks that match your Sub Agents’ specializations. The AI will automatically delegate appropriate work.
|
||||||
Simply ask the main AI to perform tasks that match your subagents' specializations. The AI will automatically delegate appropriate work.
|
|
||||||
|
|
||||||
### Example Usage
|
### Example Usage
|
||||||
|
|
||||||
```
|
```
|
||||||
User: "Please write comprehensive tests for the authentication module"
|
User: "Please write comprehensive tests for the authentication module"
|
||||||
|
AI: I'll delegate this to your testing specialist Sub Agents.
|
||||||
AI: I'll delegate this to your testing specialist subagent.
|
[Delegates to "testing-expert" Sub Agents]
|
||||||
[Delegates to "testing-expert" subagent]
|
|
||||||
[Shows real-time progress of test creation]
|
[Shows real-time progress of test creation]
|
||||||
[Returns with completed test files and execution summary]
|
[Returns with completed test files and execution summary]`
|
||||||
```
|
```
|
||||||
|
|
||||||
## Management
|
## Management
|
||||||
|
|
||||||
### CLI Commands
|
### CLI Commands
|
||||||
|
Sub Agents are managed through the `/agents` slash command and its subcommands:
|
||||||
Subagents are managed through the `/agents` slash command and its subcommands:
|
#### /agents create
|
||||||
|
Creates a new Sub Agents through a guided step wizard.
|
||||||
#### `/agents create`
|
|
||||||
|
|
||||||
Creates a new subagent through a guided step wizard.
|
|
||||||
|
|
||||||
**Usage:**
|
**Usage:**
|
||||||
|
`/agents create`
|
||||||
```
|
#### /agents manage
|
||||||
/agents create
|
Opens an interactive management dialog for viewing and managing existing Sub Agents.
|
||||||
```
|
|
||||||
|
|
||||||
#### `/agents manage`
|
|
||||||
|
|
||||||
Opens an interactive management dialog for viewing and managing existing subagents.
|
|
||||||
|
|
||||||
**Usage:**
|
**Usage:**
|
||||||
|
`/agents manage`
|
||||||
```
|
|
||||||
/agents manage
|
|
||||||
```
|
|
||||||
|
|
||||||
### Storage Locations
|
### Storage Locations
|
||||||
|
Sub Agents are stored as Markdown files in two locations:
|
||||||
Subagents are stored as Markdown files in two locations:
|
- **Project-level**: `.qwen/agents/` (takes precedence)
|
||||||
|
- **User-level**: `~/.qwen/agents/` (fallback)
|
||||||
- **Project-level**: `.qwen/agents/` (takes precedence)
|
|
||||||
- **User-level**: `~/.qwen/agents/` (fallback)
|
|
||||||
|
|
||||||
This allows you to have both project-specific agents and personal agents that work across all projects.
|
This allows you to have both project-specific agents and personal agents that work across all projects.
|
||||||
|
|
||||||
### File Format
|
### File Format
|
||||||
|
Sub Agents are configured using Markdown files with YAML frontmatter. This format is human-readable and easy to edit with any text editor.
|
||||||
Subagents are configured using Markdown files with YAML frontmatter. This format is human-readable and easy to edit with any text editor.
|
|
||||||
|
|
||||||
#### Basic Structure
|
#### Basic Structure
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: agent-name
|
name: agent-name
|
||||||
description: Brief description of when and how to use this agent
|
description: Brief description of when and how to use this agent
|
||||||
@@ -116,10 +79,8 @@ System prompt content goes here.
|
|||||||
Multiple paragraphs are supported.
|
Multiple paragraphs are supported.
|
||||||
You can use ${variable} templating for dynamic content.
|
You can use ${variable} templating for dynamic content.
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Example Usage
|
#### Example Usage
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: project-documenter
|
name: project-documenter
|
||||||
description: Creates project documentation and README files
|
description: Creates project documentation and README files
|
||||||
@@ -135,38 +96,26 @@ Generated on: ${timestamp}
|
|||||||
Focus on creating clear, comprehensive documentation that helps both
|
Focus on creating clear, comprehensive documentation that helps both
|
||||||
new contributors and end users understand the project.
|
new contributors and end users understand the project.
|
||||||
```
|
```
|
||||||
|
## Using Sub Agents Effectively
|
||||||
## Using Subagents Effectively
|
|
||||||
|
|
||||||
### Automatic Delegation
|
### Automatic Delegation
|
||||||
|
|
||||||
Qwen Code proactively delegates tasks based on:
|
Qwen Code proactively delegates tasks based on:
|
||||||
|
|
||||||
- The task description in your request
|
- The task description in your request
|
||||||
- The description field in subagent configurations
|
- The description field in Sub Agents configurations
|
||||||
- Current context and available tools
|
- Current context and available tools
|
||||||
|
|
||||||
To encourage more proactive subagent use, include phrases like "use PROACTIVELY" or "MUST BE USED" in your description field.
|
To encourage more proactive Sub Agents use, include phrases like “use PROACTIVELY” or “MUST BE USED” in your description field.
|
||||||
|
|
||||||
### Explicit Invocation
|
### Explicit Invocation
|
||||||
|
Request a specific Sub Agents by mentioning it in your command:
|
||||||
Request a specific subagent by mentioning it in your command:
|
|
||||||
|
|
||||||
```
|
```
|
||||||
> Let the testing-expert subagent create unit tests for the payment module
|
Let the testing-expert Sub Agents create unit tests for the payment module
|
||||||
> Have the documentation-writer subagent update the API reference
|
Have the documentation-writer Sub Agents update the API reference
|
||||||
> Get the react-specialist subagent to optimize this component's performance
|
Get the react-specialist Sub Agents to optimize this component's performance
|
||||||
```
|
```
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
### Development Workflow Agents
|
### Development Workflow Agents
|
||||||
|
|
||||||
#### Testing Specialist
|
#### Testing Specialist
|
||||||
|
|
||||||
Perfect for comprehensive test creation and test-driven development.
|
Perfect for comprehensive test creation and test-driven development.
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: testing-expert
|
name: testing-expert
|
||||||
description: Writes comprehensive unit tests, integration tests, and handles test automation with best practices
|
description: Writes comprehensive unit tests, integration tests, and handles test automation with best practices
|
||||||
@@ -201,16 +150,13 @@ Focus on both positive and negative test cases.
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use Cases:**
|
**Use Cases:**
|
||||||
|
- “Write unit tests for the authentication service”
|
||||||
- "Write unit tests for the authentication service"
|
- “Create integration tests for the payment processing workflow”
|
||||||
- "Create integration tests for the payment processing workflow"
|
- “Add test coverage for edge cases in the data validation module”
|
||||||
- "Add test coverage for edge cases in the data validation module"
|
|
||||||
|
|
||||||
#### Documentation Writer
|
#### Documentation Writer
|
||||||
|
|
||||||
Specialized in creating clear, comprehensive documentation.
|
Specialized in creating clear, comprehensive documentation.
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: documentation-writer
|
name: documentation-writer
|
||||||
description: Creates comprehensive documentation, README files, API docs, and user guides
|
description: Creates comprehensive documentation, README files, API docs, and user guides
|
||||||
@@ -254,16 +200,13 @@ the actual implementation. Use clear headings, bullet points, and examples.
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use Cases:**
|
**Use Cases:**
|
||||||
|
- “Create API documentation for the user management endpoints”
|
||||||
- "Create API documentation for the user management endpoints"
|
- “Write a comprehensive README for this project”
|
||||||
- "Write a comprehensive README for this project"
|
- “Document the deployment process with troubleshooting steps”
|
||||||
- "Document the deployment process with troubleshooting steps"
|
|
||||||
|
|
||||||
#### Code Reviewer
|
#### Code Reviewer
|
||||||
|
|
||||||
Focused on code quality, security, and best practices.
|
Focused on code quality, security, and best practices.
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: code-reviewer
|
name: code-reviewer
|
||||||
description: Reviews code for best practices, security issues, performance, and maintainability
|
description: Reviews code for best practices, security issues, performance, and maintainability
|
||||||
@@ -296,18 +239,14 @@ Prioritize issues by impact and provide rationale for recommendations.
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use Cases:**
|
**Use Cases:**
|
||||||
|
- “Review this authentication implementation for security issues”
|
||||||
- "Review this authentication implementation for security issues"
|
- “Check the performance implications of this database query logic”
|
||||||
- "Check the performance implications of this database query logic"
|
- “Evaluate the code structure and suggest improvements”
|
||||||
- "Evaluate the code structure and suggest improvements"
|
|
||||||
|
|
||||||
### Technology-Specific Agents
|
### Technology-Specific Agents
|
||||||
|
|
||||||
#### React Specialist
|
#### React Specialist
|
||||||
|
|
||||||
Optimized for React development, hooks, and component patterns.
|
Optimized for React development, hooks, and component patterns.
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: react-specialist
|
name: react-specialist
|
||||||
description: Expert in React development, hooks, component patterns, and modern React best practices
|
description: Expert in React development, hooks, component patterns, and modern React best practices
|
||||||
@@ -343,16 +282,13 @@ Focus on accessibility and user experience considerations.
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use Cases:**
|
**Use Cases:**
|
||||||
|
- “Create a reusable data table component with sorting and filtering”
|
||||||
- "Create a reusable data table component with sorting and filtering"
|
- “Implement a custom hook for API data fetching with caching”
|
||||||
- "Implement a custom hook for API data fetching with caching"
|
- “Refactor this class component to use modern React patterns”
|
||||||
- "Refactor this class component to use modern React patterns"
|
|
||||||
|
|
||||||
#### Python Expert
|
#### Python Expert
|
||||||
|
|
||||||
Specialized in Python development, frameworks, and best practices.
|
Specialized in Python development, frameworks, and best practices.
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: python-expert
|
name: python-expert
|
||||||
description: Expert in Python development, frameworks, testing, and Python-specific best practices
|
description: Expert in Python development, frameworks, testing, and Python-specific best practices
|
||||||
@@ -389,88 +325,61 @@ Focus on writing clean, maintainable Python code that follows community standard
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Use Cases:**
|
**Use Cases:**
|
||||||
|
- “Create a FastAPI service for user authentication with JWT tokens”
|
||||||
- "Create a FastAPI service for user authentication with JWT tokens"
|
- “Implement a data processing pipeline with pandas and error handling”
|
||||||
- "Implement a data processing pipeline with pandas and error handling"
|
- “Write a CLI tool using argparse with comprehensive help documentation”
|
||||||
- "Write a CLI tool using argparse with comprehensive help documentation"
|
|
||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
|
|
||||||
### Design Principles
|
### Design Principles
|
||||||
|
|
||||||
#### Single Responsibility Principle
|
#### Single Responsibility Principle
|
||||||
|
Each Sub Agents should have a clear, focused purpose.
|
||||||
Each subagent should have a clear, focused purpose.
|
|
||||||
|
|
||||||
**✅ Good:**
|
**✅ Good:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: testing-expert
|
name: testing-expert
|
||||||
description: Writes comprehensive unit tests and integration tests
|
description: Writes comprehensive unit tests and integration tests
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
|
||||||
**❌ Avoid:**
|
**❌ Avoid:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: general-helper
|
name: general-helper
|
||||||
description: Helps with testing, documentation, code review, and deployment
|
description: Helps with testing, documentation, code review, and deployment
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
**Why:** Focused agents produce better results and are easier to maintain.
|
||||||
**Why:** Focused agents produce better results and are easier to maintain.
|
|
||||||
|
|
||||||
#### Clear Specialization
|
#### Clear Specialization
|
||||||
|
|
||||||
Define specific expertise areas rather than broad capabilities.
|
Define specific expertise areas rather than broad capabilities.
|
||||||
|
|
||||||
**✅ Good:**
|
**✅ Good:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: react-performance-optimizer
|
name: react-performance-optimizer
|
||||||
description: Optimizes React applications for performance using profiling and best practices
|
description: Optimizes React applications for performance using profiling and best practices
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
|
||||||
**❌ Avoid:**
|
**❌ Avoid:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
---
|
---
|
||||||
name: frontend-developer
|
name: frontend-developer
|
||||||
description: Works on frontend development tasks
|
description: Works on frontend development tasks
|
||||||
---
|
---
|
||||||
```
|
```
|
||||||
|
**Why:** Specific expertise leads to more targeted and effective assistance.
|
||||||
**Why:** Specific expertise leads to more targeted and effective assistance.
|
|
||||||
|
|
||||||
#### Actionable Descriptions
|
#### Actionable Descriptions
|
||||||
|
|
||||||
Write descriptions that clearly indicate when to use the agent.
|
Write descriptions that clearly indicate when to use the agent.
|
||||||
|
|
||||||
**✅ Good:**
|
**✅ Good:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
description: Reviews code for security vulnerabilities, performance issues, and maintainability concerns
|
description: Reviews code for security vulnerabilities, performance issues, and maintainability concerns
|
||||||
```
|
```
|
||||||
|
|
||||||
**❌ Avoid:**
|
**❌ Avoid:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
description: A helpful code reviewer
|
description: A helpful code reviewer
|
||||||
```
|
```
|
||||||
|
**Why:** Clear descriptions help the main AI choose the right agent for each task.
|
||||||
**Why:** Clear descriptions help the main AI choose the right agent for each task.
|
|
||||||
|
|
||||||
### Configuration Best Practices
|
### Configuration Best Practices
|
||||||
|
|
||||||
#### System Prompt Guidelines
|
#### System Prompt Guidelines
|
||||||
|
|
||||||
**Be Specific About Expertise:**
|
**Be Specific About Expertise:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
You are a Python testing specialist with expertise in:
|
You are a Python testing specialist with expertise in:
|
||||||
|
|
||||||
- pytest framework and fixtures
|
- pytest framework and fixtures
|
||||||
@@ -480,8 +389,7 @@ You are a Python testing specialist with expertise in:
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Include Step-by-Step Approaches:**
|
**Include Step-by-Step Approaches:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
For each testing task:
|
For each testing task:
|
||||||
|
|
||||||
1. Analyze the code structure and dependencies
|
1. Analyze the code structure and dependencies
|
||||||
@@ -492,8 +400,7 @@ For each testing task:
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Specify Output Standards:**
|
**Specify Output Standards:**
|
||||||
|
```
|
||||||
```markdown
|
|
||||||
Always follow these standards:
|
Always follow these standards:
|
||||||
|
|
||||||
- Use descriptive test names that explain the scenario
|
- Use descriptive test names that explain the scenario
|
||||||
@@ -503,10 +410,9 @@ Always follow these standards:
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Security Considerations
|
## Security Considerations
|
||||||
|
- **Tool Restrictions**: Sub Agents only have access to their configured tools
|
||||||
- **Tool Restrictions**: Subagents only have access to their configured tools
|
|
||||||
- **Sandboxing**: All tool execution follows the same security model as direct tool use
|
- **Sandboxing**: All tool execution follows the same security model as direct tool use
|
||||||
- **Audit Trail**: All subagent actions are logged and visible in real-time
|
- **Audit Trail**: All Sub Agents actions are logged and visible in real-time
|
||||||
- **Access Control**: Project and user-level separation provides appropriate boundaries
|
- **Access Control**: Project and user-level separation provides appropriate boundaries
|
||||||
- **Sensitive Information**: Avoid including secrets or credentials in agent configurations
|
- **Sensitive Information**: Avoid including secrets or credentials in agent configurations
|
||||||
- **Production Environments**: Consider separate agents for production vs development environments
|
- **Production Environments**: Consider separate agents for production vs development environments
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
Prerequisites:
|
Prerequisites:
|
||||||
|
|
||||||
- A [Qwen Code](https://chat.qwen.ai/auth?mode=register) account
|
- A [Qwen Code](https://chat.qwen.ai/auth?mode=register) account
|
||||||
- Requires [Node.js 20+](https://nodejs.org/download), you can use `node -v` check the version. If it's not installed, use the following command to install it.
|
- Requires [Node.js 20+](https://nodejs.org/download), you can use `node -v` to check the version. If it's not installed, use the following command to install it.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -qL https://www.npmjs.com/install.sh | sh
|
curl -qL https://www.npmjs.com/install.sh | sh
|
||||||
@@ -54,11 +54,13 @@ You'll be prompted to log in on first use. That's it! [Continue with Quickstart
|
|||||||
|
|
||||||
> [!tip]
|
> [!tip]
|
||||||
>
|
>
|
||||||
> See [advanced setup](/setup) for installation options or [troubleshooting](/troubleshooting) if you hit issues.
|
> See [troubleshooting](/troubleshooting) if you hit issues.
|
||||||
|
|
||||||
> [!note]
|
> [!note]
|
||||||
>
|
>
|
||||||
> **New VS Code Extension (Beta)**: Prefer a graphical interface? Our new [VS Code extension](/vs-code) provides an easy-to-use native IDE experience without requiring terminal familiarity. Simply install from the marketplace and start coding with Qwen Code directly in your sidebar.
|
> **New VS Code Extension (Beta)**: Prefer a graphical interface? Our new **VS Code extension** provides an easy-to-use native IDE experience without requiring terminal familiarity. Simply install from the marketplace and start coding with Qwen Code directly in your sidebar.
|
||||||
|
>
|
||||||
|
> 
|
||||||
|
|
||||||
## What Qwen Code does for you
|
## What Qwen Code does for you
|
||||||
|
|
||||||
@@ -72,57 +74,3 @@ You'll be prompted to log in on first use. That's it! [Continue with Quickstart
|
|||||||
* **Works in your terminal**: Not another chat window. Not another IDE. Qwen Code meets you where you already work, with the tools you already love.
|
* **Works in your terminal**: Not another chat window. Not another IDE. Qwen Code meets you where you already work, with the tools you already love.
|
||||||
* **Takes action**: Qwen Code can directly edit files, run commands, and create commits. Need more? [MCP](/mcp) lets Qwen Code read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling.
|
* **Takes action**: Qwen Code can directly edit files, run commands, and create commits. Need more? [MCP](/mcp) lets Qwen Code read your design docs in Google Drive, update your tickets in Jira, or use *your* custom developer tooling.
|
||||||
* **Unix philosophy**: Qwen Code is composable and scriptable. `tail -f app.log | qwen -p "Slack me if you see any anomalies appear in this log stream"` *works*. Your CI can run `qwen -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`.
|
* **Unix philosophy**: Qwen Code is composable and scriptable. `tail -f app.log | qwen -p "Slack me if you see any anomalies appear in this log stream"` *works*. Your CI can run `qwen -p "If there are new text strings, translate them into French and raise a PR for @lang-fr-team to review"`.
|
||||||
* **Enterprise-ready**: Use the Qwen Code API, or host on AWS or GCP. Enterprise-grade [security](/security) and [Terms of Service](https://qwenlm.github.io/qwen-code-docs/support/tos-privacy/) is built-in.
|
|
||||||
|
|
||||||
## Next steps
|
|
||||||
|
|
||||||
<CardGroup>
|
|
||||||
<Card title="Quickstart" icon="rocket" href="/quickstart">
|
|
||||||
See Qwen Code in action with practical examples
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Common workflows" icon="graduation-cap" href="/common-workflows">
|
|
||||||
Step-by-step guides for common workflows
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Troubleshooting" icon="wrench" href="/troubleshooting">
|
|
||||||
Solutions for common issues with Qwen Code
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="IDE setup" icon="laptop" href="/vs-code">
|
|
||||||
Add Qwen Code to your IDE
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
</CardGroup>
|
|
||||||
|
|
||||||
## Additional resources
|
|
||||||
|
|
||||||
<CardGroup>
|
|
||||||
<Card title="Build with the Agent SDK" icon="code-branch" href="https://docs.claude.com/docs/agent-sdk/overview">
|
|
||||||
Create custom AI agents with the Claude Agent SDK
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Host on AWS or GCP" icon="cloud" href="/third-party-integrations">
|
|
||||||
Configure Qwen Code with Amazon Bedrock or Google Vertex AI
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Settings" icon="gear" href="/settings">
|
|
||||||
Customize Qwen Code for your workflow
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Commands" icon="terminal" href="/cli-reference">
|
|
||||||
Learn about CLI commands and controls
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Reference implementation" icon="code" href="https://github.com/anthropics/claude-code/tree/main/.devcontainer">
|
|
||||||
Clone our development container reference implementation
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Security" icon="shield" href="/security">
|
|
||||||
Discover Qwen Code's safeguards and best practices for safe usage
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Privacy and data usage" icon="lock" href="/data-usage">
|
|
||||||
Understand how Qwen Code handles your data
|
|
||||||
</Card>
|
|
||||||
</CardGroup>
|
|
||||||
|
|||||||
@@ -91,10 +91,6 @@ You'll see the Qwen Code welcome screen with your session information, recent co
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
> [!caution]
|
|
||||||
>
|
|
||||||
> After logging in (Step 2), your credentials are stored on your system. If you need OpenAI API authentication, you can refer to [Authentication](/authentication).
|
|
||||||
|
|
||||||
## Chat with Qwen Code
|
## Chat with Qwen Code
|
||||||
|
|
||||||
### Ask your first question
|
### Ask your first question
|
||||||
@@ -239,16 +235,24 @@ review my changes and suggest improvements
|
|||||||
Here are the most important commands for daily use:
|
Here are the most important commands for daily use:
|
||||||
|
|
||||||
| Command | What it does | Example |
|
| Command | What it does | Example |
|
||||||
| ------------------- | --------------------------------- | ----------------------------------- |
|
| --------------------- | ------------------------------------------------------ | ---------------------------------- |
|
||||||
| `qwen` | Start interactive mode | `qwen` |
|
| `qwen` | start Qwen Code | `qwen` |
|
||||||
| `qwen-code "task"` | Run a one-time task | `qwen-code "fix the build error"` |
|
| `/chat` | Manually save and restore conversation history | Requires sub-commands |
|
||||||
| `qwen-code -p "query"` | Run one-off query, then exit | `qwen-code -p "explain this function"` |
|
| → `save <label>` | Save current conversation state | `/chat save Feature Ideation` |
|
||||||
| `qwen-code -c` | Continue most recent conversation | `qwen-code -c` |
|
| → `resume <label>` | Restore conversation from saved point | `/chat resume Feature Ideation` |
|
||||||
| `qwen-code -r` | Resume a previous conversation | `qwen-code -r` |
|
| → `list` | List all recoverable conversation labels | `/chat list` |
|
||||||
| `qwen-code commit` | Create a Git commit | `qwen-code commit` |
|
| → `delete <label>` | Delete saved conversation checkpoint | `/chat delete Feature Ideation` |
|
||||||
| `/clear` | Clear conversation history | `/clear` |
|
| → `share [file]` | Export conversation as Markdown or JSON | `/chat share Discussion Record.md` |
|
||||||
| `/help` | Show available commands | `/help` |
|
| `/summary` | Generate project summary based on conversation history | `/summary` |
|
||||||
| `quit` or Ctrl+C | Exit Qwen Code | `/quit` |
|
| `/compress` | Replace chat history with summary to save Tokens | `/compress` |
|
||||||
|
| `/clear` | Clear terminal screen content | `/clear` (shortcut: `Ctrl+L`) |
|
||||||
|
| `/theme` | Change Qwen Code visual theme | `/theme` |
|
||||||
|
| `/language` | View or change language settings | `/language` |
|
||||||
|
| → `ui [language]` | Set UI interface language | `/language ui zh-CN` |
|
||||||
|
| → `output [language]` | Set LLM output language | `/language output Chinese` |
|
||||||
|
| `/help` | Display help information for available commands | `/help` or `/?` |
|
||||||
|
| `/auth` | Change authentication method | `/auth` |
|
||||||
|
| `/quit` | Exit Qwen Code immediately | `/quit` or `/exit` |
|
||||||
|
|
||||||
See the [CLI reference](/cli-reference) for a complete list of commands.
|
See the [CLI reference](/cli-reference) for a complete list of commands.
|
||||||
|
|
||||||
@@ -281,30 +285,6 @@ See the [CLI reference](/cli-reference) for a complete list of commands.
|
|||||||
- Press ↑ for command history
|
- Press ↑ for command history
|
||||||
- Type `/` to see all slash commands
|
- Type `/` to see all slash commands
|
||||||
|
|
||||||
## What's next?
|
|
||||||
|
|
||||||
Now that you've learned the basics, explore more advanced features:
|
|
||||||
|
|
||||||
|
|
||||||
<CardGroup cols={3}>
|
|
||||||
<Card title="Common workflows" icon="graduation-cap" href="/en/common-workflows">
|
|
||||||
Step-by-step guides for common tasks
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="CLI reference" icon="terminal" href="/en/cli-reference">
|
|
||||||
Master all commands and options
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Configuration" icon="gear" href="/en/settings">
|
|
||||||
Customize Qwen Code for your workflow
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card title="Qwen Code on the web" icon="cloud" href="/en/claude-code-on-the-web">
|
|
||||||
Run tasks asynchronously in the cloud
|
|
||||||
</Card>
|
|
||||||
</CardGroup>
|
|
||||||
|
|
||||||
|
|
||||||
## Getting help
|
## Getting help
|
||||||
|
|
||||||
- **In Qwen Code**: Type `/help` or ask "how do I..."
|
- **In Qwen Code**: Type `/help` or ask "how do I..."
|
||||||
|
|||||||
259
docs/users/reference/cil-reference.md
Normal file
259
docs/users/reference/cil-reference.md
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
# Qwen Code Command Reference
|
||||||
|
|
||||||
|
This document details all commands supported by Qwen Code, helping you efficiently manage sessions, customize the interface, and control its behavior.
|
||||||
|
|
||||||
|
Qwen Code commands are triggered through specific prefixes and fall into three categories:
|
||||||
|
|
||||||
|
| Prefix Type | Function Description | Typical Use Case |
|
||||||
|
| -------------------------- | --------------------------------------------------- | ---------------------------------------------------------------- |
|
||||||
|
| Slash Commands (`/`) | Meta-level control of Qwen Code itself | Managing sessions, modifying settings, getting help |
|
||||||
|
| At Commands (`@`) | Quickly inject local file content into conversation | Allowing AI to analyze specified files or code under directories |
|
||||||
|
| Exclamation Commands (`!`) | Direct interaction with system Shell | Executing system commands like `git status`, `ls`, etc. |
|
||||||
|
|
||||||
|
## 1. Slash Commands (`/`)
|
||||||
|
|
||||||
|
Slash commands are used to manage Qwen Code sessions, interface, and basic behavior.
|
||||||
|
|
||||||
|
### 1.1 Session and Project Management
|
||||||
|
|
||||||
|
These commands help you save, restore, and summarize work progress.
|
||||||
|
|
||||||
|
| Command | Description | Usage Examples |
|
||||||
|
| ------------------ | --------------------------------------------------------- | ------------------------------------ |
|
||||||
|
| `/chat` | Manually save and restore conversation history | Requires sub-commands |
|
||||||
|
| → `save <label>` | Save current conversation state | `/chat save Feature Ideation` |
|
||||||
|
| → `resume <label>` | Restore conversation from saved point | `/chat resume Feature Ideation` |
|
||||||
|
| → `list` | List all recoverable conversation labels | `/chat list` |
|
||||||
|
| → `delete <label>` | Delete saved conversation checkpoint | `/chat delete Feature Ideation` |
|
||||||
|
| → `share [file]` | Export conversation as Markdown or JSON | `/chat share Discussion Record.md` |
|
||||||
|
| `/summary` | Generate project summary based on conversation history | `/summary` |
|
||||||
|
| `/compress` | Replace chat history with summary to save Tokens | `/compress` |
|
||||||
|
| `/restore` | Restore files to state before tool execution | `/restore` (list) or `/restore <ID>` |
|
||||||
|
| `/init` | Analyze current directory and create initial context file | `/init` |
|
||||||
|
|
||||||
|
### 1.2 Interface and Workspace Control
|
||||||
|
|
||||||
|
Commands for adjusting interface appearance and work environment.
|
||||||
|
|
||||||
|
| Command | Description | Usage Examples |
|
||||||
|
| ------------ | ---------------------------------------- | ----------------------------- |
|
||||||
|
| `/clear` | Clear terminal screen content | `/clear` (shortcut: `Ctrl+L`) |
|
||||||
|
| `/theme` | Change Qwen Code visual theme | `/theme` |
|
||||||
|
| `/vim` | Turn input area Vim editing mode on/off | `/vim` |
|
||||||
|
| `/directory` | Manage multi-directory support workspace | `/dir add ./src,./tests` |
|
||||||
|
| `/editor` | Open dialog to select supported editor | `/editor` |
|
||||||
|
|
||||||
|
### 1.3 Language Settings
|
||||||
|
|
||||||
|
Commands specifically for controlling interface and output language.
|
||||||
|
|
||||||
|
| Command | Description | Usage Examples |
|
||||||
|
| --------------------- | -------------------------------- | -------------------------- |
|
||||||
|
| `/language` | View or change language settings | `/language` |
|
||||||
|
| → `ui [language]` | Set UI interface language | `/language ui zh-CN` |
|
||||||
|
| → `output [language]` | Set LLM output language | `/language output Chinese` |
|
||||||
|
|
||||||
|
- Available UI languages: `zh-CN` (Simplified Chinese), `en-US` (English)
|
||||||
|
- Output language examples: `Chinese`, `English`, `Japanese`, etc.
|
||||||
|
|
||||||
|
### 1.4 Tool and Model Management
|
||||||
|
|
||||||
|
Commands for managing AI tools and models.
|
||||||
|
|
||||||
|
| Command | Description | Usage Examples |
|
||||||
|
| ---------------- | --------------------------------------------- | --------------------------------------------- |
|
||||||
|
| `/mcp` | List configured MCP servers and tools | `/mcp`, `/mcp desc` |
|
||||||
|
| `/tools` | Display currently available tool list | `/tools`, `/tools desc` |
|
||||||
|
| `/approval-mode` | Change approval mode for tool usage | `/approval-mode <mode (auto-edit)> --project` |
|
||||||
|
| →`plan` | Analysis only, no execution | Secure review |
|
||||||
|
| →`default` | Require approval for edits | Daily use |
|
||||||
|
| →`auto-edit` | Automatically approve edits | Trusted environment |
|
||||||
|
| →`yolo` | Automatically approve all | Quick prototyping |
|
||||||
|
| `/model` | Switch model used in current session | `/model` |
|
||||||
|
| `/extensions` | List all active extensions in current session | `/extensions` |
|
||||||
|
| `/memory` | Manage AI's instruction context | `/memory add Important Info` |
|
||||||
|
|
||||||
|
### 1.5 Information, Settings, and Help
|
||||||
|
|
||||||
|
Commands for obtaining information and performing system settings.
|
||||||
|
|
||||||
|
| Command | Description | Usage Examples |
|
||||||
|
| --------------- | ----------------------------------------------- | ------------------------------------------------ |
|
||||||
|
| `/help` | Display help information for available commands | `/help` or `/?` |
|
||||||
|
| `/about` | Display version information | `/about` |
|
||||||
|
| `/stats` | Display detailed statistics for current session | `/stats` |
|
||||||
|
| `/settings` | Open settings editor | `/settings` |
|
||||||
|
| `/auth` | Change authentication method | `/auth` |
|
||||||
|
| `/bug` | Submit issue about Qwen Code | `/bug Button click unresponsive` |
|
||||||
|
| `/copy` | Copy last output content to clipboard | `/copy` |
|
||||||
|
| `/quit-confirm` | Show confirmation dialog before quitting | `/quit-confirm` (shortcut: press `Ctrl+C` twice) |
|
||||||
|
| `/quit` | Exit Qwen Code immediately | `/quit` or `/exit` |
|
||||||
|
|
||||||
|
### 1.6 Common Shortcuts
|
||||||
|
|
||||||
|
| Shortcut | Function | Note |
|
||||||
|
| ------------------ | ----------------------- | ---------------------- |
|
||||||
|
| `Ctrl/cmd+L` | Clear screen | Equivalent to `/clear` |
|
||||||
|
| `Ctrl/cmd+T` | Toggle tool description | MCP tool management |
|
||||||
|
| `Ctrl/cmd+C`×2 | Exit confirmation | Secure exit mechanism |
|
||||||
|
| `Ctrl/cmd+Z` | Undo input | Text editing |
|
||||||
|
| `Ctrl/cmd+Shift+Z` | Redo input | Text editing |
|
||||||
|
|
||||||
|
## 2. @ Commands (Introducing Files)
|
||||||
|
|
||||||
|
@ commands are used to quickly add local file or directory content to the conversation.
|
||||||
|
|
||||||
|
| Command Format | Description | Examples |
|
||||||
|
| ------------------- | -------------------------------------------- | ------------------------------------------------ |
|
||||||
|
| `@<file path>` | Inject content of specified file | `@src/main.py Please explain this code` |
|
||||||
|
| `@<directory path>` | Recursively read all text files in directory | `@docs/ Summarize content of this document` |
|
||||||
|
| Standalone `@` | Used when discussing `@` symbol itself | `@ What is this symbol used for in programming?` |
|
||||||
|
|
||||||
|
Note: Spaces in paths need to be escaped with backslash (e.g., `@My\ Documents/file.txt`)
|
||||||
|
|
||||||
|
## 3. Exclamation Commands (`!`) - Shell Command Execution
|
||||||
|
|
||||||
|
Exclamation commands allow you to execute system commands directly within Qwen Code.
|
||||||
|
|
||||||
|
| Command Format | Description | Examples |
|
||||||
|
| ------------------ | ------------------------------------------------------------------ | -------------------------------------- |
|
||||||
|
| `!<shell command>` | Execute command in sub-Shell | `!ls -la`, `!git status` |
|
||||||
|
| Standalone `!` | Switch Shell mode, any input is executed directly as Shell command | `!`(enter) → Input command → `!`(exit) |
|
||||||
|
|
||||||
|
Environment Variables: Commands executed via `!` will set the `QWEN_CODE=1` environment variable.
|
||||||
|
|
||||||
|
## 4. Custom Commands
|
||||||
|
|
||||||
|
Save frequently used prompts as shortcut commands to improve work efficiency and ensure consistency.
|
||||||
|
|
||||||
|
### 📋 Quick Overview
|
||||||
|
|
||||||
|
| Function | Description | Advantages | Priority | Applicable Scenarios |
|
||||||
|
| ---------------- | ------------------------------------------ | -------------------------------------- | -------- | ---------------------------------------------------- |
|
||||||
|
| Namespace | Subdirectory creates colon-named commands | Better command organization | | |
|
||||||
|
| Global Commands | `~/.qwen/commands/` | Available in all projects | Low | Personal frequently used commands, cross-project use |
|
||||||
|
| Project Commands | `<project root directory>/.qwen/commands/` | Project-specific, version-controllable | High | Team sharing, project-specific commands |
|
||||||
|
|
||||||
|
Priority Rules: Project commands > User commands (project command used when names are same)
|
||||||
|
|
||||||
|
### 🔤 Command Naming Rules
|
||||||
|
|
||||||
|
#### File Path to Command Name Mapping Table
|
||||||
|
|
||||||
|
| File Location | Generated Command | Example Call |
|
||||||
|
| ---------------------------- | ----------------- | --------------------- |
|
||||||
|
| `~/.qwen/commands/test.toml` | `/test` | `/test Parameter` |
|
||||||
|
| `<project>/git/commit.toml` | `/git:commit` | `/git:commit Message` |
|
||||||
|
|
||||||
|
Naming Rules: Path separator (`/` or `\`) converted to colon (`:`)
|
||||||
|
|
||||||
|
### 📄 TOML File Format Specification
|
||||||
|
|
||||||
|
| Field | Required | Description | Example |
|
||||||
|
| ------------- | -------- | ---------------------------------------- | ------------------------------------------ |
|
||||||
|
| `prompt` | Required | Prompt content sent to model | `prompt = "Please analyze code: {{args}}"` |
|
||||||
|
| `description` | Optional | Command description (displayed in /help) | `description = "Code analysis tool"` |
|
||||||
|
|
||||||
|
### 🔧 Parameter Processing Mechanism
|
||||||
|
|
||||||
|
| Processing Method | Syntax | Applicable Scenarios | Security Features |
|
||||||
|
| ---------------------------- | ------------------ | ------------------------------------ | -------------------------------------- |
|
||||||
|
| Context-aware Injection | `{{args}}` | Need precise parameter control | Automatic Shell escaping |
|
||||||
|
| Default Parameter Processing | No special marking | Simple commands, parameter appending | Append as-is |
|
||||||
|
| Shell Command Injection | `!{command}` | Need dynamic content | Execution confirmation required before |
|
||||||
|
|
||||||
|
#### 1. Context-aware Injection (`{{args}}`)
|
||||||
|
|
||||||
|
| Scenario | TOML Configuration | Call Method | Actual Effect |
|
||||||
|
| ---------------- | --------------------------------------- | --------------------- | ------------------------ |
|
||||||
|
| Raw Injection | `prompt = "Fix: {{args}}"` | `/fix "Button issue"` | `Fix: "Button issue"` |
|
||||||
|
| In Shell Command | `prompt = "Search: !{grep {{args}} .}"` | `/search "hello"` | Execute `grep "hello" .` |
|
||||||
|
|
||||||
|
#### 2. Default Parameter Processing
|
||||||
|
|
||||||
|
| Input Situation | Processing Method | Example |
|
||||||
|
| --------------- | ------------------------------------------------------ | ---------------------------------------------- |
|
||||||
|
| Has parameters | Append to end of prompt (separated by two line breaks) | `/cmd parameter` → Original prompt + parameter |
|
||||||
|
| No parameters | Send prompt as is | `/cmd` → Original prompt |
|
||||||
|
|
||||||
|
🚀 Dynamic Content Injection
|
||||||
|
|
||||||
|
| Injection Type | Syntax | Processing Order | Purpose |
|
||||||
|
| --------------------- | -------------- | ------------------- | -------------------------------- |
|
||||||
|
| File Content | `@{file path}` | Processed first | Inject static reference files |
|
||||||
|
| Shell Commands | `!{command}` | Processed in middle | Inject dynamic execution results |
|
||||||
|
| Parameter Replacement | `{{args}}` | Processed last | Inject user parameters |
|
||||||
|
|
||||||
|
#### 3. Shell Command Execution (`!{...}`)
|
||||||
|
|
||||||
|
| Operation | User Interaction |
|
||||||
|
| -------------------------------- | ------------------- |
|
||||||
|
| 1️⃣ Parse command and parameters | - |
|
||||||
|
| 2️⃣ Automatic Shell escaping | - |
|
||||||
|
| 3️⃣ Show confirmation dialog | ✅ User confirmation |
|
||||||
|
| 4️⃣ Execute command | - |
|
||||||
|
| 5️⃣ Inject output to prompt | - |
|
||||||
|
|
||||||
|
Example: Git Commit Message Generation
|
||||||
|
|
||||||
|
```
|
||||||
|
# git/commit.toml
|
||||||
|
description = "Generate Commit message based on staged changes"
|
||||||
|
prompt = """
|
||||||
|
Please generate a Commit message based on the following diff:
|
||||||
|
diff
|
||||||
|
!{git diff --staged}
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. File Content Injection (`@{...}`)
|
||||||
|
|
||||||
|
| File Type | Support Status | Processing Method |
|
||||||
|
| ------------ | --------------------- | --------------------------- |
|
||||||
|
| Text Files | ✅ Full Support | Directly inject content |
|
||||||
|
| Images/PDF | ✅ Multi-modal Support | Encode and inject |
|
||||||
|
| Binary Files | ⚠️ Limited Support | May be skipped or truncated |
|
||||||
|
| Directory | ✅ Recursive Injection | Follow .gitignore rules |
|
||||||
|
|
||||||
|
Example: Code Review Command
|
||||||
|
|
||||||
|
```
|
||||||
|
# review.toml
|
||||||
|
description = "Code review based on best practices"
|
||||||
|
prompt = """
|
||||||
|
Review {{args}}, reference standards:
|
||||||
|
|
||||||
|
@{docs/code-standards.md}
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🛠️ Practical Creation Example
|
||||||
|
|
||||||
|
#### "Pure Function Refactoring" Command Creation Steps Table
|
||||||
|
|
||||||
|
| Operation | Command/Code |
|
||||||
|
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| 1️⃣ Create directory structure | `mkdir -p ~/.qwen/commands/refactor` |
|
||||||
|
| 2️⃣ Create command file | `touch ~/.qwen/commands/refactor/pure.toml` |
|
||||||
|
| 3️⃣ Edit command content | ```<br># ~/.qwen/commands/refactor/pure.toml<br>description = "Refactor code to pure function"<br>prompt = """<br>Please analyze code in current context, refactor to pure function.<br>Requirements:<br>1. Provide refactored code<br>2. Explain key changes and pure function characteristic implementation<br>3. Maintain function unchanged<br>"""<br>``` |
|
||||||
|
| 4️⃣ Test command | `@file.js` → `/refactor:pure` |
|
||||||
|
|
||||||
|
### 💡 Custom Command Best Practices Summary
|
||||||
|
|
||||||
|
#### Command Design Recommendations Table
|
||||||
|
|
||||||
|
| Practice Points | Recommended Approach | Avoid |
|
||||||
|
| -------------------- | ----------------------------------- | ------------------------------------------- |
|
||||||
|
| Command Naming | Use namespaces for organization | Avoid overly generic names |
|
||||||
|
| Parameter Processing | Clearly use `{{args}}` | Rely on default appending (easy to confuse) |
|
||||||
|
| Error Handling | Utilize Shell error output | Ignore execution failure |
|
||||||
|
| File Organization | Organize by function in directories | All commands in root directory |
|
||||||
|
| Description Field | Always provide clear description | Rely on auto-generated description |
|
||||||
|
|
||||||
|
#### Security Features Reminder Table
|
||||||
|
|
||||||
|
| Security Mechanism | Protection Effect | User Operation |
|
||||||
|
| ---------------------- | -------------------------- | ---------------------- |
|
||||||
|
| Shell Escaping | Prevent command injection | Automatic processing |
|
||||||
|
| Execution Confirmation | Avoid accidental execution | Dialog confirmation |
|
||||||
|
| Error Reporting | Help diagnose issues | View error information |
|
||||||
Reference in New Issue
Block a user