@codewizard-dt/bootstrap 2.14.0 → 2.17.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.
Files changed (40) hide show
  1. package/lib/hooks/README.md +639 -142
  2. package/lib/hooks/absolute-path-guard.js +142 -0
  3. package/lib/hooks/claude-settings-guard.js +200 -0
  4. package/lib/hooks/env-content-read-guard.js +367 -0
  5. package/lib/hooks/git-protected-ops-block.js +12 -7
  6. package/lib/hooks/interpreter-indirection-guard.js +576 -0
  7. package/lib/hooks/lib/command-parse.js +63 -0
  8. package/lib/hooks/package-install-consent.js +151 -0
  9. package/lib/hooks/protected-write-guard.js +237 -0
  10. package/lib/scripts/README.md +73 -8
  11. package/lib/scripts/build-mcp-guide.sh +9 -1
  12. package/lib/scripts/install-global.sh +62 -11
  13. package/lib/scripts/install-mcps.sh +140 -36
  14. package/lib/scripts/lib.sh +24 -15
  15. package/lib/scripts/merge-gitignore.sh +221 -33
  16. package/lib/scripts/merge-settings-deny.js +112 -39
  17. package/lib/scripts/merge-settings-hooks.js +374 -0
  18. package/lib/scripts/templates/file-suggestion.sh +142 -0
  19. package/lib/scripts/templates/gitignore +8 -0
  20. package/lib/scripts/templates/guides/stubs/playwright.md +2 -0
  21. package/lib/scripts/templates/settings-deny.json +81 -1
  22. package/lib/scripts/templates/settings-hooks.json +151 -0
  23. package/lib/skills/debug-logs/SKILL.md +1 -1
  24. package/lib/skills/git-commit/SKILL.md +8 -0
  25. package/package.json +5 -2
  26. package/raw/research/brave-mcp-single-docker-container/index.md +0 -94
  27. package/raw/research/brave-mcp-single-docker-container/sources.md +0 -70
  28. package/raw/research/dark-mode-theme/index.md +0 -85
  29. package/raw/research/dark-mode-theme/sources.md +0 -49
  30. package/raw/research/mcp-add-scope-writes/index.md +0 -46
  31. package/raw/research/mcp-add-scope-writes/sources.md +0 -38
  32. package/raw/research/mcp-one-process-per-user/index.md +0 -75
  33. package/raw/research/mcp-one-process-per-user/sources.md +0 -66
  34. package/raw/research/mcp-scope-conflict-handling/index.md +0 -61
  35. package/raw/research/mcp-scope-conflict-handling/sources.md +0 -32
  36. package/raw/research/serena-mcp-disconnect/index.md +0 -81
  37. package/raw/research/serena-mcp-disconnect/sources.md +0 -87
  38. package/raw/research/wiki-tooling-improvements/index.md +0 -126
  39. package/raw/research/wiki-tooling-improvements/sources.md +0 -73
  40. package/raw/software-factory-case-study.pdf +0 -0
