From a6000df9744f31df2eb63eff4911f5d96180a01c Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Mon, 16 Nov 2026 00:42:16 -0500 Subject: [PATCH] fix(claude-code): send the saved Server credential to the plugin MCP server Setup saves a URL-bound credential that the hooks read, but the plugin's MCP server sent only `${POWERCONTEXT_CLAUDE_AUTHORIZATION:-}`. Without that variable in the process that starts Claude Code, MCP failed to connect and offered no tools while the hooks kept working. The MCP server now runs a `headersHelper` that emits the credential saved for the endpoint Claude Code connects to, and nothing for another endpoint. The static environment header stays for when nothing is saved. Claude Code removes credential-like variables before it runs a plugin's helper, so the helper does not read the environment and the saved credential wins for MCP; the docs say to rerun setup to rotate the token. --- .claude-plugin/marketplace.json | 2 +- docs/en/docs/integrations/claude-code.md | 27 +++++-- docs/en/docs/operate/troubleshoot.md | 15 ++-- docs/zh/docs/integrations/claude-code.md | 23 ++++-- docs/zh/docs/operate/troubleshoot.md | 12 ++- integrations/claude-code/README.md | 9 ++- .../powercontext/.claude-plugin/plugin.json | 2 +- .../plugins/powercontext/.mcp.json | 3 +- .../plugins/powercontext/README.md | 11 ++- .../powercontext/claude_code_settings.py | 16 +++- .../powercontext/hooks/session_start.py | 2 +- .../powercontext/hooks/user_prompt_submit.py | 2 +- .../powercontext/scripts/mcp_headers.py | 46 +++++++++++ .../powercontext/scripts/workspace_scope.py | 2 +- tests/claude_code_plugin/test_contract.py | 77 ++++++++++++++++++- tests/claude_code_plugin/test_python_floor.py | 21 +++++ 16 files changed, 228 insertions(+), 42 deletions(-) create mode 100644 integrations/claude-code/plugins/powercontext/scripts/mcp_headers.py diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6c6cf26158..3b41983489 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "name": "powercontext", "source": "./integrations/claude-code/plugins/powercontext", "description": "Restore project memory and transfer current work from Claude Code", - "version": "0.1.3", + "version": "0.1.4", "category": "Productivity" } ] diff --git a/docs/en/docs/integrations/claude-code.md b/docs/en/docs/integrations/claude-code.md index 54acfa2fc6..393e1f8033 100644 --- a/docs/en/docs/integrations/claude-code.md +++ b/docs/en/docs/integrations/claude-code.md @@ -71,7 +71,8 @@ Load `.env` on the client. It contains the complete installation configuration, MCP uses setup's persisted `server_url`, while `POWERCONTEXT_CLAUDE_SERVER_URL` can override the Hook. After changing that environment URL, also update the persisted connection with matching-source setup and `--server-url`. -Both the Hook and MCP headersHelper need `POWERCONTEXT_CLAUDE_AUTHORIZATION` from the client environment. +Setup saves the client's `POWERCONTEXT_CLAUDE_AUTHORIZATION` for that `server_url`; the Hook and the MCP `headersHelper` +both read it. See [Connect an authenticated Server](#connect-an-authenticated-server) for precedence and rotation. Desktop or other launch methods may not inherit terminal variables; restart the Claude process you actually use after changes. Running setup again updates the plugin configuration and verifies the installed version. It does not remove existing @@ -203,16 +204,25 @@ export POWERCONTEXT_SERVER_AUTH_TOKEN="$POWERCONTEXT_LOCAL_TOKEN" powercontext server run ``` -Start Claude Code from an environment containing the matching complete header: +Run setup from an environment containing the matching complete header: ```bash export POWERCONTEXT_CLAUDE_AUTHORIZATION="Bearer $POWERCONTEXT_LOCAL_TOKEN" -claude +powercontext setup claude-code ``` -The Hook reads this process environment value directly, while the MCP configuration expands it into the -`Authorization` header. The MCP header defaults to an empty value when the variable is absent. Never put the token in -the Server URL, plugin options, `.mcp.json`, Source metadata, or logs. +Setup stores a URL-bound credential under `$CLAUDE_CONFIG_DIR/powercontext/credentials.json` (by default, +`~/.claude/powercontext/credentials.json`). The Hook reads that record, and the plugin's MCP server reads it through a +`headersHelper` that runs `scripts/mcp_headers.py` with `python3`, as the Hooks do. New sessions, including ones that +Desktop or another launcher starts, do not need an authorization export. Saved credentials are rejected for a +different endpoint, malformed storage, or unsafe POSIX permissions, and are used only for an HTTPS or loopback +Server; for a non-loopback HTTP Server, export the value before starting Claude Code. + +For the Hook, an explicit `POWERCONTEXT_CLAUDE_AUTHORIZATION` value overrides saved authorization without changing it. +MCP sends that value as a static header only when no credential is saved for its endpoint: Claude Code removes +credential-like variables before it runs a plugin's `headersHelper`, so the saved credential wins for MCP. To rotate +the token, run setup again with the new value; rerunning setup without a token preserves the saved credential. Never +put the token in the Server URL, plugin options, `.mcp.json`, Source metadata, or logs. Plain HTTP is allowed on loopback by default. For a non-loopback Server, use HTTPS or explicitly set `POWERCONTEXT_CLAUDE_ALLOW_INSECURE_HTTP=true`. Guided setup can save this consent and configure both the Hook and @@ -267,7 +277,7 @@ run with `--keep-data`. | `POWERCONTEXT_CLAUDE_SERVER_URL` | `http://127.0.0.1:8000` | Server base URL used by the Hook | | `POWERCONTEXT_CLAUDE_ALLOW_INSECURE_HTTP` | `false` | Explicitly permit non-loopback plaintext HTTP for PowerContext requests | | `POWERCONTEXT_CLAUDE_SCOPE_ID` | unset | Override durable bindings and the Server default Scope | -| `POWERCONTEXT_CLAUDE_AUTHORIZATION` | unset | Complete `Bearer ` header for Hook and MCP requests | +| `POWERCONTEXT_CLAUDE_AUTHORIZATION` | unset | Complete `Bearer ` header; the Hook prefers it over the credential saved by setup, while MCP uses it only when none is saved | | `POWERCONTEXT_CLAUDE_BOOTSTRAP_CONTEXT` | `false` | Inject the curated bootstrap profile on supported `SessionStart` events | | `POWERCONTEXT_CLAUDE_BOOTSTRAP_MAX_BYTES` | `4096` | Bootstrap package limit; valid values are 512 through 8192 bytes | | `POWERCONTEXT_CLAUDE_BOOTSTRAP_HANDOFF` | unset | JSON identity of one exact committed Handoff, for example `{"artifact_id":"...","revision":3}` | @@ -279,7 +289,8 @@ run with `--keep-data`. `powercontext setup claude-code` stores `server_url` and `capture_prompts` as non-sensitive Claude Code plugin options. The corresponding `POWERCONTEXT_CLAUDE_*` variables take precedence for the process that starts Claude Code. -Authorization is environment-only and must not be added to the Server URL or plugin options. +Authorization comes from the credential saved by setup or from the environment, and must not be added to the Server +URL or plugin options. The outer `UserPromptSubmit` Hook timeout is ten seconds. Recall and capture use one shared wall-clock budget but fail independently. HTTPS certificate validation remains enabled when HTTP is explicitly permitted. Restart Claude Code diff --git a/docs/en/docs/operate/troubleshoot.md b/docs/en/docs/operate/troubleshoot.md index 90f011aac9..432a225aae 100644 --- a/docs/en/docs/operate/troubleshoot.md +++ b/docs/en/docs/operate/troubleshoot.md @@ -402,7 +402,7 @@ contract as Codex, with component `powercontext.claude_code.recall`: | Outcome | Action | | --- | --- | | `empty` | No relevant Memory was prepared; no action is required | -| `authentication_failed` | Export the complete `POWERCONTEXT_CLAUDE_AUTHORIZATION` header before starting Claude Code | +| `authentication_failed` | Rerun setup with the complete `POWERCONTEXT_CLAUDE_AUTHORIZATION` header, or export it before starting Claude Code | | `version_mismatch` | Install the package and plugin from the same ref, then restart both processes | | `server_unavailable` | Start the Server or correct `POWERCONTEXT_CLAUDE_SERVER_URL` | | `invalid_response` | Check for a proxy, redirect, incompatible schema, malformed JSON, or an oversized response; `error_code: scope_not_found` means the configured Scope does not exist or no binding resolves | @@ -413,15 +413,20 @@ the current Scope, so a `scope_resolve` event means that the prompt was neither ## Claude Code MCP authentication fails -The Hook reads `POWERCONTEXT_CLAUDE_AUTHORIZATION` from the environment that starts Claude Code, and the MCP -configuration expands the same value into its `Authorization` header. Stop the current process, export the complete -header, and start it again: +The Hook and the MCP `headersHelper` read the credential that setup saved for the configured `server_url`. The Hook +prefers an explicit `POWERCONTEXT_CLAUDE_AUTHORIZATION` in the environment that starts Claude Code; MCP uses that +value only when no credential is saved for its endpoint, so a token changed only in the environment leaves MCP on the +old saved token. Save the complete header again, then restart Claude Code: ```bash export POWERCONTEXT_CLAUDE_AUTHORIZATION="Bearer $POWERCONTEXT_LOCAL_TOKEN" -claude +powercontext setup claude-code ``` +A saved credential is not sent when the plugin's `server_url` differs from the URL it was saved for, when the file is +malformed, when its POSIX permissions allow group or other access, or when the Server uses non-loopback HTTP; MCP then +sends only the exported value. The helper runs with the `python3` on `PATH`. + Do not add the token to `.mcp.json`, the Server URL, or plugin options. Use `/mcp` after restart to confirm that the `powercontext` Server is connected. diff --git a/docs/zh/docs/integrations/claude-code.md b/docs/zh/docs/integrations/claude-code.md index 582a1a21ad..d3b2a05fa9 100644 --- a/docs/zh/docs/integrations/claude-code.md +++ b/docs/zh/docs/integrations/claude-code.md @@ -67,7 +67,8 @@ claude MCP endpoint 来自 setup 保存的 `server_url`,Hook 可被 `POWERCONTEXT_CLAUDE_SERVER_URL` 覆盖。 修改环境地址后也要用同源 setup 的 `--server-url` 更新持久配置,保证两条路径一致。 -认证使用客户端文件的 `POWERCONTEXT_CLAUDE_AUTHORIZATION`,Hook 与 MCP headersHelper 都需要它。 +setup 会按该 `server_url` 保存客户端的 `POWERCONTEXT_CLAUDE_AUTHORIZATION`;Hook 与 MCP `headersHelper` +都读取它。优先级与轮换方式参见[连接启用认证的 Server](#连接启用认证的-server)。 桌面或其他启动方式可能不继承终端环境,改文件后要重启实际使用的 Claude 进程。 再次执行 setup 会更新插件配置并验证已安装版本,不会删除已有的 PowerContext Server 数据。 @@ -185,15 +186,23 @@ export POWERCONTEXT_SERVER_AUTH_TOKEN="$POWERCONTEXT_LOCAL_TOKEN" powercontext server run ``` -在包含匹配完整 header 的环境中启动 Claude Code: +在包含匹配完整 header 的环境中运行 setup: ```bash export POWERCONTEXT_CLAUDE_AUTHORIZATION="Bearer $POWERCONTEXT_LOCAL_TOKEN" -claude +powercontext setup claude-code ``` -Hook 会直接读取该进程环境变量,MCP 配置则把它展开到 `Authorization` header。变量不存在时,MCP header -使用空值。不要把 token 放入 Server URL、插件选项、`.mcp.json`、Source metadata 或日志。 +setup 会把与 URL 绑定的凭据保存到 `$CLAUDE_CONFIG_DIR/powercontext/credentials.json`(默认为 +`~/.claude/powercontext/credentials.json`)。Hook 读取该记录,插件的 MCP server 则通过 `headersHelper` 读取它; +helper 与 Hook 一样用 `python3` 运行 `scripts/mcp_headers.py`。新会话,包括由桌面版或其他启动方式启动的会话, +都不需要导出 authorization。凭据对应的 endpoint 不同、存储格式错误或 POSIX 权限不安全时,会被拒绝;已保存 +的凭据只用于 HTTPS 或环回 Server。连接非环回 HTTP Server 时,启动 Claude Code 前导出该值。 + +对 Hook 而言,显式的 `POWERCONTEXT_CLAUDE_AUTHORIZATION` 值会覆盖已保存的 authorization,但不会修改它。MCP +只在其 endpoint 没有已保存凭据时才把该值作为静态 header 发送:Claude Code 在运行插件的 `headersHelper` 前会移除 +看起来像凭据的环境变量,因此 MCP 以已保存的凭据为准。轮换 token 时,用新值重新运行 setup;不带 token 重新运行 +setup 会保留已保存的凭据。不要把 token 放入 Server URL、插件选项、`.mcp.json`、Source metadata 或日志。 环回地址默认允许明文 HTTP。连接非环回 Server 时,使用 HTTPS,或显式设置 `POWERCONTEXT_CLAUDE_ALLOW_INSECURE_HTTP=true`。引导安装可以保存该同意,并同时配置 Hook 与原生 MCP 地址; @@ -245,7 +254,7 @@ claude plugin marketplace remove powercontext | `POWERCONTEXT_CLAUDE_SERVER_URL` | `http://127.0.0.1:8000` | Hook 使用的 Server base URL | | `POWERCONTEXT_CLAUDE_ALLOW_INSECURE_HTTP` | `false` | 显式允许 PowerContext 请求使用非环回明文 HTTP | | `POWERCONTEXT_CLAUDE_SCOPE_ID` | 未设置 | 覆盖持久 binding 和 Server 默认 Scope | -| `POWERCONTEXT_CLAUDE_AUTHORIZATION` | 未设置 | Hook 与 MCP 请求使用的完整 `Bearer ` header | +| `POWERCONTEXT_CLAUDE_AUTHORIZATION` | 未设置 | 完整的 `Bearer ` header;Hook 优先使用它而非 setup 保存的凭据,MCP 只在没有已保存凭据时使用它 | | `POWERCONTEXT_CLAUDE_BOOTSTRAP_CONTEXT` | `false` | 在支持的 `SessionStart` 事件中注入精选启动 profile | | `POWERCONTEXT_CLAUDE_BOOTSTRAP_MAX_BYTES` | `4096` | 启动上下文总预算;有效范围为 512 到 8192 bytes | | `POWERCONTEXT_CLAUDE_BOOTSTRAP_HANDOFF` | 未设置 | 一个 exact committed Handoff 的 JSON 身份,例如 `{"artifact_id":"...","revision":3}` | @@ -257,7 +266,7 @@ claude plugin marketplace remove powercontext `powercontext setup claude-code` 会把 `server_url` 和 `capture_prompts` 保存为非敏感的 Claude Code 插件 选项。启动 Claude Code 的进程中,对应的 `POWERCONTEXT_CLAUDE_*` 环境变量优先级更高。 -Authorization 只能来自环境变量,不能加入 Server URL 或插件选项。 +Authorization 来自 setup 保存的凭据或环境变量,不能加入 Server URL 或插件选项。 `UserPromptSubmit` Hook 的外层超时为十秒。召回与采集共用一个 wall-clock 时间预算,但会独立降级。 显式允许 HTTP 不会关闭 HTTPS 证书校验。修改环境变量后需要重启 Claude Code。 diff --git a/docs/zh/docs/operate/troubleshoot.md b/docs/zh/docs/operate/troubleshoot.md index e8b27f5fa3..daa48b320b 100644 --- a/docs/zh/docs/operate/troubleshoot.md +++ b/docs/zh/docs/operate/troubleshoot.md @@ -380,7 +380,7 @@ component 为 `powercontext.claude_code.recall`: | Outcome | 处理方式 | | --- | --- | | `empty` | 没有准备出相关 Memory,无需处理 | -| `authentication_failed` | 启动 Claude Code 前导出完整的 `POWERCONTEXT_CLAUDE_AUTHORIZATION` header | +| `authentication_failed` | 用完整的 `POWERCONTEXT_CLAUDE_AUTHORIZATION` header 重新运行 setup,或在启动 Claude Code 前导出它 | | `version_mismatch` | 从同一个 ref 安装 package 和插件,再重启两个进程 | | `server_unavailable` | 启动 Server,或修正 `POWERCONTEXT_CLAUDE_SERVER_URL` | | `invalid_response` | 检查 proxy、redirect、不兼容 schema、错误 JSON 或超大响应;`error_code: scope_not_found` 表示配置的 Scope 不存在或没有可解析的绑定 | @@ -391,14 +391,18 @@ component 为 `powercontext.claude_code.recall`: ## Claude Code MCP 认证失败 -Hook 从启动 Claude Code 的进程环境读取 `POWERCONTEXT_CLAUDE_AUTHORIZATION`,MCP 配置则把同一个值展开到 -`Authorization` header。停止当前进程,导出完整 header,再重新启动: +Hook 与 MCP `headersHelper` 读取 setup 为已配置 `server_url` 保存的凭据。Hook 优先使用启动 Claude Code 的进程 +环境中显式的 `POWERCONTEXT_CLAUDE_AUTHORIZATION`;MCP 只在其 endpoint 没有已保存凭据时使用该值,因此只在环境中 +修改 token 时,MCP 仍会使用旧的已保存 token。重新保存完整 header,再重启 Claude Code: ```bash export POWERCONTEXT_CLAUDE_AUTHORIZATION="Bearer $POWERCONTEXT_LOCAL_TOKEN" -claude +powercontext setup claude-code ``` +插件的 `server_url` 与保存时的 URL 不同、文件格式错误、POSIX 权限允许 group 或 other 访问,或 Server 使用非环回 +HTTP 时,不会发送已保存的凭据;此时 MCP 只发送导出的值。helper 使用 `PATH` 中的 `python3` 运行。 + 不要把 token 加入 `.mcp.json`、Server URL 或插件选项。重启后使用 `/mcp` 确认 `powercontext` Server 已连接。 ## Pi 没有注入召回上下文 diff --git a/integrations/claude-code/README.md b/integrations/claude-code/README.md index d18238d789..07dea1bc4b 100644 --- a/integrations/claude-code/README.md +++ b/integrations/claude-code/README.md @@ -45,7 +45,8 @@ helper, and exercise explicit Memory and Handoff workflows against public and authenticated Server instances. Contract tests also reject machine-specific Windows paths in the distributed integration files. -The default Server endpoint is `http://127.0.0.1:8000`. Set -`POWERCONTEXT_CLAUDE_AUTHORIZATION` to a complete `Bearer ` value -before starting Claude Code when the Server requires authentication. The MCP -configuration expands this environment variable into its `Authorization` header. +The default Server endpoint is `http://127.0.0.1:8000`. When the Server +requires authentication, set `POWERCONTEXT_CLAUDE_AUTHORIZATION` to a complete +`Bearer ` value before running setup. Setup saves it for that Server, and +both the Hook and the MCP `headersHelper` read the saved value. An explicit +environment value overrides it for the Hook only; rerun setup to rotate it. diff --git a/integrations/claude-code/plugins/powercontext/.claude-plugin/plugin.json b/integrations/claude-code/plugins/powercontext/.claude-plugin/plugin.json index cf061339d3..b27604c8ba 100644 --- a/integrations/claude-code/plugins/powercontext/.claude-plugin/plugin.json +++ b/integrations/claude-code/plugins/powercontext/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "powercontext", - "version": "0.1.3", + "version": "0.1.4", "description": "Restore project memory and transfer current work through PowerContext.", "author": { "name": "PowerContext Team", diff --git a/integrations/claude-code/plugins/powercontext/.mcp.json b/integrations/claude-code/plugins/powercontext/.mcp.json index de8245b6e9..de86c36736 100644 --- a/integrations/claude-code/plugins/powercontext/.mcp.json +++ b/integrations/claude-code/plugins/powercontext/.mcp.json @@ -4,6 +4,7 @@ "url": "${user_config.server_url}/mcp", "headers": { "Authorization": "${POWERCONTEXT_CLAUDE_AUTHORIZATION:-}" - } + }, + "headersHelper": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/mcp_headers.py\"" } } diff --git a/integrations/claude-code/plugins/powercontext/README.md b/integrations/claude-code/plugins/powercontext/README.md index 8c1eefc709..e7d5d8d2e7 100644 --- a/integrations/claude-code/plugins/powercontext/README.md +++ b/integrations/claude-code/plugins/powercontext/README.md @@ -32,10 +32,13 @@ Scope is resolved by the Server from an explicit override, the current session or workspace binding, and finally the Server default. Bindings let multiple agents share the same Scope without deriving identities locally. -The plugin defaults to `http://127.0.0.1:8000`. Its Hook and MCP transport share -`POWERCONTEXT_CLAUDE_AUTHORIZATION` when optional bearer authentication is -enabled. Prompt capture can be disabled through the plugin's `capture_prompts` -option or by setting `POWERCONTEXT_CLAUDE_CAPTURE_PROMPTS=false`. +The plugin defaults to `http://127.0.0.1:8000`. When optional bearer +authentication is enabled, its Hook and its MCP `headersHelper` +(`scripts/mcp_headers.py`) share the credential that setup saves for the +configured Server. `POWERCONTEXT_CLAUDE_AUTHORIZATION` overrides it for the +Hook and reaches MCP only when nothing is saved; rerun setup to rotate it. +Prompt capture can be disabled through the plugin's `capture_prompts` option +or by setting `POWERCONTEXT_CLAUDE_CAPTURE_PROMPTS=false`. HTTPS and loopback HTTP work by default. To persist an explicit non-loopback HTTP endpoint for this host: diff --git a/integrations/claude-code/plugins/powercontext/claude_code_settings.py b/integrations/claude-code/plugins/powercontext/claude_code_settings.py index 2daca616e7..c401f1362e 100644 --- a/integrations/claude-code/plugins/powercontext/claude_code_settings.py +++ b/integrations/claude-code/plugins/powercontext/claude_code_settings.py @@ -275,6 +275,20 @@ def _stored_authorization(*, server_url: str, root: Path) -> str | None: return None +def mcp_authorization(server_url: str) -> str | None: + """Return the credential that setup saved for the MCP endpoint `server_url`, if any. + + Only a credential saved for this same Server is returned, so a token is never sent to another endpoint. The + environment is not consulted: Claude Code removes credential-like variables before it runs a plugin's + `headersHelper`, so `POWERCONTEXT_CLAUDE_AUTHORIZATION` reaches MCP only through the static header. + """ + + return _stored_authorization( + server_url=server_url, + root=Path(os.environ.get("CLAUDE_CONFIG_DIR", Path.home() / ".claude")).expanduser(), + ) + + def _http_base_url(value: str, *, allow_insecure_http: bool = False) -> str: normalized = value.strip().rstrip("/") parsed = urlsplit(normalized) @@ -302,4 +316,4 @@ def _http_base_url(value: str, *, allow_insecure_http: bool = False) -> str: return urlunsplit((scheme, netloc, path, "", "")).rstrip("/") -__all__ = ["BootstrapHandoff", "ClaudeCodePluginSettings"] +__all__ = ["BootstrapHandoff", "ClaudeCodePluginSettings", "mcp_authorization"] diff --git a/integrations/claude-code/plugins/powercontext/hooks/session_start.py b/integrations/claude-code/plugins/powercontext/hooks/session_start.py index 2ce270cd72..5437c12505 100644 --- a/integrations/claude-code/plugins/powercontext/hooks/session_start.py +++ b/integrations/claude-code/plugins/powercontext/hooks/session_start.py @@ -66,7 +66,7 @@ _REQUEST_HEADERS = { "Accept": "application/json", "Content-Type": "application/json", - "User-Agent": "powercontext-claude-code-plugin/0.1.3", + "User-Agent": "powercontext-claude-code-plugin/0.1.4", } diff --git a/integrations/claude-code/plugins/powercontext/hooks/user_prompt_submit.py b/integrations/claude-code/plugins/powercontext/hooks/user_prompt_submit.py index aaee2f622b..511008f450 100644 --- a/integrations/claude-code/plugins/powercontext/hooks/user_prompt_submit.py +++ b/integrations/claude-code/plugins/powercontext/hooks/user_prompt_submit.py @@ -57,7 +57,7 @@ "X-PowerContext-Dream-Contract": "2", "Accept": "application/json", "Content-Type": "application/json", - "User-Agent": "powercontext-claude-code-plugin/0.1.3", + "User-Agent": "powercontext-claude-code-plugin/0.1.4", } _FAILURE_OUTCOMES = frozenset({"authentication_failed", "version_mismatch", "server_unavailable", "invalid_response"}) diff --git a/integrations/claude-code/plugins/powercontext/scripts/mcp_headers.py b/integrations/claude-code/plugins/powercontext/scripts/mcp_headers.py new file mode 100644 index 0000000000..5ee25f09a5 --- /dev/null +++ b/integrations/claude-code/plugins/powercontext/scripts/mcp_headers.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Emit the Authorization header that setup saved for the endpoint Claude Code connects to. + +Claude Code runs this as the plugin MCP server's `headersHelper` and passes the endpoint in +`CLAUDE_CODE_MCP_SERVER_URL`. The emitted header overrides the static one. When nothing is saved for that endpoint, or +on any failure, no header is emitted and the static `POWERCONTEXT_CLAUDE_AUTHORIZATION` header still applies. +""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + + +def main() -> int: + try: + from claude_code_settings import mcp_authorization + + authorization = mcp_authorization(os.environ.get("CLAUDE_CODE_MCP_SERVER_URL", "")) + except Exception: + authorization = None + json.dump({} if authorization is None else {"Authorization": authorization}, sys.stdout, separators=(",", ":")) + sys.stdout.write("\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py b/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py index b119cd5194..626e4196eb 100644 --- a/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py +++ b/integrations/claude-code/plugins/powercontext/scripts/workspace_scope.py @@ -58,7 +58,7 @@ def override(method: _MethodT, /) -> _MethodT: _REQUEST_HEADERS = { "Accept": "application/json", "Content-Type": "application/json", - "User-Agent": "powercontext-claude-code-plugin/0.1.3", + "User-Agent": "powercontext-claude-code-plugin/0.1.4", } diff --git a/tests/claude_code_plugin/test_contract.py b/tests/claude_code_plugin/test_contract.py index 46ac11abf1..c91473b57d 100644 --- a/tests/claude_code_plugin/test_contract.py +++ b/tests/claude_code_plugin/test_contract.py @@ -15,7 +15,11 @@ from __future__ import annotations import json +import os import re +import shutil +import subprocess +import sys from pathlib import Path from types import ModuleType from typing import Any, cast @@ -37,7 +41,7 @@ def test_repository_exposes_a_claude_marketplace() -> None: "name": "powercontext", "source": "./integrations/claude-code/plugins/powercontext", "description": "Restore project memory and transfer current work from Claude Code", - "version": "0.1.3", + "version": "0.1.4", "category": "Productivity", } ] @@ -47,7 +51,7 @@ def test_plugin_uses_standard_component_discovery() -> None: manifest = json.loads((PLUGIN_ROOT / ".claude-plugin" / "plugin.json").read_text()) assert manifest["name"] == "powercontext" - assert manifest["version"] == "0.1.3" + assert manifest["version"] == "0.1.4" assert "hooks" not in manifest assert "mcpServers" not in manifest assert (PLUGIN_ROOT / "hooks" / "hooks.json").is_file() @@ -69,17 +73,84 @@ def test_hook_uses_exec_form_and_does_not_capture_stop() -> None: assert hook["args"] == ["${CLAUDE_PLUGIN_ROOT}/hooks/user_prompt_submit.py"] -def test_mcp_uses_claude_top_level_server_map_and_environment_header() -> None: +def test_mcp_uses_claude_top_level_server_map_and_authorization_headers() -> None: configuration = json.loads((PLUGIN_ROOT / ".mcp.json").read_text()) assert set(configuration) == {"powercontext"} + # The helper's header overrides the static one; a host that cannot run the helper still sends the environment value. assert configuration["powercontext"] == { "type": "http", "url": "${user_config.server_url}/mcp", "headers": {"Authorization": "${POWERCONTEXT_CLAUDE_AUTHORIZATION:-}"}, + "headersHelper": 'python3 "${CLAUDE_PLUGIN_ROOT}/scripts/mcp_headers.py"', } +def _mcp_headers(root: Path, *, mcp_url: str | None, authorization: str | None = None) -> dict[str, str]: + environment = { + name: value for name, value in os.environ.items() if not name.startswith(("CLAUDE_", "POWERCONTEXT_")) + } + environment.update(HOME=str(root), CLAUDE_CONFIG_DIR=str(root)) + if mcp_url is not None: + environment["CLAUDE_CODE_MCP_SERVER_URL"] = mcp_url + if authorization is not None: + environment["POWERCONTEXT_CLAUDE_AUTHORIZATION"] = authorization + # -S leaves out site-packages, as for the hooks: the helper may import only the standard library. + result = subprocess.run( + [sys.executable, "-S", str(PLUGIN_ROOT / "scripts" / "mcp_headers.py")], + env=environment, + capture_output=True, + text=True, + timeout=30, + check=True, + ) + return json.loads(result.stdout) + + +@pytest.mark.parametrize( + ("mcp_url", "authorization", "expected"), + [ + # Setup's saved credential is sent to the Server it was saved for. + ("http://127.0.0.1:8000/mcp", None, {"Authorization": "Bearer saved-token"}), + # A token is never sent to another endpoint. + ("https://memory.example/mcp", None, {}), + # Claude Code may strip credential-like variables from the helper, so the helper never reads the environment; + # the saved credential overrides the static environment header. + ("http://127.0.0.1:8000/mcp", "Bearer environment-token", {"Authorization": "Bearer saved-token"}), + # Without the endpoint, the helper cannot match a saved credential. + (None, None, {}), + ], +) +def test_mcp_headers_helper_sends_only_the_credential_for_its_endpoint( + tmp_path: Path, mcp_url: str | None, authorization: str | None, expected: dict[str, str] +) -> None: + _write_credentials(tmp_path, server_url="http://127.0.0.1:8000", authorization="Bearer saved-token") + + assert _mcp_headers(tmp_path, mcp_url=mcp_url, authorization=authorization) == expected + + +@pytest.mark.skipif(sys.platform == "win32", reason="the shell command is checked with a POSIX shell") +def test_mcp_headers_helper_command_runs_from_a_plugin_root_with_spaces(tmp_path: Path) -> None: + configuration = json.loads((PLUGIN_ROOT / ".mcp.json").read_text()) + root = tmp_path / "Application Support" / "powercontext" + shutil.copytree(PLUGIN_ROOT, root) + _write_credentials(tmp_path, server_url="http://127.0.0.1:8000", authorization="Bearer saved-token") + environment = { + name: value for name, value in os.environ.items() if not name.startswith(("CLAUDE_", "POWERCONTEXT_")) + } + environment.update( + HOME=str(tmp_path), CLAUDE_CONFIG_DIR=str(tmp_path), CLAUDE_CODE_MCP_SERVER_URL="http://127.0.0.1:8000/mcp" + ) + # Claude Code substitutes the raw plugin root into the command and runs it through a shell. + command = configuration["powercontext"]["headersHelper"].replace("${CLAUDE_PLUGIN_ROOT}", str(root)) + + result = subprocess.run( # noqa: S602 - the command is the plugin's own shipped helper. + command, shell=True, env=environment, capture_output=True, text=True, timeout=30, check=True + ) + + assert json.loads(result.stdout) == {"Authorization": "Bearer saved-token"} + + def test_scope_resolver_and_workspace_binding_use_the_server( scope_module: ModuleType, monkeypatch: pytest.MonkeyPatch, diff --git a/tests/claude_code_plugin/test_python_floor.py b/tests/claude_code_plugin/test_python_floor.py index 00db60a457..721d8e4e28 100644 --- a/tests/claude_code_plugin/test_python_floor.py +++ b/tests/claude_code_plugin/test_python_floor.py @@ -340,3 +340,24 @@ def test_statusline_shows_token_savings_on_python_3_9( assert "PC online" in output assert "saved 1.2k today" in output + + +def test_mcp_headers_helper_emits_the_saved_credential_on_python_3_9(python_floor: str, tmp_path: Path) -> None: + credential = tmp_path / "claude" / "powercontext" / "credentials.json" + credential.parent.mkdir(parents=True) + credential.write_text( + json.dumps({"version": 1, "server_url": "http://127.0.0.1:8000", "authorization": "Bearer saved-token"}), + encoding="utf-8", + ) + credential.chmod(0o600) + + output = _run( + python_floor, + "scripts/mcp_headers.py", + {}, + server_url="http://127.0.0.1:8000", + home=tmp_path, + settings={"CLAUDE_CODE_MCP_SERVER_URL": "http://127.0.0.1:8000/mcp"}, + ) + + assert json.loads(output) == {"Authorization": "Bearer saved-token"}