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
|
||||
> - Request a glossary of project-specific terms
|
||||
|
||||
|
||||
### Find relevant code
|
||||
|
||||
Suppose you need to locate code related to a specific feature or functionality.
|
||||
@@ -88,12 +87,12 @@ I'm seeing an error when I run npm test
|
||||
|
||||
2. Ask for fix recommendations
|
||||
```
|
||||
suggest a few ways to fix the @ts-ignore in user. ts
|
||||
suggest a few ways to fix the @ts-ignore in user.ts
|
||||
```
|
||||
|
||||
3. Apply the fix
|
||||
```
|
||||
update user. ts to add the null check you suggested
|
||||
update user.tsto add the null check you suggested
|
||||
```
|
||||
|
||||
> [!tip] Tips:
|
||||
@@ -185,15 +184,15 @@ Then select "Create New subagent" and follow the prompts to define:
|
||||
|
||||
> [!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
|
||||
> - 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
|
||||
|
||||
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
|
||||
|
||||
@@ -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**
|
||||
|
||||
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
|
||||
/approval-mode plan -p "Analyze the authentication system and suggest improvements"
|
||||
qwen --prompt "What is machine learning?"
|
||||
```
|
||||
|
||||
### Example: Planning a complex refactor
|
||||
@@ -245,7 +244,7 @@ How should we handle database migration?
|
||||
### Configure Plan Mode as default
|
||||
|
||||
```json
|
||||
// .qwen-code/settings.json
|
||||
// .qwen/settings.json
|
||||
{
|
||||
"permissions": {
|
||||
"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
|
||||
|
||||
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
|
||||
```
|
||||
> check if the documentation follows our project standards
|
||||
check if the documentation follows our project standards
|
||||
```
|
||||
|
||||
> [!tip] Tips:
|
||||
@@ -354,9 +351,9 @@ You can use any of these methods:
|
||||
|
||||
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)
|
||||
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?
|
||||
```
|
||||
@@ -394,7 +391,6 @@ What HTML structure would recreate this component?
|
||||
> - You can work with multiple images in a conversation
|
||||
> - Image analysis works with diagrams, screenshots, mockups, and more
|
||||
|
||||
|
||||
## Reference files and directories
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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:
|
||||
>
|
||||
@@ -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.
|
||||
|
||||
> [!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
|
||||
```
|
||||
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.
|
||||
@@ -443,7 +435,8 @@ 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.
|
||||
|
||||
2. Refine the thinking with follow-up prompts
|
||||
2. Refine the thinking with follow-up prompts
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
> [!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]
|
||||
> 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
|
||||
cd ../project-bugfix
|
||||
qwen
|
||||
@@ -594,7 +567,7 @@ git worktree remove ../project-feature-a
|
||||
> [!tip] Tips:
|
||||
>
|
||||
> - 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
|
||||
> - 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
|
||||
@@ -604,9 +577,9 @@ git worktree remove ../project-feature-a
|
||||
> - 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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
**Pipe data through Claude:**
|
||||
**Pipe data through Qwen Code:**
|
||||
|
||||
```bash
|
||||
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:
|
||||
>
|
||||
> - 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 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
|
||||
|
||||
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?
|
||||
```
|
||||
|
||||
|
||||
> [!note]
|
||||
>
|
||||
> 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
|
||||
> - Ask specific questions to get detailed answers
|
||||
> - 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,172 +1,121 @@
|
||||
# Subagents
|
||||
|
||||
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 Subagents?
|
||||
|
||||
Subagents are independent AI assistants that:
|
||||
|
||||
- **Specialize in specific tasks** - Each subagent 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
|
||||
- **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
|
||||
# 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.
|
||||
## What are Sub Agents?
|
||||
Sub Agents are independent AI assistants that:
|
||||
- **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
|
||||
- **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
|
||||
- **Provide detailed feedback** - You can see their progress, tool usage, and execution statistics in real-time
|
||||
|
||||
## Key Benefits
|
||||
|
||||
- **Task Specialization**: Create agents optimized for specific workflows (testing, documentation, refactoring, etc.)
|
||||
- **Context Isolation**: Keep specialized work separate from your main conversation
|
||||
- **Reusability**: Save and reuse agent configurations across projects and sessions
|
||||
- **Controlled Access**: Limit which tools each agent can use for security and focus
|
||||
- **Progress Visibility**: Monitor agent execution with real-time progress updates
|
||||
|
||||
## How Subagents Work
|
||||
|
||||
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 subagents
|
||||
3. **Execution**: Subagents work independently, using their configured tools to complete tasks
|
||||
## How Sub Agents Work
|
||||
1. **Configuration**: You create Sub Agents configurations that define their behavior, tools, and system prompts
|
||||
2. **Delegation**: The main AI can automatically delegate tasks to appropriate Sub Agents
|
||||
3. **Execution**: Sub Agents work independently, using their configured tools to complete tasks
|
||||
4. **Results**: They return results and execution summaries back to the main conversation
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 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**:
|
||||
|
||||
```
|
||||
/agents manage
|
||||
```
|
||||
`/agents manage`
|
||||
|
||||
View and manage your configured subagents.
|
||||
|
||||
3. **Use subagents automatically**:
|
||||
Simply ask the main AI to perform tasks that match your subagents' specializations. The AI will automatically delegate appropriate work.
|
||||
View and manage your configured Sub Agents.
|
||||
|
||||
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.
|
||||
|
||||
### Example Usage
|
||||
|
||||
```
|
||||
User: "Please write comprehensive tests for the authentication module"
|
||||
|
||||
AI: I'll delegate this to your testing specialist subagent.
|
||||
[Delegates to "testing-expert" subagent]
|
||||
AI: I'll delegate this to your testing specialist Sub Agents.
|
||||
[Delegates to "testing-expert" Sub Agents]
|
||||
[Shows real-time progress of test creation]
|
||||
[Returns with completed test files and execution summary]
|
||||
[Returns with completed test files and execution summary]`
|
||||
```
|
||||
|
||||
## Management
|
||||
|
||||
### CLI Commands
|
||||
|
||||
Subagents are managed through the `/agents` slash command and its subcommands:
|
||||
|
||||
#### `/agents create`
|
||||
|
||||
Creates a new subagent through a guided step wizard.
|
||||
|
||||
Sub Agents are managed through the `/agents` slash command and its subcommands:
|
||||
#### /agents create
|
||||
Creates a new Sub Agents through a guided step wizard.
|
||||
**Usage:**
|
||||
|
||||
```
|
||||
/agents create
|
||||
```
|
||||
|
||||
#### `/agents manage`
|
||||
|
||||
Opens an interactive management dialog for viewing and managing existing subagents.
|
||||
|
||||
`/agents create`
|
||||
#### /agents manage
|
||||
Opens an interactive management dialog for viewing and managing existing Sub Agents.
|
||||
**Usage:**
|
||||
|
||||
```
|
||||
/agents manage
|
||||
```
|
||||
|
||||
`/agents manage`
|
||||
### Storage Locations
|
||||
|
||||
Subagents are stored as Markdown files in two locations:
|
||||
|
||||
- **Project-level**: `.qwen/agents/` (takes precedence)
|
||||
- **User-level**: `~/.qwen/agents/` (fallback)
|
||||
Sub Agents are stored as Markdown files in two locations:
|
||||
- **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.
|
||||
|
||||
### File Format
|
||||
|
||||
Subagents are configured using Markdown files with YAML frontmatter. This format is human-readable and easy to edit with any text editor.
|
||||
|
||||
Sub Agents are configured using Markdown files with YAML frontmatter. This format is human-readable and easy to edit with any text editor.
|
||||
#### Basic Structure
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: agent-name
|
||||
description: Brief description of when and how to use this agent
|
||||
tools:
|
||||
- tool1
|
||||
- tool2
|
||||
- tool3 # Optional
|
||||
tools:
|
||||
- tool1
|
||||
- tool2
|
||||
- tool3 # Optional
|
||||
---
|
||||
|
||||
System prompt content goes here.
|
||||
Multiple paragraphs are supported.
|
||||
You can use ${variable} templating for dynamic content.
|
||||
```
|
||||
|
||||
#### Example Usage
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: project-documenter
|
||||
description: Creates project documentation and README files
|
||||
---
|
||||
|
||||
|
||||
You are a documentation specialist for the ${project_name} project.
|
||||
|
||||
|
||||
Your task: ${task_description}
|
||||
|
||||
|
||||
Working directory: ${current_directory}
|
||||
Generated on: ${timestamp}
|
||||
|
||||
|
||||
Focus on creating clear, comprehensive documentation that helps both
|
||||
new contributors and end users understand the project.
|
||||
```
|
||||
|
||||
## Using Subagents Effectively
|
||||
|
||||
## Using Sub Agents Effectively
|
||||
### Automatic Delegation
|
||||
|
||||
Qwen Code proactively delegates tasks based on:
|
||||
|
||||
- The task description in your request
|
||||
- The description field in subagent configurations
|
||||
- The description field in Sub Agents configurations
|
||||
- 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
|
||||
|
||||
Request a specific subagent by mentioning it in your command:
|
||||
|
||||
Request a specific Sub Agents by mentioning it in your command:
|
||||
```
|
||||
> Let the testing-expert subagent create unit tests for the payment module
|
||||
> Have the documentation-writer subagent update the API reference
|
||||
> Get the react-specialist subagent to optimize this component's performance
|
||||
Let the testing-expert Sub Agents create unit tests for the payment module
|
||||
Have the documentation-writer Sub Agents update the API reference
|
||||
Get the react-specialist Sub Agents to optimize this component's performance
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Development Workflow Agents
|
||||
|
||||
#### Testing Specialist
|
||||
|
||||
Perfect for comprehensive test creation and test-driven development.
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: testing-expert
|
||||
description: Writes comprehensive unit tests, integration tests, and handles test automation with best practices
|
||||
@@ -176,41 +125,38 @@ tools:
|
||||
- read_many_files
|
||||
- run_shell_command
|
||||
---
|
||||
|
||||
|
||||
You are a testing specialist focused on creating high-quality, maintainable tests.
|
||||
|
||||
|
||||
Your expertise includes:
|
||||
|
||||
|
||||
- Unit testing with appropriate mocking and isolation
|
||||
- Integration testing for component interactions
|
||||
- Test-driven development practices
|
||||
- Edge case identification and comprehensive coverage
|
||||
- Performance and load testing when appropriate
|
||||
|
||||
|
||||
For each testing task:
|
||||
|
||||
|
||||
1. Analyze the code structure and dependencies
|
||||
2. Identify key functionality, edge cases, and error conditions
|
||||
3. Create comprehensive test suites with descriptive names
|
||||
4. Include proper setup/teardown and meaningful assertions
|
||||
5. Add comments explaining complex test scenarios
|
||||
6. Ensure tests are maintainable and follow DRY principles
|
||||
|
||||
|
||||
Always follow testing best practices for the detected language and framework.
|
||||
Focus on both positive and negative test cases.
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
|
||||
- "Write unit tests for the authentication service"
|
||||
- "Create integration tests for the payment processing workflow"
|
||||
- "Add test coverage for edge cases in the data validation module"
|
||||
- “Write unit tests for the authentication service”
|
||||
- “Create integration tests for the payment processing workflow”
|
||||
- “Add test coverage for edge cases in the data validation module”
|
||||
|
||||
#### Documentation Writer
|
||||
|
||||
Specialized in creating clear, comprehensive documentation.
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: documentation-writer
|
||||
description: Creates comprehensive documentation, README files, API docs, and user guides
|
||||
@@ -220,50 +166,47 @@ tools:
|
||||
- read_many_files
|
||||
- web_search
|
||||
---
|
||||
|
||||
|
||||
You are a technical documentation specialist for ${project_name}.
|
||||
|
||||
|
||||
Your role is to create clear, comprehensive documentation that serves both
|
||||
developers and end users. Focus on:
|
||||
|
||||
|
||||
**For API Documentation:**
|
||||
|
||||
|
||||
- Clear endpoint descriptions with examples
|
||||
- Parameter details with types and constraints
|
||||
- Response format documentation
|
||||
- Error code explanations
|
||||
- Authentication requirements
|
||||
|
||||
|
||||
**For User Documentation:**
|
||||
|
||||
|
||||
- Step-by-step instructions with screenshots when helpful
|
||||
- Installation and setup guides
|
||||
- Configuration options and examples
|
||||
- Troubleshooting sections for common issues
|
||||
- FAQ sections based on common user questions
|
||||
|
||||
|
||||
**For Developer Documentation:**
|
||||
|
||||
|
||||
- Architecture overviews and design decisions
|
||||
- Code examples that actually work
|
||||
- Contributing guidelines
|
||||
- Development environment setup
|
||||
|
||||
|
||||
Always verify code examples and ensure documentation stays current with
|
||||
the actual implementation. Use clear headings, bullet points, and examples.
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
|
||||
- "Create API documentation for the user management endpoints"
|
||||
- "Write a comprehensive README for this project"
|
||||
- "Document the deployment process with troubleshooting steps"
|
||||
- “Create API documentation for the user management endpoints”
|
||||
- “Write a comprehensive README for this project”
|
||||
- “Document the deployment process with troubleshooting steps”
|
||||
|
||||
#### Code Reviewer
|
||||
|
||||
Focused on code quality, security, and best practices.
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: code-reviewer
|
||||
description: Reviews code for best practices, security issues, performance, and maintainability
|
||||
@@ -271,11 +214,11 @@ tools:
|
||||
- read_file
|
||||
- read_many_files
|
||||
---
|
||||
|
||||
|
||||
You are an experienced code reviewer focused on quality, security, and maintainability.
|
||||
|
||||
|
||||
Review criteria:
|
||||
|
||||
|
||||
- **Code Structure**: Organization, modularity, and separation of concerns
|
||||
- **Performance**: Algorithmic efficiency and resource usage
|
||||
- **Security**: Vulnerability assessment and secure coding practices
|
||||
@@ -283,31 +226,27 @@ Review criteria:
|
||||
- **Error Handling**: Proper exception handling and edge case coverage
|
||||
- **Readability**: Clear naming, comments, and code organization
|
||||
- **Testing**: Test coverage and testability considerations
|
||||
|
||||
|
||||
Provide constructive feedback with:
|
||||
|
||||
|
||||
1. **Critical Issues**: Security vulnerabilities, major bugs
|
||||
2. **Important Improvements**: Performance issues, design problems
|
||||
3. **Minor Suggestions**: Style improvements, refactoring opportunities
|
||||
4. **Positive Feedback**: Well-implemented patterns and good practices
|
||||
|
||||
|
||||
Focus on actionable feedback with specific examples and suggested solutions.
|
||||
Prioritize issues by impact and provide rationale for recommendations.
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
|
||||
- "Review this authentication implementation for security issues"
|
||||
- "Check the performance implications of this database query logic"
|
||||
- "Evaluate the code structure and suggest improvements"
|
||||
- “Review this authentication implementation for security issues”
|
||||
- “Check the performance implications of this database query logic”
|
||||
- “Evaluate the code structure and suggest improvements”
|
||||
|
||||
### Technology-Specific Agents
|
||||
|
||||
#### React Specialist
|
||||
|
||||
Optimized for React development, hooks, and component patterns.
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: react-specialist
|
||||
description: Expert in React development, hooks, component patterns, and modern React best practices
|
||||
@@ -317,42 +256,39 @@ tools:
|
||||
- read_many_files
|
||||
- run_shell_command
|
||||
---
|
||||
|
||||
|
||||
You are a React specialist with deep expertise in modern React development.
|
||||
|
||||
|
||||
Your expertise covers:
|
||||
|
||||
|
||||
- **Component Design**: Functional components, custom hooks, composition patterns
|
||||
- **State Management**: useState, useReducer, Context API, and external libraries
|
||||
- **Performance**: React.memo, useMemo, useCallback, code splitting
|
||||
- **Testing**: React Testing Library, Jest, component testing strategies
|
||||
- **TypeScript Integration**: Proper typing for props, hooks, and components
|
||||
- **Modern Patterns**: Suspense, Error Boundaries, Concurrent Features
|
||||
|
||||
|
||||
For React tasks:
|
||||
|
||||
|
||||
1. Use functional components and hooks by default
|
||||
2. Implement proper TypeScript typing
|
||||
3. Follow React best practices and conventions
|
||||
4. Consider performance implications
|
||||
5. Include appropriate error handling
|
||||
6. Write testable, maintainable code
|
||||
|
||||
|
||||
Always stay current with React best practices and avoid deprecated patterns.
|
||||
Focus on accessibility and user experience considerations.
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
|
||||
- "Create a reusable data table component with sorting and filtering"
|
||||
- "Implement a custom hook for API data fetching with caching"
|
||||
- "Refactor this class component to use modern React patterns"
|
||||
- “Create a reusable data table component with sorting and filtering”
|
||||
- “Implement a custom hook for API data fetching with caching”
|
||||
- “Refactor this class component to use modern React patterns”
|
||||
|
||||
#### Python Expert
|
||||
|
||||
Specialized in Python development, frameworks, and best practices.
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: python-expert
|
||||
description: Expert in Python development, frameworks, testing, and Python-specific best practices
|
||||
@@ -362,11 +298,11 @@ tools:
|
||||
- read_many_files
|
||||
- run_shell_command
|
||||
---
|
||||
|
||||
|
||||
You are a Python expert with deep knowledge of the Python ecosystem.
|
||||
|
||||
|
||||
Your expertise includes:
|
||||
|
||||
|
||||
- **Core Python**: Pythonic patterns, data structures, algorithms
|
||||
- **Frameworks**: Django, Flask, FastAPI, SQLAlchemy
|
||||
- **Testing**: pytest, unittest, mocking, test-driven development
|
||||
@@ -374,9 +310,9 @@ Your expertise includes:
|
||||
- **Async Programming**: asyncio, async/await patterns
|
||||
- **Package Management**: pip, poetry, virtual environments
|
||||
- **Code Quality**: PEP 8, type hints, linting with pylint/flake8
|
||||
|
||||
|
||||
For Python tasks:
|
||||
|
||||
|
||||
1. Follow PEP 8 style guidelines
|
||||
2. Use type hints for better code documentation
|
||||
3. Implement proper error handling with specific exceptions
|
||||
@@ -384,95 +320,68 @@ For Python tasks:
|
||||
5. Consider performance and memory usage
|
||||
6. Include appropriate logging
|
||||
7. Write testable, modular code
|
||||
|
||||
|
||||
Focus on writing clean, maintainable Python code that follows community standards.
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
|
||||
- "Create a FastAPI service for user authentication with JWT tokens"
|
||||
- "Implement a data processing pipeline with pandas and error handling"
|
||||
- "Write a CLI tool using argparse with comprehensive help documentation"
|
||||
- “Create a FastAPI service for user authentication with JWT tokens”
|
||||
- “Implement a data processing pipeline with pandas and error handling”
|
||||
- “Write a CLI tool using argparse with comprehensive help documentation”
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Design Principles
|
||||
|
||||
#### Single Responsibility Principle
|
||||
|
||||
Each subagent should have a clear, focused purpose.
|
||||
|
||||
Each Sub Agents should have a clear, focused purpose.
|
||||
**✅ Good:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: testing-expert
|
||||
description: Writes comprehensive unit tests and integration tests
|
||||
---
|
||||
```
|
||||
|
||||
**❌ Avoid:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: general-helper
|
||||
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
|
||||
|
||||
Define specific expertise areas rather than broad capabilities.
|
||||
|
||||
**✅ Good:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: react-performance-optimizer
|
||||
description: Optimizes React applications for performance using profiling and best practices
|
||||
---
|
||||
```
|
||||
|
||||
**❌ Avoid:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
---
|
||||
name: frontend-developer
|
||||
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
|
||||
|
||||
Write descriptions that clearly indicate when to use the agent.
|
||||
|
||||
**✅ Good:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
description: Reviews code for security vulnerabilities, performance issues, and maintainability concerns
|
||||
```
|
||||
|
||||
**❌ Avoid:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
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
|
||||
|
||||
#### System Prompt Guidelines
|
||||
|
||||
**Be Specific About Expertise:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
You are a Python testing specialist with expertise in:
|
||||
|
||||
|
||||
- pytest framework and fixtures
|
||||
- Mock objects and dependency injection
|
||||
- Test-driven development practices
|
||||
@@ -480,10 +389,9 @@ You are a Python testing specialist with expertise in:
|
||||
```
|
||||
|
||||
**Include Step-by-Step Approaches:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
For each testing task:
|
||||
|
||||
|
||||
1. Analyze the code structure and dependencies
|
||||
2. Identify key functionality and edge cases
|
||||
3. Create comprehensive test suites with clear naming
|
||||
@@ -492,10 +400,9 @@ For each testing task:
|
||||
```
|
||||
|
||||
**Specify Output Standards:**
|
||||
|
||||
```markdown
|
||||
```
|
||||
Always follow these standards:
|
||||
|
||||
|
||||
- Use descriptive test names that explain the scenario
|
||||
- Include both positive and negative test cases
|
||||
- Add docstrings for complex test functions
|
||||
@@ -503,10 +410,9 @@ Always follow these standards:
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Tool Restrictions**: Subagents only have access to their configured tools
|
||||
- **Tool Restrictions**: Sub Agents only have access to their configured tools
|
||||
- **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
|
||||
- **Sensitive Information**: Avoid including secrets or credentials in agent configurations
|
||||
- **Production Environments**: Consider separate agents for production vs development environments
|
||||
@@ -7,7 +7,7 @@
|
||||
Prerequisites:
|
||||
|
||||
- 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
|
||||
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]
|
||||
>
|
||||
> See [advanced setup](/setup) for installation options or [troubleshooting](/troubleshooting) if you hit issues.
|
||||
> See [troubleshooting](/troubleshooting) if you hit issues.
|
||||
|
||||
> [!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
|
||||
|
||||
@@ -71,58 +73,4 @@ 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.
|
||||
* **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"`.
|
||||
* **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>
|
||||
* **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"`.
|
||||
@@ -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
|
||||
|
||||
### Ask your first question
|
||||
@@ -238,17 +234,25 @@ review my changes and suggest improvements
|
||||
|
||||
Here are the most important commands for daily use:
|
||||
|
||||
| Command | What it does | Example |
|
||||
| ------------------- | --------------------------------- | ----------------------------------- |
|
||||
| `qwen` | Start interactive mode | `qwen` |
|
||||
| `qwen-code "task"` | Run a one-time task | `qwen-code "fix the build error"` |
|
||||
| `qwen-code -p "query"` | Run one-off query, then exit | `qwen-code -p "explain this function"` |
|
||||
| `qwen-code -c` | Continue most recent conversation | `qwen-code -c` |
|
||||
| `qwen-code -r` | Resume a previous conversation | `qwen-code -r` |
|
||||
| `qwen-code commit` | Create a Git commit | `qwen-code commit` |
|
||||
| `/clear` | Clear conversation history | `/clear` |
|
||||
| `/help` | Show available commands | `/help` |
|
||||
| `quit` or Ctrl+C | Exit Qwen Code | `/quit` |
|
||||
| Command | What it does | Example |
|
||||
| --------------------- | ------------------------------------------------------ | ---------------------------------- |
|
||||
| `qwen` | start Qwen Code | `qwen` |
|
||||
| `/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` |
|
||||
| `/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.
|
||||
|
||||
@@ -281,32 +285,8 @@ See the [CLI reference](/cli-reference) for a complete list of commands.
|
||||
- Press ↑ for command history
|
||||
- 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
|
||||
|
||||
- **In Qwen Code**: Type `/help` or ask "how do I..."
|
||||
- **Documentation**: You're here! Browse other guides
|
||||
- **Community**: Join our [GitHub Discussion](https://github.com/QwenLM/qwen-code/discussions) for tips and support
|
||||
- **Community**: Join our [GitHub Discussion](https://github.com/QwenLM/qwen-code/discussions) for tips and support
|
||||
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