@@ -1,85 +0,0 @@
1
- ---
2
- topic: plan to implement a dark mode theme
3
- slug: dark-mode-theme
4
- researched: 2026-07-06
5
- sources: [./sources.md]
6
- ---
7
-
8
- # Research: Dark Mode Theme for the Wiki Dashboard
9
-
10
- > `TASK-002-wiki-dashboard-client.md` requires light/dark theming for `dashboard.html` via `@media (prefers-color-scheme: dark)` "at minimum," but no concrete palette, CSS-variable structure, or toggle mechanism exists anywhere in this repo. Recommendation: implement a full explicit-override toggle (`localStorage` > OS `prefers-color-scheme` > default), backed by a dark palette derived from the existing `raw/house-style` light tokens, following the CSS-custom-property + `data-theme` attribute pattern that is the 2025 industry-converged approach for self-contained static pages.
11
-
12
- ## Research Questions
13
-
14
- - Does this repo have any existing dark-mode/theme convention `dashboard.html` should follow?
15
- - What does the wiki-dashboard roadmap (ROADMAP-002) and its sibling tasks (TASK-001/003/004/005) say about theming?
16
- - What is current (2025) best practice for implementing a light/dark toggle in a dependency-free vanilla HTML/CSS/JS file?
17
- - What palette should the dark theme use, given `raw/house-style` is light-mode only?
18
- - How does theming interact with `dashboard.html`'s live-polling render loop?
19
-
20
- ## Current State (Codebase)
21
-
22
- - `wiki/work/tasks/TASK-002-wiki-dashboard-client.md` (lines 27, 36) is the only place in the repo that mentions theming: "Theme: support light/dark via `prefers-color-scheme` media query at minimum" — stated as a floor, not a full spec.
23
- - `wiki/work/tasks/TASK-001-wiki-dashboard-server.md`, `TASK-003-wiki-dashboard-cli-wiring.md`, `TASK-004-wiki-dashboard-sync-scaffold.md`, `TASK-005-wiki-dashboard-docs.md`, and the parent `ROADMAP-002` file contain zero mentions of "dark," "theme," "light mode," `prefers-color-scheme`, CSS variables, or a toggle. They cover the static server, CLI wiring, scaffold distribution, and docs respectively — none touch `dashboard.html`'s markup/CSS/JS content, which is entirely TASK-002's scope.
24
- - `raw/house-style/tokens/tokens.json` (the repo's design-token source of truth) defines only light-mode colors: `canvas #f6f7f9`, `surface #f1f2f4`, `card #ffffff`, `ink #0b0b0d`, `ink-2 #33353b`, `muted #6b6e76`, `muted-2 #9a9da5`, `line #e7e8ea`, `accent #4f5a78`, plus status accents (`red #e5484d`, `green #30a46c`, `blue #3b6ef6`, `amber #e0901a`, `violet #8b5cf6`). No dark variants exist.
25
- - `raw/house-style/preview/src/index.css` confirms there is no dark-mode handling anywhere in the house-style preview — no `prefers-color-scheme`, no `data-theme`.
26
- - `dashboard.html` itself does not exist yet; TASK-002 (status: `todo`) is what will create `lib/scripts/templates/wiki/dashboard.html`, and it plans a 5-second polling loop (`renderFamily()` / `setInterval`) that re-renders all six family panels — any theme toggle must live outside that regenerated DOM subtree.
27
- - The nearest usable structural reference on this machine (outside this repo) is `~/.claude/plugins/marketplaces/claude-plugins-official/plugins/project-artifact/skills/project-artifact/template.html`, which implements `:root` custom properties + `@media (prefers-color-scheme: dark)` overrides (no manual toggle) — the right shape to extend, but missing the explicit-override layer.
28
-
29
- ## Key Findings
30
-
31
- - No dark-mode precedent or convention exists anywhere in `bootstrap-claude` to reuse — this had to be designed fresh. [S1][S2][S3]
32
- - `dashboard.html` is a plain static file served by TASK-001's Node server and opened directly in a browser; it is **not** a Claude Artifact, so the Artifact tool's "host stamps `data-theme`" behavior does not apply — the toggle logic must be fully self-contained in the file itself. *(inference from Artifact tool documentation — no primary source file)*
33
- - 2025 best-practice consensus across multiple independent sources is a **tri-state cascade**: explicit `localStorage` choice > OS `prefers-color-scheme` > default, resolved via an inline script that runs before first paint to avoid a flash of the wrong theme (FOUC/FOWT). [S4][S5][S6]
34
- - CSS structure: define color tokens as custom properties in `:root` (light defaults) and override them in `@media (prefers-color-scheme: dark)` as a passive fallback; then define `:root[data-theme="light"]` / `:root[data-theme="dark"]` blocks after the media query so an explicit attribute always wins at equal specificity. [S6][S7]
35
- - Accessibility/UX details repeatedly emphasized: avoid pure-black backgrounds (use ~`#17181c`–`#1c1d21`); add `<meta name="color-scheme" content="light dark">` so native scrollbars/form controls theme correctly; give the toggle a real `aria-label`; respect `prefers-reduced-motion` for any color-transition animation. [S5][S8]
36
- - `localStorage` reads/writes should be wrapped in `try/catch` since they can throw in locked-down or private-browsing contexts — theming should degrade gracefully to media-query-only rather than break the page. *(inference — no single primary source states this explicitly, but it follows from standard defensive JS practice)*
37
-
38
- ## Constraints
39
-
40
- - No build step and no external dependencies — `dashboard.html` must remain a single self-contained file (per TASK-002's stated constraint), so no CSS/theming library or framework can be introduced.
41
- - Must not regress the existing 5-second polling/re-render loop; the toggle button and its listener must survive every re-render cycle.
42
- - Must derive from `raw/house-style` tokens where possible for light-mode consistency with the rest of the ecosystem, even though house-style has no dark equivalents to copy directly.
43
-
44
- ## Recommendation
45
-
46
- **Recommended approach: full explicit-override toggle**, not a bare media query.
47
-
48
- **Palette** (dark values derived from the existing light `tokens.json`, keeping hue relationships, lightening saturated accents ~10–15% for contrast on dark backgrounds, avoiding pure black):
49
-
50
- | Token | Light (existing, from `tokens.json`) | Dark (new) |
51
- |---|---|---|
52
- | `--bg` | `#f6f7f9` | `#16171a` |
53
- | `--surface` | `#f1f2f4` | `#1c1d21` |
54
- | `--card` | `#ffffff` | `#202127` |
55
- | `--text` | `#0b0b0d` | `#e8e9ec` |
56
- | `--text-2` | `#33353b` | `#c3c5cb` |
57
- | `--muted` | `#6b6e76` | `#9a9da5` |
58
- | `--border` | `#e7e8ea` | `#303238` |
59
- | `--accent` | `#4f5a78` | `#8891ab` |
60
- | `--red` | `#e5484d` | `#ff6b70` |
61
- | `--green` | `#30a46c` | `#3ddc91` |
62
- | `--blue` | `#3b6ef6` | `#6e93ff` |
63
- | `--amber` | `#e0901a` | `#f0a83a` |
64
- | `--violet` | `#8b5cf6` | `#a78bfa` |
65
-
66
- **Implementation outline** (for TASK-002 steps 1 and 3):
67
-
68
- 1. `:root { --bg: #f6f7f9; ... }` (light defaults) + `@media (prefers-color-scheme: dark) { :root { --bg: #16171a; ... } }` as the passive fallback.
69
- 2. `:root[data-theme="light"] { ... }` / `:root[data-theme="dark"] { ... }` blocks placed *after* the media query in source order, so an explicit attribute wins over the media query.
70
- 3. An inline `<script>` near the top of `<body>`, run synchronously before the rest of the page paints: read `localStorage.getItem('dashboard-theme')`; if present, set `document.documentElement.setAttribute('data-theme', saved)` immediately. If absent, leave the attribute unset (media query governs) and attach a `matchMedia('(prefers-color-scheme: dark)')` change listener so a live OS flip is reflected while no explicit choice exists.
71
- 4. A toggle `<button aria-label="Switch color theme">` in the static header: on click, compute the currently-resolved theme, flip it, `setAttribute('data-theme', next)` + `localStorage.setItem('dashboard-theme', next)`.
72
- 5. `<meta name="color-scheme" content="light dark">` in `<head>`.
73
- 6. Wrap any theme-swap transition in `@media (prefers-reduced-motion: no-preference)`.
74
-
75
- **Risks and mitigations:**
76
- - Polling loop could wipe the toggle button if rendering is scoped too broadly → keep `renderFamily()`/panel rendering confined to a container below the static header.
77
- - `localStorage` can throw in private/locked-down browsing → wrap in `try/catch`, degrade to media-query-only.
78
- - Dark palette values above are a starting point, not contrast-checked — verify WCAG AA (4.5:1 body text) once real markup exists.
79
-
80
- **Alternative if constraints change**: if a future requirement demands matching an exact design tool's dark palette (e.g. a rebuilt house-style with real dark tokens), swap only the palette table above — the CSS-variable/`data-theme` structure does not need to change.
81
-
82
- ## Next Steps
83
-
84
- - Implementation: this is guidance for existing `TASK-002` (`wiki/work/tasks/TASK-002-wiki-dashboard-client.md`) — no new task needed. Consider amending TASK-002 steps 1 & 3 with the palette table and toggle structure above so the implementer doesn't re-derive it.
85
- - To ingest into the knowledge base: `/wiki-ingest raw/research/dark-mode-theme/index.md`
@@ -1,49 +0,0 @@
1
- ---
2
- topic: plan to implement a dark mode theme
3
- slug: dark-mode-theme
4
- researched: 2026-07-06
5
- ---
6
-
7
- # Primary Sources — Dark Mode Theme for the Wiki Dashboard
8
-
9
- | ID | Type | Locator | Accessed | What it contributed |
10
- |----|------|---------|----------|---------------------|
11
- | S1 | codebase | `wiki/work/tasks/TASK-002-wiki-dashboard-client.md` (lines 27, 36) | 2026-07-06 | The only theming requirement in the repo: "support light/dark via `prefers-color-scheme` media query at minimum" |
12
- | S2 | codebase | `wiki/work/tasks/TASK-001-wiki-dashboard-server.md`, `TASK-003-wiki-dashboard-cli-wiring.md`, `TASK-004-wiki-dashboard-sync-scaffold.md`, `TASK-005-wiki-dashboard-docs.md`, `wiki/work/roadmaps/` (ROADMAP-002) | 2026-07-06 | Confirmed zero mentions of dark mode/theming anywhere else in the roadmap or sibling tasks; established that TASK-002 is the sole owner of `dashboard.html` content |
13
- | S3 | codebase | `raw/house-style/tokens/tokens.json` | 2026-07-06 | The repo's only color-token source of truth; confirmed light-mode-only (no dark values, no `data-theme` reference) — basis for deriving the dark palette |
14
- | S4 | web | https://whitep4nth3r.com/blog/best-light-dark-mode-theme-toggle-javascript/ | 2026-07-06 | Tri-state "preference cascade" pattern: `localStorage` choice, falling back to `matchMedia('(prefers-color-scheme: dark)')`, falling back to a default |
15
- | S5 | web | https://blog.openreplay.com/build-dark-mode-toggle-css-js/ | 2026-07-06 | `<meta name="color-scheme" content="light dark">` for native control theming; `data-theme` on `<html>`; script-before-paint to prevent flash; accessible toggle button with `aria-label` |
16
- | S6 | web | https://www.magicpatterns.com/blog/implementing-dark-mode | 2026-07-06 | `:root[data-theme="dark"]` custom-property override pattern so consuming component CSS never needs to change per theme |
17
- | S7 | web | https://medium.com/@cerutti.alexander/a-mostly-complete-guide-to-theme-switching-in-css-and-js-c4992d5fd357 | 2026-07-06 | Confirms `@media (prefers-color-scheme)` + `[data-theme]` attribute can coexist, covering all four system/setting combinations; explains why the attribute override must come after the media query in source order |
18
- | S8 | web | https://www.srfdeveloper.com/2025/08/css-javascript-dark-mode-toggle.html | 2026-07-06 | "A user's explicit choice (clicking our toggle) should always win" over OS preference; avoid pure-black dark backgrounds |
19
- | S9 | codebase | `~/.claude/plugins/marketplaces/claude-plugins-official/plugins/project-artifact/skills/project-artifact/template.html` | 2026-07-06 | Reference implementation of `:root` custom properties + `@media (prefers-color-scheme: dark)` override (no manual toggle) — structural starting point |
20
-
21
- ## Excerpts
22
-
23
- ### S1 — TASK-002-wiki-dashboard-client.md
24
- `wiki/work/tasks/TASK-002-wiki-dashboard-client.md`
25
- > Theme: support light/dark via `prefers-color-scheme` media query at minimum (this repo's Artifact convention favors theme-awareness; apply the same care here since it's a long-running local tool a developer will have open).
26
-
27
- ### S3 — tokens.json
28
- `raw/house-style/tokens/tokens.json`
29
- > "color": { "canvas": "#f6f7f9", "surface": "#f1f2f4", "paper": "#ffffff", "card": "#ffffff", "ink": "#0b0b0d", "ink-2": "#33353b", "muted": "#6b6e76", "muted-2": "#9a9da5", "line": "#e7e8ea", "line-2": "#f0f1f3", "accent": "#4f5a78", "accent-red": "#e5484d", "accent-green": "#30a46c", "accent-blue": "#3b6ef6", "accent-amber": "#e0901a", "accent-violet": "#8b5cf6", "accent-rose": "#f43f5e" }
30
-
31
- ### S4 — whitep4nth3r.com
32
- https://whitep4nth3r.com/blog/best-light-dark-mode-theme-toggle-javascript/
33
- > If there's no stored theme preference in localStorage, we'll detect the user's system settings using the window.matchMedia() method by passing in a media query string... const systemSettingDark = window.matchMedia("(prefers-color-scheme: dark)");
34
-
35
- ### S5 — openreplay.com
36
- https://blog.openreplay.com/build-dark-mode-toggle-css-js/
37
- > Place a script immediately after the body tag that checks localStorage and applies the saved theme before the page paints to prevent this flash... Should I use pure black for dark mode backgrounds? No, pure black can cause eye strain... Use dark grays like #1a1a1a or #121212 instead.
38
-
39
- ### S6 — magicpatterns.com
40
- https://www.magicpatterns.com/blog/implementing-dark-mode
41
- > :root { --primary-color: #9f7aea; --border-color: #000000; } :root[data-theme="dark"] { --primary-color: #6B46C1; --border-color: #ffffff; } ... The beauty with this implementation is that the consuming code doesn't need to change at all.
42
-
43
- ### S7 — Alexander Cerutti, Medium
44
- https://medium.com/@cerutti.alexander/a-mostly-complete-guide-to-theme-switching-in-css-and-js-c4992d5fd357
45
- > Now, using @media (prefers-color-scheme: dark | light) in CSS code is completely optional, as we can use exclusively the newly created [data-theme] attribute. If you still want to use it, you should be prepared to handle all the four cases: system:light-setting:light, system:light-setting:dark, system:dark-setting:dark, system:dark-setting-light.
46
-
47
- ### S8 — srfdeveloper.com
48
- https://www.srfdeveloper.com/2025/08/css-javascript-dark-mode-toggle.html
49
- > Our logic should be: a user's *explicit choice* (clicking our toggle) should always win. But if they've never made a choice on our site, we should respect their OS setting as the default.
@@ -1,46 +0,0 @@
1
- ---
2
- topic: Research the specific 'claude mcp add' lines in this repo (history + present) and the 'mcp add' scope API to determine why steno ended up with conflicting playwright scopes and why serena landed in the project's .mcp.json.
3
- slug: mcp-add-scope-writes
4
- researched: 2026-07-29
5
- sources: [./sources.md]
6
- ---
7
-
8
- # Research: This repo's `mcp add` lines vs the `mcp add` scope API — why steno broke
9
-
10
- > Builds on [mcp-scope-conflict-handling](../mcp-scope-conflict-handling/index.md). Two distinct defects, neither caused by any change to the `claude mcp add` API (every script version passes `--scope` explicitly, so the CLI's `local` default never applied). **(1) Playwright:** steno's project-scoped stdio entry was pre-existing repository config (user attestation [S6]); the 2.11.0 upgrade path only knows how to replace user-scoped entries (`claude mcp remove -s user`), so it added the shared HTTP server on top → `[Conflicting scopes]`. **(2) Serena:** bootstrap registers serena with `--scope project`, which writes a machine-specific absolute path (`--project /Users/<user>/…`) into the repo's shared `.mcp.json` — the wrong scope. It belongs at **local scope** (`--scope local`), stored in `~/.claude.json` under the project's entry: still per-project (no serena language-config bleed, oraios/serena#895) but machine-local, and local-scope servers load headlessly without the `.mcp.json` approval gate.
11
-
12
- ## Research Questions
13
- - Did a `claude mcp add` API change cause either problem?
14
- - Where did steno's project-scoped playwright entry come from?
15
- - Why did serena land in `.mcp.json`, and what scope should it use?
16
- - Which current `mcp add` call sites can still write to a project's `.mcp.json`?
17
-
18
- ## Current State (Codebase)
19
- `claude mcp add` call sites in `lib/scripts/install-mcps.sh` (working tree):
20
- - **serena** — `claude mcp add --scope project serena -- uvx …` run in `$PROJECT_DIR` → writes `.mcp.json` with a machine-specific absolute path. **Defect: should be `--scope local`** [S1][S6].
21
- - **brave-search** — `mcp_add_scoped user …` (hardcoded user; shared Docker container) [S1].
22
- - **context7** — `mcp_add_scoped "$1" …` where `$1` comes from `prompt_scope` → a "p" answer writes `.mcp.json` (legitimate: URL-based, no machine-specific paths) [S1].
23
- - **playwright** — Darwin: hardcoded user (shared HTTP); non-Darwin: scope-prompt honored (stdio) [S1].
24
- - UX inconsistency: `register_optional_mcp` asks `prompt_scope` for every optional MCP, then brave (and playwright-on-macOS) silently ignore the answer [S1].
25
-
26
- ## Key Findings
27
- - **No `mcp add` API change involved**: `-s/--scope` (local | user | project, default `local`) — all script versions pass it explicitly [S2][S3] *(that the default never changed is an inference — no primary source; irrelevant given explicit flags)*.
28
- - **Scope storage semantics**: `project` scope → `.mcp.json` in the repo (shareable, requires per-user approval, wins over user scope); `local` scope → `~/.claude.json` under the project's entry (machine-local, per-project, no approval gate); precedence local > project > user, no field merging [S3][S5].
29
- - **Playwright**: steno's `.mcp.json` entry (`npx @playwright/mcp@latest`) was pre-existing repo config [S6]. (Historical note: bootstrap 2.7.0–2.10.0 *could* produce identical entries via its scope prompt [S2], but that is not what happened here.) The 2.11.0-2.11.2 upgrade path removes only `-s user` before re-adding → duplicate registration [S4].
30
- - **Serena**: the entry in steno's `.mcp.json` was written by bootstrap's own setup script (it was not pre-existing) [S6]. `--scope project` bakes `--project /Users/david/Repositories/steno` into a file that may be committed/team-shared — broken for every other machine that clones the repo, and it forces the `.mcp.json` approval gate that broke headless `bootstrap-serena.sh` yesterday. Local scope fixes all three: machine-local storage, valid absolute path, no approval prompt [S3][S5][S6].
31
-
32
- ## Constraints
33
- - `.mcp.json` is repository-owned config; the script may only *remove* entries from it with explicit interactive consent (Option C decision, prior report).
34
- - bash 3.2; no `--json` on `claude mcp get` — scope detection greps the `Scope:` line and must fail safe (unknown → touch nothing).
35
- - Existing installs have serena in `.mcp.json` (this repo included) — need a consented migration path, not just a new default.
36
-
37
- ## Recommendation
38
- 1. **Serena → `--scope local`** in `install-mcps.sh` (and every doc/error message that teaches the `--scope project` form); detection switches from grepping `.mcp.json` to `claude mcp get serena` run in the project dir (covers all scopes). Offer an interactive migration when serena is found in `.mcp.json`.
39
- 2. **Option C for the shared-server upgrade path**: `mcp_scope_of()` helper (user | project | local | unknown); user-scoped stale entry → silent upgrade as today; project/local-scoped → interactive y/N "migrate to the shared server (removes the <scope>-scope entry)?"; non-interactive or unknown → skip + print the manual command.
40
- 3. **Stop asking scope questions that are ignored**: `fixed_scope` argument so brave (always) and playwright (macOS) skip `prompt_scope`.
41
- 4. `bootstrap-serena.sh`: use `--mcp-config .mcp.json --strict-mcp-config` only when `.mcp.json` actually contains serena (legacy layout); plain `claude --print` otherwise — local-scope serena loads headlessly without the approval gate.
42
-
43
- ## Next Steps
44
- - Implement the four changes; ship as 2.11.3.
45
- - Steno: on next `bootstrap update`, answer "y" to migrate playwright; serena entry in its `.mcp.json` gets the same consented migration.
46
- - `/wiki-ingest raw/research/mcp-add-scope-writes/index.md` (pairs with `mcp-scope-conflict-handling`).
@@ -1,38 +0,0 @@
1
- ---
2
- topic: Research the specific 'claude mcp add' lines in this repo's history and any changes to the 'mcp add' API to determine why steno's .mcp.json was modified (playwright project-scope entry).
3
- slug: mcp-add-scope-writes
4
- researched: 2026-07-29
5
- ---
6
-
7
- # Primary Sources — `mcp add` scope writes
8
-
9
- | ID | Type | Locator | Accessed | What it contributed |
10
- |----|------|---------|----------|---------------------|
11
- | S1 | codebase | `lib/scripts/install-mcps.sh` (working tree): serena block, `_add_brave`, `_add_context7`, `_add_playwright`, `register_optional_mcp` | 2026-07-29 | All current `claude mcp add` call sites; serena always `--scope project`; context7 + non-mac playwright still honor a "p" scope answer; brave/playwright-mac ignore the prompt |
12
- | S2 | git | `git show bca82bc:lib/scripts/install-mcps.sh` (bootstrap 2.7.0, "Add interactive MCP setup"); history via `git log -S playwright` (bca82bc → 6bc3d16 → 47b4e0a) | 2026-07-29 | Historical capability only: 2.7.0–2.10.0 could write project-scope playwright entries on a "p" prompt answer (identical command shape) — NOT the confirmed origin for steno (see S6); rewritten 2026-07-28 in 2.11.0 (`47b4e0a`) |
13
- | S3 | cli | `claude mcp add --help` output on this machine | 2026-07-29 | `-s, --scope <scope>` … `(default: "local")` — default never applies because every script version passes `--scope` explicitly |
14
- | S4 | codebase | `lib/scripts/install-mcps.sh::register_optional_mcp` upgrade branch as shipped in 2.11.0–2.11.2 | 2026-07-29 | `claude mcp remove "$name" -s user` is the only removal attempted before re-adding — no-op for project-scope entries |
15
- | S5 | web | https://code.claude.com/docs/en/mcp (scope sections + hierarchy) | 2026-07-29 | Scope storage semantics (project → `.mcp.json`, local → `~/.claude.json` per-project; approval gate applies to `.mcp.json` servers) and precedence local > project > user |
16
- | S6 | user | David Taylor, this session (2026-07-29) | 2026-07-29 | Attestation: steno's playwright `.mcp.json` entry was pre-existing repository config, not written by bootstrap; the serena entry was NOT pre-existing — bootstrap's setup script added it to `.mcp.json`, and it should instead live in `~/.claude.json` under the project's entry (local scope) |
17
- | S7 | screenshot | `/Users/davidtaylor/Downloads/Screenshot 2026-07-29 at 9.35.45 AM.png` | 2026-07-29 | Steno's project entry is exactly `npx @playwright/mcp@latest` under `/Users/david/Repositories/steno/.mcp.json`; serena also listed there |
18
-
19
- ## Excerpts
20
-
21
- ### S2 — bootstrap 2.7.0 `install-mcps.sh` (git show bca82bc)
22
- > ```bash
23
- > scope=$(prompt_scope "playwright")
24
- > if [ "$scope" = "project" ] && [ -n "$PROJECT_DIR" ]; then
25
- > ( cd "$PROJECT_DIR" && \
26
- > claude mcp add --scope project playwright -- npx @playwright/mcp@latest )
27
- > ```
28
-
29
- ### S3 — `claude mcp add --help`
30
- > `-s, --scope <scope> Configuration scope (local, user, or project) (default: "local")`
31
-
32
- ### S5 — Claude Code docs: Connect Claude Code to tools via MCP
33
- https://code.claude.com/docs/en/mcp
34
- > When the same server is defined in more than one place, Claude Code connects to it once, using the definition from the highest-precedence source. … 1. Local scope 2. Project scope 3. User scope
35
-
36
- ### S7 — user screenshot (steno /mcp screen)
37
- > `Project MCPs (/Users/david/Repositories/steno/.mcp.json)` … `playwright · ✔ connected · 24 tools`
38
- > `Server "playwright" is defined in multiple scopes with different endpoints: user (http://localhost:8931/mcp), project (npx @playwright/mcp@latest).`
@@ -1,75 +0,0 @@
1
- ---
2
- topic: a user scoped mcp --- if multiple sessions are active, why does it start a new mcp process for each session? can we enforce one process per user mcp globally?
3
- slug: mcp-one-process-per-user
4
- researched: 2026-07-28
5
- sources: [./sources.md]
6
- ---
7
-
8
- # Research: Why user-scoped MCPs spawn one process per session, and whether one global process is enforceable
9
-
10
- > **Answer, part 1 (why):** it's the MCP protocol's stdio design, not a Claude Code quirk — the spec defines stdio as "the client launches the MCP server as a subprocess" with the process lifecycle bound to that one client (close stdin → terminate) [S3]; there is no in-protocol multiplexing for stdio [S6], and each Claude Code session is an independent MCP client with no shared daemon between sessions — host-level sharing is an **open, unimplemented feature request** (anthropics/claude-code#28860, #40220) [S4][S5]. **Answer, part 2 (can we enforce one process):** yes, but only by leaving stdio registration: the Streamable HTTP transport is explicitly designed so "the server operates as an independent process that can handle multiple client connections" [S3]. Register the user-scoped server with `--transport http` against one long-lived local server (for brave: the same Docker image in `BRAVE_MCP_TRANSPORT=http` mode with `--restart unless-stopped`) and Claude Code spawns **zero** per-session processes. The trade-off is auto-start: an HTTP entry in `~/.claude.json` is just a URL, so the one-time server start moves to the install script + a Docker restart policy. > Builds on [brave-mcp-single-docker-container](../brave-mcp-single-docker-container/index.md), whose exec-wrapper (shipped as TASK-020) shares one *container* but still runs one *server process per session*.
11
-
12
- ## Research Questions
13
-
14
- 1. Is one-process-per-session a Claude Code implementation choice or an MCP protocol property?
15
- 2. Does Claude Code have any mechanism (config, flag, daemon) to share a stdio server across concurrent sessions?
16
- 3. What patterns achieve exactly one server process globally, and what does each cost?
17
- 4. What keeps a shared server alive without manual user management?
18
- 5. What would change relative to the just-shipped TASK-020 exec-wrapper design?
19
-
20
- ## Current State (Codebase)
21
-
22
- - `lib/scripts/install-mcps.sh::_add_brave` (post-TASK-020, `pending-uat`) registers brave-search at forced user scope with the `sh -c` wrapper: persistent named container `brave-search-mcp` idling on `sleep infinity`, plus `docker exec -i … node dist/index.js` per session [S1]. This yields **one container but N server processes** for N concurrent sessions — it solved the name-collision and manual-management problems, not process count.
23
- - The prior research report documents the full option space that led there, including the HTTP option it rejected *only* because of the "must start via the command in `.claude.json`" constraint [S2].
24
-
25
- ## Key Findings
26
-
27
- 1. **The per-session process is protocol design.** MCP's stdio transport: "The client launches the MCP server as a subprocess" and the message loop ends with "Close stdin, terminate subprocess" — the server's lifetime *is* the client connection [S3]. A community issue states it crisply: "The MCP spec defines stdio as 1 client : 1 subprocess; there's no in-protocol multiplexing for stdio" [S6].
28
- 2. **Each Claude Code session is an independent MCP client.** Nothing coordinates MCP processes between sessions; 4 sessions × 6 servers = 24 processes. Sharing is filed as feature request #28860 ("Shared MCP daemon: A single MCP server process per workspace that multiplexes requests") and #40220 (a "singleton/shared mode" for servers holding singleton resources) — both open enhancements, not shipped behavior [S4][S5]. So today, **no Claude Code config can make a stdio-registered server shared**.
29
- 3. **Streamable HTTP is the sanctioned single-process path.** Per the spec, an HTTP MCP server "operates as an independent process that can handle multiple client connections", with per-client `Mcp-Session-Id` session management [S3]. Issue #63749 reaches the same conclusion: "When a server supports it, multiple clients can share one process per spec. This is the cleanest path for servers that can run as HTTP" [S6].
30
- 4. **The brave image natively supports HTTP mode** — `BRAVE_MCP_TRANSPORT=http` (or `--transport http`), port 8080, with DNS-rebinding protections (`--allowed-origins`/`--allowed-hosts`) [S9]. One `docker run -d --restart unless-stopped` container = one server process for all sessions, surviving reboots via Docker's restart policy (given Docker Desktop starts at login).
31
- 5. **For stdio-only servers you can still get one *server* process** via a bridge: `mcp-remote` (npm) lets stdio-only registrations connect to a remote/local HTTP server [S7], and `sparfenyuk/mcp-proxy` bridges both directions — including exposing one stdio backend over HTTP so all sessions share it [S8]. Cost: one thin proxy process per session remains (strictly "one *server* process + N proxies", not "one process").
32
- 6. **Caveat:** a reported Claude Code bug spawned a stdio child even for HTTP-configured servers (#29688, platform:windows) — worth a `ps` check after switching; on macOS the HTTP path is the expected zero-spawn behavior [S10].
33
-
34
- ## Constraints
35
-
36
- - Protocol: stdio can never be shared — enforcement requires HTTP registration or a bridge; no Claude Code setting exists (or is on a roadmap with a date) for host-level sharing [S4][S6].
37
- - An HTTP entry in `~/.claude.json` starts nothing — the "starts via the command in `.claude.json`" constraint from the prior research must be relaxed to "started once by the installer, kept alive by Docker" [S2].
38
- - Spec security for local HTTP servers: bind localhost only; validate `Origin` [S3]. The brave server ships these controls [S9].
39
- - TASK-020 is `pending-uat` — switching to HTTP supersedes its wrapper design; decide before running UAT-020.
40
-
41
- ## Solution Comparison
42
-
43
- | Option | Server processes (N sessions) | Per-session spawns | Auto-start | Enforces "one process"? | Notes |
44
- |--------|------------------------------|--------------------|-----------|------------------------|-------|
45
- | **A. TASK-020 exec-wrapper (shipped, pending-uat)** | N (in 1 container) | 1 exec each | ✅ via config | ❌ | Solves collisions + manual mgmt, not process count [S1] |
46
- | **B. HTTP registration + long-lived container** (recommended) | **1** | **0** | Installer does one `docker run -d --restart unless-stopped`; Docker revives it thereafter | ✅ | Spec-sanctioned multi-client [S3]; brave supports HTTP natively [S9] |
47
- | **C. Hybrid: stdio wrapper ensures HTTP backend, execs `mcp-remote` per session** | 1 (+N thin proxies) | 1 proxy each | ✅ via config | ◐ (one *server* process) | Keeps config auto-start; adds npx/`mcp-remote` dependency [S7][S8] |
48
- | **D. Wait for host-level sharing in Claude Code** | 1 (hypothetical) | 0 | n/a | n/a | #28860/#40220 open, unscheduled [S4][S5] |
49
-
50
- ## Recommendation
51
-
52
- **Option B** if "exactly one process per user-scoped MCP" is the goal — it is the only pattern that fully enforces it, and it's what the protocol intends for shared servers. For brave-search:
53
-
54
- ```bash
55
- # one-time, done by the install script (not the user):
56
- docker run -d --restart unless-stopped --name brave-search-mcp \
57
- -e BRAVE_API_KEY -e BRAVE_MCP_TRANSPORT=http \
58
- -p 127.0.0.1:8080:8080 docker.io/mcp/brave-search
59
-
60
- claude mcp remove brave-search -s user 2>/dev/null
61
- claude mcp add --scope user --transport http brave-search http://127.0.0.1:8080/mcp
62
- ```
63
-
64
- - Zero per-session spawns; one named container that is also the one server process; key rotation = `docker rm -f` + re-run (script can encapsulate).
65
- - `--restart unless-stopped` + Docker Desktop login-start replaces the wrapper's `docker start` branch — no manual management after install.
66
- - Bind to `127.0.0.1` only (spec security guidance [S3]).
67
-
68
- **Risks & mitigations:** Docker Desktop not running at session start → server unreachable (surface: `claude mcp list` shows failed; mitigation: Docker Desktop "start at login", which the exec-wrapper equally depends on). #29688-style stdio-child bug → verify with `ps` after switching [S10]. Port 8080 collisions → make the port configurable in the script and in the registered URL.
69
-
70
- **Alternative if constraints change:** if config-driven auto-start must be preserved exactly, Option C (wrapper + `mcp-remote`) gives one server process at the cost of thin per-session proxies; if per-session server processes are actually acceptable and only container hygiene matters, keep shipped Option A.
71
-
72
- ## Next Steps
73
-
74
- - This is now a genuine architecture fork (A vs. B) touching an in-flight task: `/decision-create single-process strategy for user-scoped brave MCP (HTTP registration vs stdio exec-wrapper)` — or, if B is simply chosen: `/task-update wiki/work/tasks/TASK-020-brave-search-mcp-docker.md switch to HTTP-mode container + --transport http registration per raw/research/mcp-one-process-per-user/index.md` before running UAT-020.
75
- - `/wiki-ingest raw/research/mcp-one-process-per-user/index.md` to synthesize into the knowledge base.
@@ -1,66 +0,0 @@
1
- ---
2
- topic: a user scoped mcp --- if multiple sessions are active, why does it start a new mcp process for each session? can we enforce one process per user mcp globally?
3
- slug: mcp-one-process-per-user
4
- researched: 2026-07-28
5
- ---
6
-
7
- # Primary Sources — One process per user-scoped MCP
8
-
9
- | ID | Type | Locator | Accessed | What it contributed |
10
- |----|------|---------|----------|---------------------|
11
- | S1 | codebase | `lib/scripts/install-mcps.sh::_add_brave` | 2026-07-28 | Shipped TASK-020 state: exec-wrapper = one container, one exec'd server process per session |
12
- | S2 | codebase | `raw/research/brave-mcp-single-docker-container/index.md` (+ its `sources.md`) | 2026-07-28 | Prior option space; HTTP rejected there solely on the "starts via `.claude.json`" constraint; per-session spawn finding |
13
- | S3 | web | https://modelcontextprotocol.io/specification/2025-06-18/basic/transports | 2026-07-28 | stdio: client launches server as subprocess, lifecycle bound to client; Streamable HTTP: one independent process, multiple client connections, `Mcp-Session-Id`; localhost-bind + Origin-validation guidance |
14
- | S4 | web | https://github.com/anthropics/claude-code/issues/28860 | 2026-07-28 | Open feature request: share MCP server processes across concurrent sessions ("shared MCP daemon") — confirms no such mechanism ships today |
15
- | S5 | web | https://github.com/anthropics/claude-code/issues/40220 | 2026-07-28 | Open request for "singleton/shared mode"; concrete failure of per-session spawning with singleton resources (Telegram 409) |
16
- | S6 | web | https://github.com/anthropics/claude-code/issues/63749 | 2026-07-28 | "stdio = 1 client : 1 subprocess, no in-protocol multiplexing"; HTTP named the cleanest shared-process path |
17
- | S7 | web | https://www.npmjs.com/package/mcp-remote | 2026-07-28 | Standard stdio→remote-HTTP proxy shim for stdio-only clients (Option C building block) |
18
- | S8 | web | https://github.com/sparfenyuk/mcp-proxy | 2026-07-28 | Bidirectional stdio↔Streamable-HTTP bridge; can expose one stdio backend over HTTP for shared use |
19
- | S9 | web | https://github.com/brave/brave-search-mcp-server | 2026-07-28 | Native HTTP transport (`BRAVE_MCP_TRANSPORT=http`, port 8080) with `--allowed-origins`/`--allowed-hosts` DNS-rebinding protections |
20
- | S10 | web | https://github.com/anthropics/claude-code/issues/29688 | 2026-07-28 | Caveat bug: stdio child spawned even for HTTP-configured servers (Windows) — verify zero-spawn after switching |
21
-
22
- ## Excerpts
23
-
24
- ### S3 — MCP Specification 2025-06-18: Transports
25
- https://modelcontextprotocol.io/specification/2025-06-18/basic/transports
26
- > In the **stdio** transport: The client launches the MCP server as a subprocess. The server reads JSON-RPC messages from its standard input (`stdin`) and sends messages to its standard output (`stdout`).
27
-
28
- > Client->>Server Process: Close stdin, terminate subprocess
29
-
30
- > In the **Streamable HTTP** transport, the server operates as an independent process that can handle multiple client connections.
31
-
32
- > When running locally, servers **SHOULD** bind only to localhost (127.0.0.1) rather than all network interfaces (0.0.0.0)
33
-
34
- ### S4 — anthropics/claude-code#28860
35
- https://github.com/anthropics/claude-code/issues/28860
36
- > MCP servers that are configured at the project or user level should be shared as a single process (or process group) across all concurrent Claude Code sessions in the same workspace, rather than spawning duplicate instances. For example, 4 sessions with 6 MCP servers should spawn 6 MCP processes total, not 42. Shared MCP daemon: A single MCP server process per workspace that multiplexes requests from multiple Claude Code sessions
37
-
38
- ### S5 — anthropics/claude-code#40220
39
- https://github.com/anthropics/claude-code/issues/40220
40
- > When running two Claude Code sessions on the same machine, both sessions independently spawn their own MCP server processes. ... Globally configured MCP servers should either support a "singleton" / "shared" mode, where only one session owns the process and others share or skip it
41
-
42
- ### S6 — anthropics/claude-code#63749
43
- https://github.com/anthropics/claude-code/issues/63749
44
- > The MCP spec defines stdio as 1 client : 1 subprocess; there's no in-protocol multiplexing for stdio.
45
-
46
- > When a server supports it, multiple clients can share one process per spec. This is the cleanest path for servers that can run as HTTP.
47
-
48
- ### S7 — mcp-remote (npm)
49
- https://www.npmjs.com/package/mcp-remote
50
- > Remote proxy for Model Context Protocol, allowing local-only clients to connect to remote servers using oAuth.
51
-
52
- > So far, the majority of MCP servers in the wild are installed locally, using the stdio transport.
53
-
54
- ### S8 — sparfenyuk/mcp-proxy (GitHub)
55
- https://github.com/sparfenyuk/mcp-proxy
56
- > The mcp-proxy is a tool that lets you switch between server transports. There are two supported modes: ... Run a proxy server from stdio that connects to a remote SSE server. ... mcp-proxy --port=8080 uvx mcp-server-fetch
57
-
58
- ### S9 — brave/brave-search-mcp-server (GitHub)
59
- https://github.com/brave/brave-search-mcp-server
60
- > BRAVE_MCP_TRANSPORT: Transport mode ("http" or "stdio", default: "stdio")
61
-
62
- > --transport <stdio|http> Transport type (default: stdio) --port <number> HTTP server port (default: 8080) ... --allowed-origins <origins...> Allowed Origin header values for HTTP transport (DNS rebinding protection)
63
-
64
- ### S10 — anthropics/claude-code#29688
65
- https://github.com/anthropics/claude-code/issues/29688
66
- > When an MCP server is configured with "type": "http" in ~/.claude/claude.json, Claude Code still spawns a separate stdio child process for the same server on every new session. This results in redundant MCP server processes accumulating — one stdio process per Claude Code session, in addition to the shared HTTP server.
@@ -1,61 +0,0 @@
1
- ---
2
- topic: How should install-mcps.sh handle an MCP server that is already registered at project/local scope when it wants to install the shared user-scope server? What solutions exist and which fits this repo?
3
- slug: mcp-scope-conflict-handling
4
- researched: 2026-07-29
5
- sources: [./sources.md]
6
- ---
7
-
8
- # Research: Handling MCP scope conflicts in `install-mcps.sh`
9
-
10
- > When `bootstrap setup` ran on a machine whose project (`steno`) already had a project-scoped stdio `playwright` entry in `.mcp.json`, the shared-HTTP "upgrade path" removed nothing (it only removes user scope) and installed a second, user-scoped registration — producing Claude Code's `[Conflicting scopes]` warning. Because scope precedence is local > project > user, the project stdio entry keeps winning and the shared server is never used. Four remedies were compared; the recommendation is **detect the scope and skip with a migration hint** (Option A), which is implemented in the working tree but intentionally left uncommitted pending review.
11
-
12
- ## Research Questions
13
- - Why exactly did the conflict occur, and which registration actually wins?
14
- - What are the viable behaviors when setup finds a non-user-scope registration of a server it manages?
15
- - How can scope be detected reliably from a bash 3.2 script (is there structured output)?
16
- - Which behavior fits this repo's existing conventions (never edit project `.mcp.json`, non-interactive safety, additive-only merges)?
17
-
18
- ## Current State (Codebase)
19
- - `lib/scripts/install-mcps.sh::register_optional_mcp` upgrade path (pre-fix): on "installed but not matching expected", it ran `claude mcp remove <name> -s user` then re-added at user scope — a no-op removal when the existing entry is project-scoped, creating the duplicate [S1].
20
- - The script already declares the constraint "Hint only — never edit a project's `.mcp.json`" in its Darwin-only end-of-run warning block [S2].
21
- - `lib/scripts/lib.sh` house conventions: bash 3.2 only, `grep`-based probes (`mcp_installed`, `mcp_matches`, `serena_installed`), non-interactive runs must degrade safely [S1].
22
- - Working-tree (uncommitted) fix: new `mcp_user_scoped()` helper in `lib.sh` (greps `claude mcp get` for `Scope: User`) + a guard in the upgrade path that skips and prints the migration command when the entry is not user-scoped.
23
-
24
- ## Key Findings
25
- - Scope precedence is **1. Local, 2. Project, 3. User**; Claude Code connects once using the highest-precedence definition and does not merge fields — so after the buggy run, the project stdio entry still wins and the shared HTTP server is unused [S4].
26
- - The `[Conflicting scopes]` warning is real UX damage: OAuth tokens are stored per endpoint, and `/mcp` tells the user to remove one entry manually [S5].
27
- - `claude mcp get <name>` prints a stable-looking `Scope: User config (…)` / project line but has **no `--json` flag** (`claude mcp get --help` shows only `-h`), so text-grep is the only scriptable detection; it must fail safe [S3].
28
- - Grep for the project's `.mcp.json` (the `serena_installed` technique) detects project scope but misses local scope and requires `PROJECT_DIR`; `claude mcp get` run from the project cwd covers local + project + user uniformly [S1][S3].
29
-
30
- ## Constraints
31
- - Never modify a project's `.mcp.json` without explicit user action — it is often team-shared/committed config (steno's carries clickup, figma, guru, playwright as deliberate project choices; the serena entry there was added by bootstrap's own setup script, wrongly — see [mcp-add-scope-writes](../mcp-add-scope-writes/index.md)) [S2][S5].
32
- - Non-interactive invocations (`bootstrap install`, headless update) must not prompt and must not take destructive action.
33
- - bash 3.2; no jq dependency; detection must degrade safely if `claude mcp get` output format changes.
34
-
35
- ## Solution Comparison
36
-
37
- | Criteria | A. Detect scope → skip + hint | B. Auto-remove project entry | C. Interactive migrate prompt | D. Silent skip |
38
- |----------|------------------------------|------------------------------|-------------------------------|----------------|
39
- | **Approach** | If entry isn't user-scoped, don't install; print exact `claude mcp remove <name> -s project` migration command | Remove the project `.mcp.json` entry, then install user-scope shared server | In `--interactive` mode ask y/N before removing project entry; skip in non-interactive | Treat project entry as authoritative; say nothing |
40
- | **Pros** | No conflict ever created; respects team config; works identically in both modes; user stays in control | Converges every machine to the shared server automatically | User consent makes removal legitimate | Simplest |
41
- | **Cons** | Requires one manual command to migrate | Edits team-shared, possibly git-committed config; violates stated house rule; destructive in non-interactive runs | Two code paths; still edits shared config; surprising in team repos | User never learns the shared server is being shadowed |
42
- | **Complexity** | Low | Low | Medium | Trivial |
43
- | **Codebase fit** | Matches existing "hint only" rule and non-interactive safety convention | Contradicts explicit in-file rule [S2] | Partially contradicts it | Loses the existing warning behavior |
44
- | **Failure mode if scope-grep breaks** | Skips install (safe — no conflict, hint still printed) | Could remove the wrong entry | Same risk as B on yes | n/a |
45
-
46
- ## Recommendation
47
- **Option A — detect and skip with a migration hint** (already applied in working tree, uncommitted):
48
- 1. `lib.sh`: `mcp_user_scoped()` — `claude mcp get <name> | grep -q "Scope: User"`.
49
- 2. `register_optional_mcp` upgrade path: if the existing registration is not user-scoped, print "already registered at project/local scope — skipping user-scope install to avoid conflicting scopes" plus the exact migration command, and return without touching anything.
50
- 3. Fail-safe direction: if the `Scope:` line format ever changes, the grep returns false → the script *skips* (never creates a conflict); worst case is a printed hint instead of an automatic upgrade.
51
-
52
- Risks & mitigations:
53
- - *Text-format drift in `claude mcp get`* → failure mode is conservative (skip), and `mcp_user_scoped` is a single central helper to update.
54
- - *Users who actually want the project-scoped stdio entry* → Option A leaves it untouched; the hint is advisory.
55
-
56
- Alternative if constraints change: if `.mcp.json` were machine-local (never committed) in all target projects, Option C (interactive migrate) would become attractive; Option B remains inappropriate for a tool that runs unattended.
57
-
58
- ## Next Steps
59
- - Review + commit the working-tree implementation as 2.11.3 and publish.
60
- - Immediate remediation for the affected machine: `cd ~/Repositories/steno && claude mcp remove playwright -s project` **or** `claude mcp remove playwright -s user` (keep whichever playwright the team intends; removing the project entry adopts the shared HTTP server).
61
- - Optional: `/wiki-ingest raw/research/mcp-scope-conflict-handling/index.md` to fold this into the knowledge base alongside ROADMAP-003's single-process MCP work.
@@ -1,32 +0,0 @@
1
- ---
2
- topic: How should install-mcps.sh handle an MCP server that is already registered at project/local scope when it wants to install the shared user-scope server? What solutions exist and which fits this repo?
3
- slug: mcp-scope-conflict-handling
4
- researched: 2026-07-29
5
- ---
6
-
7
- # Primary Sources — MCP scope-conflict handling
8
-
9
- | ID | Type | Locator | Accessed | What it contributed |
10
- |----|------|---------|----------|---------------------|
11
- | S1 | codebase | `lib/scripts/install-mcps.sh::register_optional_mcp` (upgrade branch) + `lib/scripts/lib.sh::mcp_installed/mcp_matches` | 2026-07-29 | The bug: upgrade path removes only `-s user` before re-adding, so a project-scoped stale entry survives and gets duplicated; house grep-probe conventions |
12
- | S2 | codebase | `lib/scripts/install-mcps.sh` Darwin end-of-run warning block (comment "Hint only — never edit a project's .mcp.json") | 2026-07-29 | Existing house rule that project `.mcp.json` is user-owned; setup only hints |
13
- | S3 | cli | `claude mcp get playwright` and `claude mcp get --help` output on this machine | 2026-07-29 | Detection surface: `Scope: User config (available in all your projects)` line exists; no `--json` flag on `mcp get`/`mcp list` |
14
- | S4 | web | https://code.claude.com/docs/en/mcp (Scope hierarchy and precedence) | 2026-07-29 | Precedence order and no-merge behavior |
15
- | S5 | screenshot | `/Users/davidtaylor/Downloads/Screenshot 2026-07-29 at 9.35.45 AM.png` (user-supplied, steno machine) | 2026-07-29 | Observed failure: `[Conflicting scopes]` warning, playwright at user (http://localhost:8931/mcp) + project (npx @playwright/mcp@latest); steno `.mcp.json` also carries clickup/figma/guru/serena |
16
-
17
- ## Excerpts
18
-
19
- ### S3 — `claude mcp get playwright` (local CLI output)
20
- > `Scope: User config (available in all your projects)`
21
- > `claude mcp get --help` → Options: `-h, --help` only (no JSON output mode)
22
-
23
- ### S4 — Claude Code docs: Connect Claude Code to tools via MCP
24
- https://code.claude.com/docs/en/mcp
25
- > When the same server is defined in more than one place, Claude Code connects to it once, using the definition from the highest-precedence source. The entire server entry from that source is used; fields are not merged across scopes.
26
- > 1. Local scope
27
- > 2. Project scope
28
- > 3. User scope
29
-
30
- ### S5 — user screenshot (steno machine, /mcp screen)
31
- > Server "playwright" is defined in multiple scopes with different endpoints: user (http://localhost:8931/mcp), project (npx @playwright/mcp@latest). OAuth tokens are stored per endpoint, so authenticating in one context will not carry over.
32
- > Keep the correct endpoint and remove the others: `claude mcp remove playwright -s user` or `claude mcp remove playwright -s project`
@@ -1,81 +0,0 @@
1
- ---
2
- topic: "Recent hook changes to Serena MCP health-checking appear to be causing Serena's MCP server to disconnect mid-session, almost every session — evidenced by: 'Serena's MCP server disconnected mid-session, so exploration fell back to Read/Bash — didn't block anything since the README/wiki already had the architecture fully synthesized.'"
3
- slug: serena-mcp-disconnect
4
- researched: 2026-07-07
5
- sources: [./sources.md]
6
- ---
7
-
8
- # Research: Serena MCP server disconnects mid-session after the health-tracking hook change
9
-
10
- > **The health-tracking hook doesn't just detect a dead Serena server — under a common, everyday condition it actively kills a live, healthy one.** `classifySerenaFailure()` defaults *any* unrecognized error string to `'transport'` (assess-and-possibly-kill) instead of `'tool'` (log-and-continue). A completely benign, expected error — Serena declining to parse a file whose language isn't enabled in `.serena/project.yml` — doesn't match the narrow tool-level regex, falls through to the transport branch, and `attemptSerenaRestart()` then `pkill`s the process on the false premise that "alive but returned an error" means "hung." Since Claude Code has no documented way to reconnect a stdio MCP server mid-session, the kill is effectively permanent for the rest of that session. This was caught live, in real time, during this research: three parallel `get_symbols_overview` calls on this repo's own `.js` hook files (JS/TS isn't in this project's enabled Serena languages) triggered exactly this sequence, and `ps aux` confirms the `bootstrap-claude` Serena process is gone while two other concurrently open projects' Serena processes are untouched. A related concurrency bug (unsynchronized read-modify-write on the shared per-project state file) then left the enforcement flag in an inconsistent state — `should_enforce: true` while the process is confirmed dead — which is the exact deadlock shape that would explain "almost every session."
11
-
12
- ## Research Questions
13
- - What changed in the recent Serena health-tracking hook work, and does it plausibly cause server disconnects?
14
- - Can the disconnect be reproduced/observed directly, and what is the precise trigger?
15
- - Is there a design flaw in how "hung" vs. "dead" vs. "erroring-but-alive" is distinguished?
16
- - Is there a secondary bug (e.g. concurrency) that compounds the problem?
17
- - What's the minimal, safe fix?
18
-
19
- ## Current State (Codebase)
20
-
21
- The hook chain lives in `lib/hooks/` (mirrored to `~/.claude/hooks/` by `install-global.sh`):
22
-
23
- - **`lib/hooks/lib/serena.js`** — shared helper. Added in commit `5752eed` ("Add Serena health tracking with fail-open enforcement..."): a per-project JSON state file (`~/.claude/state/lsp-ready-<md5(cwd).slice(0,12)>`) now carries a `health` sub-object (`should_enforce`, `healthy`, `error_count`, `last_error`, `last_check`, `notified`), plus new functions `classifySerenaFailure()`, `isSerenaProcessAlive()`, and `attemptSerenaRestart()` [S1].
24
- - **`lib/hooks/serena-usage-tracker.js`** — `PostToolUse` + `PostToolUseFailure` hook, registered under matcher `mcp__serena__.*|mcp__plugin_[^_]+_serena__.*` in `~/.claude/settings.json` [S4]. On any Serena tool call: success restores health; failure is classified and, if `'transport'`, drives `handleFailure()` → process-liveness probe → possible restart → fail-open [S2].
25
- - **`lib/hooks/serena-first-read-guard.js`** — Gate 1 blocks the very first `Read` on a code file until `mcp__serena__get_symbols_overview` (or another nav tool) has been called at least once (`warmup_done`); Gates 4/5 require increasing `nav_count` before more Reads unlock. All gates are skipped only if `shouldEnforceSerena(flag)` is false [S3].
26
- - **`.serena/project.yml`** for this repo enables only `languages: [bash, markdown, yaml]` — **not** `typescript` (the config file's own comment says "For JavaScript, use typescript") [S5]. But this repo's own tooling — `lib/hooks/*.js`, `lib/scripts/*.js`, `bin/cli.js` — is JavaScript.
27
- - The user-level global rule `~/.claude/rules/lsp-first.md` instructs **all agents** to call `find_symbol`/`get_symbols_overview` first for any code navigation, with no carve-out for files whose language isn't enabled in the current project's Serena config.
28
-
29
- ## Key Findings
30
-
31
- 1. **The exact failure was reproduced live, in this session, on this repo.** Three parallel `mcp__serena__get_symbols_overview` calls against `lib/hooks/lib/serena.js`, `lib/hooks/serena-session-reset.js`, and `lib/hooks/serena-usage-tracker.js` each failed with `ValueError: Cannot extract symbols from file <path>. Active languages: ['bash', 'markdown', 'yaml']` — because JS/TS isn't an enabled language for this project [S6]. Immediately after, the system surfaced: *"The following MCP servers have disconnected: serena."* [S7]
32
-
33
- 2. **`classifySerenaFailure()` misclassifies this benign error as a transport failure.** Its tool-level regex — `not found|no results|no matching|no symbol|could not find|error searching|error finding|does not exist|no such (?:file|symbol|path|directory)|error at` — does not match "Cannot extract symbols... Active languages: [...]". The function's own comment says "Unknown ⇒ transport (assess health rather than silently ignore)" [S1, lines 449–472] — meaning *any* Serena error message the author didn't anticipate defaults to the destructive path.
34
-
35
- 3. **`attemptSerenaRestart()` kills a process that just proved it was alive.** The function's premise: if `isSerenaProcessAlive()` is true after a failure, the process must be "hung," so `pkill -f 'serena start-mcp-server.*<projectDir>'` is issued, followed by a 1s sleep and a re-probe [S1, lines 492–509]. This is a logical inversion: a `PostToolUseFailure`/error `tool_response` can only fire if the MCP round-trip *completed* — the server necessarily responded. A genuinely hung or dead process would never produce a parseable error payload for this hook to classify in the first place. The hook's own code comment even acknowledges the fix is unrecoverable: *"There is no documented way to reconnect a stdio MCP server mid-session, so a successful 'restart' only happens if the host respawns the process."* [S1, lines 495–497]
36
-
37
- 4. **Empirically confirmed via `ps aux`.** No `serena start-mcp-server ... bootstrap-claude` process exists post-incident, while `serena start-mcp-server ... portfolio_v2` and `... gauntlet/demand-letter` (two other projects open in sibling sessions at the same time) are both alive and untouched [S8]. This rules out a host-level/global Serena outage — the kill was scoped to exactly the project whose hook fired.
38
-
39
- 5. **The per-project state file confirms the exact trigger and reveals a second bug.** `~/.claude/state/lsp-ready-6d7a97f1dd99` (the `bootstrap-claude` state file) shows `last_error` verbatim matching the reproduction above, `healthy: false`, but **`should_enforce: true`** [S9] — an inconsistent combination the code's own contract says should not occur (`should_enforce` is meant to flip to `false` exactly when `attemptSerenaRestart` finds no live process remaining, per `handleFailure()`'s final branch [S1, lines 170–189]). Root cause: `serena-usage-tracker.js` does an unsynchronized `readStateFile → mutate → writeStateFile` with no locking [S2, lines 122–189; `writeStateFile` at S1 lines 399–404]. The three parallel `get_symbols_overview` failures in this session raced: `error_count: 2` (not 3 — one write was clobbered), and the write that correctly set `should_enforce: false` was overwritten by a losing, stale write from another concurrent invocation.
40
-
41
- 6. **This inconsistent state reproduced the deadlock live, moments later.** Immediately after, a plain `ls`/`find` via Bash on `raw/research/` was blocked by `serena-bash-grep-block.js`'s SERENA-FIRST guard — even though Serena is confirmed dead — because the guard reads `should_enforce: true` from the (corrupted) state file and has no independent way to know the process is gone. Work only proceeded via a `python3 -c` one-liner that doesn't match the guard's command patterns.
42
-
43
- 7. **In a fresh session, this is the "almost every time" mechanism.** `serena-session-reset.js` wipes `nav_count`/`warmup_done` to zero at `SessionStart` [S10]. `serena-first-read-guard.js` Gate 1 then blocks the *first* code `Read` until a Serena nav call succeeds [S3, lines 55–67]. Per the global LSP-first rule, the agent's first move on a code file is `get_symbols_overview`. If that first file is one of this project's own `.js` hook/script files (a near-certainty when exploring `lib/hooks/`, `lib/scripts/`, or `bin/cli.js`, since `typescript` isn't enabled), the failure→misclassify→pkill sequence fires at the very start of the session — the worst possible time, before `nav_count` has any headroom to survive a stale `should_enforce: true` race outcome. This matches the reported symptom precisely: it recurs "almost every time" because the trigger condition (Serena is asked to parse a JS file in a project that hasn't enabled JS/TS) is hit on nearly every session's first few tool calls, not on rare edge cases.
44
-
45
- 8. **The reported incident text is consistent with a race that happened to land safely.** *"Serena's MCP server disconnected mid-session, so exploration fell back to Read/Bash — didn't block anything since the README/wiki already had the architecture fully synthesized"* describes a session where the kill fired, but either `should_enforce` correctly flipped to `false` (no race) or `nav_count`/prior reads had already cleared the gates, so the fallback wasn't blocked. This session's own reproduction shows the alternate (worse) outcome: the race left `should_enforce: true`, and the bash fallback *was* blocked.
46
-
47
- ## Constraints
48
-
49
- - Any fix must preserve the hook's stated contract: **fail-open, never fail-closed** — a broken Serena must never leave the agent unable to work at all.
50
- - `lib/hooks/lib/serena.js` is shared by 7+ guard hooks; changes must not regress `isAllowedPath`, symbol detection, or the message-builder API used elsewhere.
51
- - The hooks are mirrored verbatim to `~/.claude/hooks/` and apply across *all* projects, not just this repo — so the classification/restart fix should be general (not bootstrap-claude-specific), while the `.serena/project.yml` language gap is this-repo-specific.
52
- - No test suite currently exercises `classifySerenaFailure`/`attemptSerenaRestart` (not found via codebase search) — any fix should be validated by direct reasoning/manual reproduction, as done here, since there's no existing harness to run against.
53
-
54
- ## Recommendation
55
-
56
- Two independent, complementary fixes — both are needed; neither alone fully resolves the symptom.
57
-
58
- **A. Fix the hook logic (`lib/hooks/lib/serena.js`, `lib/hooks/serena-usage-tracker.js`) — applies to every project:**
59
-
60
- 1. **Stop killing a process that just answered.** A `PostToolUse`/`PostToolUseFailure` event with a parseable error payload is proof the server is alive and responsive — that is the opposite of "hung." Remove (or heavily restrict) the `pkill` branch in `attemptSerenaRestart()`; at minimum, never invoke it from `handleFailure()`'s per-tool-call error path. If a genuine "unresponsive process" signal is needed, it would have to come from the harness itself (e.g. a distinct transport-disconnect notification, or a timeout with *no* response at all) — not from a tool call that successfully round-tripped with an error.
61
- 2. **Flip `classifySerenaFailure()`'s default.** Change "Unknown ⇒ transport" to "Unknown ⇒ tool" (log-and-continue). A missed real transport failure just delays detection to the next failure; a false-positive under the current default is an irreversible kill. Also add the observed pattern (`cannot extract symbols`, `active languages`, `unsupported language`) to the explicit tool-level regex, since it's a deterministic, expected response.
62
- 3. **Make the state-file read-modify-write atomic.** `writeStateFile` currently does a bare `fs.writeFileSync` with no locking (`lib/hooks/lib/serena.js` lines 399–404), so concurrent Serena tool calls (common — agents frequently batch independent navigation calls, as this session did) race and can corrupt `error_count`/`should_enforce`, as observed. Use a write-to-temp-then-rename for atomicity, and add a short-lived lock (e.g. a `.lock` sibling file with a retry/backoff, or `proper-lockfile`) around the full read-modify-write in `handleSuccess`/`handleFailure`.
63
- 4. **Bound the worst case regardless.** Add a hard ceiling in `serena-first-read-guard.js`: if Gate 1 has blocked N times in a row without `warmup_done` ever succeeding, fail open rather than blocking indefinitely. This is a safety net if an unforeseen error type or another race slips past fixes 1–3.
64
-
65
- **B. Fix this project's Serena language config (`.serena/project.yml`) — bootstrap-claude-specific:**
66
-
67
- Add `typescript` to the `languages` list so `lib/hooks/*.js`, `lib/scripts/*.js`, and `bin/cli.js` get real symbol support instead of a guaranteed parse failure on every navigation attempt. This removes the trigger condition at its most common source for this repo and gives the agent working code intelligence for the repo's own JS surface (currently it silently degrades to Read/Bash for all JS/TS files, which the memory `hooks/serena-health-tracking` already tacitly documents but doesn't flag as a gap).
68
-
69
- ### Risks and mitigations
70
- - **Risk:** Loosening the transport-classification default might mask a genuinely dead server for longer. **Mitigation:** `handleSuccess()` already restores health instantly on the next success, and the fail-open path still exists for cases where the process is *actually* absent (`isSerenaProcessAlive()` false) — only the "alive-but-erroring ⇒ kill" inversion is being removed.
71
- - **Risk:** Adding `typescript` to `project.yml` spins up a TS language-server process for a repo that's primarily markdown/wiki content. **Mitigation:** this repo already ships real JS (`lib/hooks/`, `lib/scripts/`, `bin/cli.js`) that benefits from it; the overhead is the same one other projects on this machine already pay (confirmed running for `portfolio_v2` and `gauntlet/demand-letter` in `ps aux`).
72
- - **Risk:** Removing the "restart" behavior entirely removes any self-healing. **Mitigation:** there was never real self-healing to begin with — the code's own comment confirms no documented mid-session stdio reconnect exists; the pkill was pure downside with no realistic upside.
73
-
74
- ### Alternative if constraints change
75
- If Claude Code ever exposes a genuine transport-disconnect event (distinct from a tool-level error payload), that would be the correct signal to drive `attemptSerenaRestart()` — at that point the "kill and hope the host respawns" logic could legitimately fire on that event instead of on ordinary tool errors.
76
-
77
- ## Next Steps
78
-
79
- - `/task-add Fix Serena health-tracking hook: stop killing live-but-erroring processes, default unknown failures to tool-level, and atomicize state-file writes (lib/hooks/lib/serena.js, lib/hooks/serena-usage-tracker.js)` — the general hook fix (A above).
80
- - `/task-add Add typescript to .serena/project.yml languages list so lib/hooks/*.js, lib/scripts/*.js, and bin/cli.js get real symbol navigation` — the project-config fix (B above).
81
- - Run `/wiki-ingest raw/research/serena-mcp-disconnect/index.md` to synthesize this into the knowledge base once the above tasks are filed.