@qodercn-ai/qoderclicn 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,480 @@
1
+ ---
2
+ name: hook-config
3
+ description:
4
+ Guide for creating and configuring hooks. Use when users want to add
5
+ automated behaviors triggered by tool execution, session lifecycle,
6
+ or other events in the Qoder CLI hook system.
7
+ allowed-tools: Edit, Write
8
+ ---
9
+
10
+ # Creating Hooks for Qoder CLI
11
+
12
+ This skill guides you through creating hooks — automated behaviors that
13
+ trigger on specific events like tool execution, session lifecycle, file
14
+ changes, and notifications. Hooks are configured in settings.json files.
15
+
16
+ ## When to Use Hooks
17
+
18
+ Use hooks when you need:
19
+
20
+ - **Automated side effects** after tool execution (format, lint, test)
21
+ - **Guardrails** before tool execution (block protected files, detect secrets)
22
+ - **Notifications** when events occur (desktop alerts, webhooks)
23
+ - **Validation gates** that block or allow operations based on conditions
24
+ - **Session automation** at start, end, or compaction
25
+
26
+ **When NOT to use hooks:**
27
+
28
+ - One-off tasks (just do them directly)
29
+ - Complex multi-step workflows (use agents or skills instead)
30
+ - Anything that needs user interaction mid-execution
31
+
32
+ ## Configuration Scopes
33
+
34
+ | Scope | File | Use Case |
35
+ | ----------- | ------------------------------------ | -------------------------------- |
36
+ | **Project** | `${QODER_CONFIG_DIR}/settings.json` | Team-shared, version controlled |
37
+ | **Local** | `${QODER_CONFIG_DIR}/settings.local.json` | Personal, not committed |
38
+ | **User** | `~/${QODER_CONFIG_DIR}/settings.json` | Global across all projects |
39
+
40
+ **Choose project** for team guardrails and standards.
41
+ **Choose local** for personal preferences and notifications.
42
+ **Choose user** for global behaviors across all projects.
43
+
44
+ ## Configuration Format
45
+
46
+ ```jsonc
47
+ {
48
+ "hooks": {
49
+ "<EventName>": [
50
+ {
51
+ "matcher": "<regex>",
52
+ "hooks": [
53
+ {
54
+ "type": "command",
55
+ "command": "${QODER_CONFIG_DIR}/hooks/my-hook.sh",
56
+ "name": "my-hook",
57
+ "timeout": 60
58
+ }
59
+ ]
60
+ }
61
+ ]
62
+ }
63
+ }
64
+ ```
65
+
66
+ Each event maps to an array of **hook definitions**. Each definition has:
67
+
68
+ | Field | Required | Description |
69
+ | ------------ | -------- | --------------------------------------------------- |
70
+ | `matcher` | No | Regex filter (matches tool name for tool events) |
71
+ | `hooks` | Yes | Array of hook handlers |
72
+ | `sequential` | No | Run hooks in order instead of parallel |
73
+ | `async` | No | Fire-and-forget, don't block the operation |
74
+
75
+ ### Hook Handler Fields
76
+
77
+ | Field | Required | Description |
78
+ | --------------- | ------------ | ----------------------------------------------------- |
79
+ | `type` | Yes | `command`, `http`, `prompt`, or `agent` |
80
+ | `command` | command type | Shell command to execute |
81
+ | `url` | http type | Webhook URL to POST to |
82
+ | `prompt` | prompt/agent | LLM prompt text |
83
+ | `if` | No | Per-hook condition: `"ToolName(glob)"` or `"ToolName"` |
84
+ | `name` | No | Display name |
85
+ | `description` | No | Human-readable description |
86
+ | `timeout` | No | Seconds before timeout |
87
+ | `statusMessage` | No | Text shown in UI during execution |
88
+ | `async` | No | Run in background without blocking |
89
+ | `asyncRewake` | No | Background hook; exit code 2 wakes model |
90
+
91
+ ## Hook Events
92
+
93
+ ### Tool Events (matcher = tool name regex)
94
+
95
+ | Event | When |
96
+ | -------------------- | ------------------------------- |
97
+ | `PreToolUse` | Before tool execution |
98
+ | `PostToolUse` | After successful tool execution |
99
+ | `PostToolUseFailure` | After tool execution fails |
100
+ | `PermissionRequest` | Tool requests user permission |
101
+
102
+ ### Session & Agent Lifecycle
103
+
104
+ | Event | When |
105
+ | --------------- | ------------------------------------ |
106
+ | `SessionStart` | Session initializes |
107
+ | `SessionEnd` | Session tears down |
108
+ | `SubagentStart` | Sub-agent session begins |
109
+ | `SubagentStop` | Sub-agent session ends |
110
+ | `Stop` | Agent decides to stop |
111
+ | `StopFailure` | Stop process fails (error, timeout) |
112
+ | `PreCompact` | Before context compaction |
113
+ | `PostCompact` | After context compaction |
114
+
115
+ ### User, Config & Notification Events
116
+
117
+ | Event | When |
118
+ | -------------------- | ------------------------------- |
119
+ | `UserPromptSubmit` | User submits a prompt |
120
+ | `ConfigChange` | Settings change at runtime |
121
+ | `Notification` | External notification arrives |
122
+ | `InstructionsLoaded` | System instructions loaded |
123
+
124
+ ### File & Workspace Events
125
+
126
+ | Event | When |
127
+ | ---------------- | -------------------------- |
128
+ | `CwdChanged` | Working directory changes |
129
+ | `FileChanged` | Watched file changes |
130
+ | `WorktreeCreate` | Git worktree created |
131
+ | `WorktreeRemove` | Git worktree removed |
132
+
133
+ ### Task Events
134
+
135
+ | Event | When |
136
+ | --------------- | ----------------------------- |
137
+ | `TaskCreated` | Background task created |
138
+ | `TaskCompleted` | Background task completes |
139
+
140
+ ## Handler Types
141
+
142
+ ### Command (`type: "command"`)
143
+
144
+ Executes a shell command. Hook input arrives as JSON on **stdin**.
145
+ Output is parsed from **stdout** as JSON.
146
+
147
+ **Exit code semantics:**
148
+
149
+ | Exit Code | Meaning |
150
+ | --------- | -------------------------------- |
151
+ | 0 | Success — parse stdout as JSON |
152
+ | 2 | Blocking deny — stderr is reason |
153
+ | Other | Non-blocking warning |
154
+
155
+ **Stdin** receives the full hook input as JSON (fields vary by event):
156
+
157
+ ```json
158
+ {
159
+ "session_id": "abc-123",
160
+ "cwd": "/path/to/project",
161
+ "hook_event_name": "PreToolUse",
162
+ "tool_name": "Edit",
163
+ "tool_input": { "file_path": "src/app.ts", "old_string": "...", "new_string": "..." }
164
+ }
165
+ ```
166
+
167
+ **Stdout** JSON output (all fields optional):
168
+
169
+ ```json
170
+ {
171
+ "decision": "allow",
172
+ "reason": "Checks passed",
173
+ "hookSpecificOutput": {
174
+ "additionalContext": "Message injected into conversation"
175
+ }
176
+ }
177
+ ```
178
+
179
+ Best for: scripts, linters, formatters, external CLI tools.
180
+
181
+ ### HTTP (`type: "http"`)
182
+
183
+ POSTs hook input as JSON to the URL. Response parsed as JSON hook
184
+ output. Headers support `${ENV_VAR}` interpolation.
185
+
186
+ ```jsonc
187
+ {
188
+ "type": "http",
189
+ "url": "https://api.example.com/hooks",
190
+ "headers": { "Authorization": "Bearer ${API_TOKEN}" }
191
+ }
192
+ ```
193
+
194
+ Best for: webhooks, external integrations, CI/CD triggers.
195
+
196
+ ### Prompt (`type: "prompt"`)
197
+
198
+ Single-turn LLM evaluation. The prompt plus hook input go to the model,
199
+ which returns a structured JSON decision.
200
+
201
+ ```jsonc
202
+ {
203
+ "type": "prompt",
204
+ "prompt": "Review this edit for security issues. Return {\"decision\": \"allow\"} or {\"decision\": \"deny\", \"reason\": \"...\"}"
205
+ }
206
+ ```
207
+
208
+ Best for: AI-powered review gates, semantic validation.
209
+
210
+ ### Agent (`type: "agent"`)
211
+
212
+ Spawns a sub-agent with tool access.
213
+
214
+ ```jsonc
215
+ {
216
+ "type": "agent",
217
+ "prompt": "Verify the edited file passes type checking. $ARGUMENTS",
218
+ "tools": ["Bash", "Read"],
219
+ "maxTurns": 10,
220
+ "timeout": 120
221
+ }
222
+ ```
223
+
224
+ Best for: complex verification needing tool use (run tests, read files,
225
+ check types).
226
+
227
+ ## The `if` Condition
228
+
229
+ Narrow when a hook fires within a matched definition:
230
+
231
+ ```jsonc
232
+ { "if": "Edit(*.ts)" } // Only Edit calls on .ts files
233
+ { "if": "Write(src/**)" } // Only Write calls under src/
234
+ { "if": "Bash" } // Any Bash call
235
+ ```
236
+
237
+ Format: `"ToolName(glob_pattern)"` or `"ToolName"`.
238
+ The glob matches the tool's primary argument (typically a file path).
239
+
240
+ ## Hook Creation Workflow
241
+
242
+ ### Step 1: Determine the Behavior
243
+
244
+ Understand what the user wants:
245
+
246
+ - What should happen automatically?
247
+ - When should it trigger? (before/after tool use, session event, etc.)
248
+ - Should it block operations or just observe?
249
+ - Who needs it? (team or personal)
250
+
251
+ **Avoid interrogation loops.** Propose a concrete hook config based on
252
+ initial understanding and ask the user to refine.
253
+
254
+ ### Step 2: Choose Event, Matcher, and Handler
255
+
256
+ Map the behavior:
257
+
258
+ | Behavior | Event | Matcher | Handler |
259
+ | ---------------------- | ------------- | -------------- | ------- |
260
+ | Auto-format after edits| `PostToolUse` | `Edit\|Write` | command |
261
+ | Block protected files | `PreToolUse` | `Edit\|Write` | command |
262
+ | Secret detection | `PreToolUse` | `Edit\|Write` | command |
263
+ | Desktop notifications | `Notification`| — | command |
264
+ | Run tests after changes| `PostToolUse` | `Edit\|Write` | command |
265
+ | AI code review gate | `PreToolUse` | `Edit` | prompt |
266
+ | Type-check verification| `PostToolUse` | `Edit\|Write` | agent |
267
+ | Webhook to CI/CD | `PostToolUse` | `Edit\|Write` | http |
268
+ | Dependency guard | `PreToolUse` | `Edit` | command |
269
+
270
+ ### Step 3: Choose Scope
271
+
272
+ - **Project** (`${QODER_CONFIG_DIR}/settings.json`): Team standards, check in
273
+ - **Local** (`${QODER_CONFIG_DIR}/settings.local.json`): Personal, not committed
274
+ - **User** (`~/${QODER_CONFIG_DIR}/settings.json`): Global, all projects
275
+
276
+ ### Step 4: Create the Configuration
277
+
278
+ 1. Read the target settings.json (if it exists)
279
+ 2. Merge the new hook into the existing `hooks` object
280
+ 3. Write back the file
281
+
282
+ If no hooks exist yet, create the full structure.
283
+
284
+ ### Step 5: Create Script Files (command type)
285
+
286
+ For command hooks with non-trivial logic, create scripts in
287
+ `${QODER_CONFIG_DIR}/hooks/`:
288
+
289
+ ```bash
290
+ mkdir -p ${QODER_CONFIG_DIR}/hooks
291
+ ```
292
+
293
+ Script requirements:
294
+ - Read JSON from stdin
295
+ - Write JSON to stdout (or nothing for simple success)
296
+ - Exit 0 for success, 2 for blocking deny, other for warning
297
+ - Use stderr for error messages and debug output
298
+ - Make executable: `chmod +x ${QODER_CONFIG_DIR}/hooks/my-hook.sh`
299
+
300
+ Test independently:
301
+
302
+ ```bash
303
+ echo '{"tool_name":"Edit","tool_input":{"file_path":"test.ts"}}' | \
304
+ ${QODER_CONFIG_DIR}/hooks/my-hook.sh
305
+ ```
306
+
307
+ ### Step 6: Verify
308
+
309
+ Tell the user to verify:
310
+
311
+ 1. Restart the session or trigger the relevant event
312
+ 2. Check the hook fires and produces expected output
313
+ 3. Test the blocking path (for PreToolUse guards)
314
+ 4. Confirm `async` hooks don't block the session
315
+
316
+ ## Best Practices
317
+
318
+ 1. **Keep hooks fast** — Target <5s for synchronous hooks
319
+ 2. **Test scripts independently** — Pipe sample JSON stdin, verify output
320
+ 3. **Use `async: true`** for non-blocking side effects (notifications, logging)
321
+ 4. **Scope matchers narrowly** — Don't fire on every tool invocation
322
+ 5. **Prefer `if` conditions** for file-type filtering
323
+ 6. **Log to stderr** — stdout is parsed as JSON; debug output goes to stderr
324
+ 7. **Handle edge cases** — Exit 0 if the condition doesn't apply
325
+ 8. **Use `statusMessage`** for meaningful UI feedback during execution
326
+
327
+ ## Anti-Patterns to Avoid
328
+
329
+ - **Overly broad matchers** — `".*"` on PreToolUse fires on every single tool call
330
+ - **Long synchronous hooks** — Block the entire interactive session
331
+ - **Stdout pollution** — Non-JSON stdout causes parse errors
332
+ - **Missing shebang** — Scripts without `#!/bin/bash` may fail silently
333
+
334
+ ## Examples
335
+
336
+ ### Auto-Format TypeScript
337
+
338
+ Runs Prettier on TypeScript files after every Edit or Write.
339
+
340
+ **`${QODER_CONFIG_DIR}/settings.json`:**
341
+
342
+ ```jsonc
343
+ {
344
+ "hooks": {
345
+ "PostToolUse": [{
346
+ "matcher": "Edit|Write",
347
+ "hooks": [{
348
+ "type": "command",
349
+ "command": "${QODER_CONFIG_DIR}/hooks/auto-format.sh",
350
+ "if": "Edit(*.{ts,tsx,js,jsx})",
351
+ "name": "auto-format",
352
+ "statusMessage": "Formatting..."
353
+ }]
354
+ }]
355
+ }
356
+ }
357
+ ```
358
+
359
+ **`${QODER_CONFIG_DIR}/hooks/auto-format.sh`:**
360
+
361
+ ```bash
362
+ #!/bin/bash
363
+ INPUT=$(cat)
364
+ FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
365
+ [ -z "$FILE" ] && exit 0
366
+ [ -f "$FILE" ] || exit 0
367
+ npx prettier --write "$FILE" >/dev/null 2>&1
368
+ exit 0
369
+ ```
370
+
371
+ ### Protected File Guard
372
+
373
+ Blocks edits to lock files and CI configuration.
374
+
375
+ **`${QODER_CONFIG_DIR}/settings.json`:**
376
+
377
+ ```jsonc
378
+ {
379
+ "hooks": {
380
+ "PreToolUse": [{
381
+ "matcher": "Edit|Write",
382
+ "hooks": [{
383
+ "type": "command",
384
+ "command": "${QODER_CONFIG_DIR}/hooks/protected-files.sh",
385
+ "name": "protected-file-guard",
386
+ "statusMessage": "Checking file permissions..."
387
+ }]
388
+ }]
389
+ }
390
+ }
391
+ ```
392
+
393
+ **`${QODER_CONFIG_DIR}/hooks/protected-files.sh`:**
394
+
395
+ ```bash
396
+ #!/bin/bash
397
+ INPUT=$(cat)
398
+ FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
399
+ [ -z "$FILE" ] && exit 0
400
+
401
+ PROTECTED_PATTERNS=(
402
+ "package-lock.json"
403
+ "yarn.lock"
404
+ "pnpm-lock.yaml"
405
+ ".github/workflows/*"
406
+ ".gitlab-ci.yml"
407
+ )
408
+
409
+ for PATTERN in "${PROTECTED_PATTERNS[@]}"; do
410
+ if [[ "$FILE" == $PATTERN ]]; then
411
+ echo "Blocked: $FILE is a protected file" >&2
412
+ exit 2
413
+ fi
414
+ done
415
+
416
+ exit 0
417
+ ```
418
+
419
+ ### Desktop Notification
420
+
421
+ Sends a macOS notification when Qoder CLI needs attention.
422
+
423
+ **`${QODER_CONFIG_DIR}/settings.local.json`:**
424
+
425
+ ```jsonc
426
+ {
427
+ "hooks": {
428
+ "Notification": [{
429
+ "hooks": [{
430
+ "type": "command",
431
+ "command": "${QODER_CONFIG_DIR}/hooks/notify.sh",
432
+ "name": "desktop-notify",
433
+ "async": true
434
+ }]
435
+ }]
436
+ }
437
+ }
438
+ ```
439
+
440
+ **`${QODER_CONFIG_DIR}/hooks/notify.sh`:**
441
+
442
+ ```bash
443
+ #!/bin/bash
444
+ INPUT=$(cat)
445
+ TITLE=$(echo "$INPUT" | jq -r '.title // "Qoder CLI"')
446
+ MSG=$(echo "$INPUT" | jq -r '.message // "Notification"')
447
+
448
+ if command -v osascript &>/dev/null; then
449
+ osascript -e "display notification \"$MSG\" with title \"$TITLE\""
450
+ elif command -v notify-send &>/dev/null; then
451
+ notify-send "$TITLE" "$MSG"
452
+ fi
453
+ exit 0
454
+ ```
455
+
456
+ ### Type-Check Gate
457
+
458
+ Uses an agent to verify TypeScript compiles after edits.
459
+
460
+ **`${QODER_CONFIG_DIR}/settings.json`:**
461
+
462
+ ```jsonc
463
+ {
464
+ "hooks": {
465
+ "PostToolUse": [{
466
+ "matcher": "Edit|Write",
467
+ "hooks": [{
468
+ "type": "agent",
469
+ "prompt": "Run `npx tsc --noEmit` and check for type errors in the edited file. If there are errors, report them. $ARGUMENTS",
470
+ "tools": ["Bash", "Read"],
471
+ "if": "Edit(*.{ts,tsx})",
472
+ "name": "type-check",
473
+ "statusMessage": "Type checking...",
474
+ "maxTurns": 5,
475
+ "timeout": 60
476
+ }]
477
+ }]
478
+ }
479
+ }
480
+ ```
@@ -0,0 +1,155 @@
1
+ ---
2
+ name: mcp-config
3
+ description: Interactively add, update, or remove MCP (Model Context Protocol) servers in QoderCLI config files. Use this skill whenever the user pastes an MCP server config snippet, asks to "add an MCP", "配置 MCP", "install this MCP server", "register an MCP", wants to move an MCP between project/user/local scope, or asks why a newly pasted MCP isn't showing up. Handles stdio, http, sse, and ws transports, merges safely into the right target file (`<repo>/.qoder/settings.json`, `~/.qoder/settings.json`, or `<repo>/.qoder/settings.local.json`), and tells the user exactly how to reload so the server actually connects.
4
+ allowed-tools: Bash, Edit, Read, Write
5
+ ---
6
+
7
+ # MCP Config Helper (QoderCLI)
8
+
9
+ Help the user land an MCP server config into the right QoderCLI config file, merge it cleanly with what's already there, and reload it so it actually takes effect.
10
+
11
+ ## When this skill fires
12
+
13
+ Typical user inputs:
14
+
15
+ - Pastes a JSON blob that looks like an MCP server definition (has `command`, `args`, or `url` + `type`)
16
+ - "帮我把这个 MCP 加到项目里"
17
+ - "Add this MCP server to user scope"
18
+ - "Why isn't my new MCP showing up in `/mcp`?"
19
+ - "Move the filesystem MCP from project to user scope"
20
+ - "Remove the old foo MCP"
21
+
22
+ If the user's request doesn't involve MCP server registration, don't invoke this skill.
23
+
24
+ ## Prefer the built-in CLI when possible
25
+
26
+ QoderCLI ships first-class commands for MCP CRUD:
27
+
28
+ - `qodercli mcp add <name> <commandOrUrl> [args...] --scope <user|local|project> --transport <stdio|sse|http|ws>`
29
+ - `qodercli mcp add-json <name> <json> --scope <user|local|project>` — ideal when the user pasted a full server body, just wrap it and pass through.
30
+ - `qodercli mcp list`, `qodercli mcp get <name>`, `qodercli mcp remove <name> --scope ...`
31
+
32
+ If the user's ask maps cleanly onto one of these, run the command via Bash instead of hand-editing JSON — the CLI handles collision detection, OAuth setup, scope validation, and writes to the right file. Fall back to direct file editing only when: (a) the user is doing a cross-scope move (read from one, write to another), (b) the user wants a surgical edit to an env var or header on an existing entry, or (c) the CLI rejects the input and you need to diagnose why.
33
+
34
+ ## What the user pastes
35
+
36
+ MCP configs come in several shapes. Normalize them before writing. Common inputs:
37
+
38
+ **Full server block (most common — from docs/README):**
39
+ ```json
40
+ {
41
+ "mcpServers": {
42
+ "filesystem": {
43
+ "command": "npx",
44
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"]
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ **Single server entry (name + body):**
51
+ ```json
52
+ "filesystem": {
53
+ "command": "npx",
54
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"]
55
+ }
56
+ ```
57
+
58
+ **Just the body (user will supply the name):**
59
+ ```json
60
+ { "command": "npx", "args": ["-y", "..."] }
61
+ ```
62
+
63
+ **HTTP / SSE transport:**
64
+ ```json
65
+ {
66
+ "type": "http",
67
+ "url": "https://example.com/mcp",
68
+ "headers": { "Authorization": "Bearer ..." }
69
+ }
70
+ ```
71
+
72
+ If the name is missing from the snippet, ask the user what to call the server. Don't invent one.
73
+
74
+ ## Target files (scopes)
75
+
76
+ QoderCLI supports three MCP scopes. Pick the right file — the difference matters:
77
+
78
+ | Scope | File | `mcpServers` lives at | When to use |
79
+ | --------- | ------------------------------------------ | ------------------------------ | --------------------------------------------------------------------- |
80
+ | `project` | `<repo>/.qoder/settings.json` | top-level `mcpServers` | Shared with the team via git. Use for project-wide, committed config. |
81
+ | `user` | `~/.qoder/settings.json` | top-level `mcpServers` | Available across all projects for this user. Use for personal tools. |
82
+ | `local` | `<repo>/.qoder/settings.local.json` | top-level `mcpServers` | Project-specific, user-only, **gitignored**. This is the CLI default. |
83
+
84
+ **Do NOT write to any of these — they are wrong targets that look plausible but the CLI does not read:**
85
+ - `<repo>/.mcp.json` or `~/.mcp.json` (Claude Code convention, not QoderCLI)
86
+ - `~/.qoder/mcp.json` (no such file — user MCPs go inside `~/.qoder/settings.json` under `mcpServers`)
87
+ - `~/Library/Application Support/Qoder/User/mcp.json` or any VS Code extension path
88
+ - `~/.claude.json` or `~/.claude/settings.json` (those are Claude Code, not QoderCLI)
89
+
90
+ The only three valid targets are the three rows in the table above. If you find yourself about to write somewhere else, stop.
91
+
92
+ **Scope selection — don't default silently.** If the user hasn't specified a scope, ask before writing. A one-liner is enough: "Add this to **project** (`<repo>/.qoder/settings.json`, committed), **user** (`~/.qoder/settings.json`, global), or **local** (`<repo>/.qoder/settings.local.json`, gitignored)?"
93
+
94
+ Don't guess "probably local scope just because it's the CLI default" — the difference between project (checked into git, teammates see it) and user/local (personal) is significant, and picking wrong can leak secrets or clutter a teammate's config. Users routinely paste MCP configs from docs that don't mention scope; they need the prompt.
95
+
96
+ Exception: proceed without asking only when phrasing makes it genuinely unambiguous — "add to this project", "push this to the team", "only for me globally", "just for this repo". Vague signals like "装一下" / "加进去" do not qualify.
97
+
98
+ ## Workflow
99
+
100
+ 1. **Parse the pasted config.** Extract: server name, transport (`stdio` if `command` present, else `http`/`sse`/`ws` based on `type`/`url`), and the server body. Normalize so the write step only deals with a clean `(name, body)` pair.
101
+
102
+ 2. **Confirm scope** if not obvious from the user's message (see table above).
103
+
104
+ 3. **Decide: CLI or direct edit?** For a plain add with a clean body, `qodercli mcp add-json <name> '<json>' --scope <scope>` is the shortest path and handles collision errors for you. For cross-scope moves, surgical field edits, or removals from multiple scopes at once, go direct.
105
+
106
+ 4. **If direct-editing, read the target file.** Use the Read tool. If the file doesn't exist, plan to create it with `{ "mcpServers": { ... } }`. If it exists, add/update a top-level `mcpServers` key and preserve every other setting already in the file.
107
+
108
+ 5. **Detect collisions — but don't be precious.** Two sub-cases:
109
+ - **User explicitly asked to update/replace/move an existing entry** (e.g. "把 filesystem 路径改成...", "update the github token", "replace example-api"): just do it. Don't ask for reconfirmation. A one-line "found existing filesystem at /old/path → updating to /new/path" is plenty; the user already decided.
110
+ - **User pasted a new config that happens to collide** (no mention of the existing entry, likely unaware it's there): stop and show them the existing entry vs. the new one, ask replace/rename/cancel. Silent overwrite here loses hand-edited fields (env vars, auth headers) and surprises the user.
111
+
112
+ The distinguishing signal: did the user's wording acknowledge that the server already exists? If yes, proceed. If no and there's a collision, surface it. Note that `qodercli mcp add`/`add-json` *refuses* to overwrite by default — if the user wants a replace, either remove-then-add via CLI, or fall back to a direct Edit.
113
+
114
+ 6. **Merge and write.** For direct edits, use the Edit tool for surgical changes when the file exists (especially `~/.qoder/settings.json`, which holds unrelated settings and shouldn't be rewritten wholesale). Only rewrite the whole file with Write when creating it fresh. Preserve formatting — match the existing indentation.
115
+
116
+ 7. **Validate.** After writing, read the relevant slice back and confirm the JSON parses and the server is present. All three targets are real settings files — a corrupted write breaks settings on the next start, so validation isn't optional.
117
+
118
+ 8. **Tell the user how to reload.** See below.
119
+
120
+ ## Reload instructions
121
+
122
+ MCP servers are loaded at startup and on explicit reconnect. After editing config, the user must reload. Tell them the shortest path:
123
+
124
+ - **Added or changed a server (running session)**: run `/mcp reload` inside QoderCLI — it restarts all MCP clients and refreshes the tool surface. This is the one you want 95% of the time.
125
+ - **Inspect what's loaded**: `/mcp` lists current servers and their status.
126
+ - **Project-scope first-time add**: QoderCLI prompts for approval before running project-level MCP servers (this is enforced via the project-MCP approval flow). The user will see a trust prompt the first time `/mcp reload` picks up the new entry — mention this so they're not surprised.
127
+ - **Removed a server**: `/mcp reload` drops the connection. If you only removed it from one of multiple scopes, it may still show up from another — `qodercli mcp list` confirms where it still lives.
128
+
129
+ Keep the reload instruction to one or two sentences — don't lecture.
130
+
131
+ ## Gotchas worth flagging
132
+
133
+ - **Env vars with secrets**: if the pasted config has `"env": { "API_KEY": "sk-..." }` with a real-looking secret, flag it: "This config has what looks like a real API key — do you want to move it to an env var reference or keep it inline?" Don't refuse; just surface the choice.
134
+ - **Settings files hold unrelated keys**: all three targets also store user preferences, keybinding toggles, auth hints, etc. Never rewrite a settings file whole — Edit the specific `mcpServers` slice.
135
+ - **Shared `.qoder` directory name**: user settings live in `~/.qoder/settings.json`; project shared settings in `<repo>/.qoder/settings.json`; project-local (gitignored) in `<repo>/.qoder/settings.local.json`. Keep the scope clear before writing.
136
+ - **Relative paths**: stdio `command`/`args` often reference local scripts. If the user pastes `./server.js`, ask whether they want it resolved to an absolute path — relative paths break when the CLI starts from a different cwd.
137
+ - **Project-scope is committed**: `<repo>/.qoder/settings.json` ends up in git. Remind the user not to include secrets there — for secret-bearing configs prefer `user` or `local`.
138
+ - **Plugin-provided MCPs**: servers whose names start with `mcp__plugin_` come from installed extensions, not user config. Don't try to edit them via this skill — point the user to the extension's own config.
139
+
140
+ ## Output style
141
+
142
+ Length should match what's actually at stake — not a fixed rule.
143
+
144
+ **Default (simple add, no concerns):** one or two sentences. What was written where, how to reload. The user pasted config and wants it landed.
145
+
146
+ > Added `filesystem` (stdio) to `~/.qoder/settings.json` (user scope). Run `/mcp reload` to pick it up.
147
+
148
+ **When there's something worth flagging, don't suppress it to stay terse.** Brief matters less than "the user understood what just happened and what to do next." Specifically, add a short follow-up paragraph (2-4 sentences) when:
149
+
150
+ - **The pasted config contained a real-looking secret** (Bearer token, API key, password). Tell them it's now sitting in plaintext in the config file, that project-scope `<repo>/.qoder/settings.json` is committed to git and `~/.qoder/settings.json` is often synced via dotfiles, and offer to switch to env-var reference or rotation if exposed. Don't assume they've thought this through — many people paste from copy-paste without realizing.
151
+ - **The operation has a non-obvious side effect** the user probably didn't anticipate. E.g., for `@modelcontextprotocol/server-filesystem`, changing the path replaces — it doesn't merge, so the old dir loses access. Mention it in one line.
152
+ - **The collision was silent** (user didn't mention the existing entry). Surface what was there before the change.
153
+ - **Scope crossed trust boundary** (e.g. moved from `local` → `project`). Remind them it's now committed and teammates will pick it up on next pull.
154
+
155
+ Don't pad. Don't add headers (`## 生效方式`, `## 安全提醒`) for a 2-sentence response — just write the sentences. Headers only earn their keep when the response is long enough that scanning matters.