diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d64ebaa..1312dd4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,3 +15,10 @@ jobs: run: sudo apt-get update && sudo apt-get install -y jq - name: Run release checks run: make release-check + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Install Codex for MCP launch regression + run: npm install --prefix "$RUNNER_TEMP/codex" @openai/codex@0.159.2 + - name: Test packaged MCP launch through Codex + run: make test-integration CODEX_TEST_BINARY="$RUNNER_TEMP/codex/node_modules/.bin/codex" diff --git a/Makefile b/Makefile index 9a1c92d..73c7a55 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,13 @@ -.PHONY: all test lint lint-json lint-policy diff-check release-check clean +.PHONY: all test test-integration lint lint-json lint-policy diff-check release-check clean all: lint test test: @tests/package-policy.sh + @python3 tests/mcp-contract.py plugins/gitkb + +test-integration: + @python3 tests/mcp-startup.py --codex "$(CODEX_TEST_BINARY)" lint: lint-json lint-policy @echo "All checks passed." diff --git a/README.md b/README.md index 6e80727..c4f09a1 100644 --- a/README.md +++ b/README.md @@ -32,3 +32,19 @@ codex plugin add gitkb@gitkb ## License MIT + +## MCP Launch Regression Tests + +`make test` checks the packaged environment allowlist and cache version. The +installation test exercises the actual Codex MCP launch boundary with synthetic +sessions, custom registry settings, paths with spaces and Unicode, and credential +canaries. It reuses an isolated plugin installation across two sessions and a +launch without activity context. It does not start a model turn or run an activity +sink, and it does not use your Codex home or credentials. + +```bash +make test-integration CODEX_TEST_BINARY=/absolute/path/to/provider/codex +``` + +Pass the provider binary, rather than an ATC shim. CI runs this test with Codex +`0.159.2`, in addition to the release checks. diff --git a/plugins/gitkb/.codex-plugin/plugin.json b/plugins/gitkb/.codex-plugin/plugin.json index e62169d..feb0065 100644 --- a/plugins/gitkb/.codex-plugin/plugin.json +++ b/plugins/gitkb/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "gitkb", - "version": "0.1.1", + "version": "0.1.2", "description": "Codex hooks, skills, and MCP config for GitKB code-intelligence guidance.", "author": { "name": "GitKB", diff --git a/plugins/gitkb/.mcp.json b/plugins/gitkb/.mcp.json index 83b7782..6c0cc04 100644 --- a/plugins/gitkb/.mcp.json +++ b/plugins/gitkb/.mcp.json @@ -11,7 +11,9 @@ "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", "SESSION_ACTIVITY_SINK_COMMAND", - "SESSION_ACTIVITY_SINK_ARGS_JSON" + "SESSION_ACTIVITY_SINK_ARGS_JSON", + "ATC_ROOT", + "ATC_CONFIG" ] } } diff --git a/plugins/gitkb/README.md b/plugins/gitkb/README.md index efe2468..1b0e7d7 100644 --- a/plugins/gitkb/README.md +++ b/plugins/gitkb/README.md @@ -54,9 +54,27 @@ git-kb init codex - one focused code-intelligence skill; - Codex lifecycle hooks that call `git-kb hook codex`; - MCP configuration for `git-kb mcp`; -- no external harness-specific behavior; +- inherited session activity context for the MCP process; - no vendored copy of the full canonical `git-kb init codex` skill set. +## ATC Session Activity + +When Codex runs through an ATC shim, the plugin forwards the parent's six +`SESSION_ACTIVITY_*` settings to `git-kb mcp`. It also forwards `ATC_ROOT` and +`ATC_CONFIG` when set, so the activity sink uses the same registry as the shim. +Codex filters the MCP environment; installing a newer `git-kb` or `atc` binary +alone does not update this plugin launch configuration. + +Install the updated plugin (`0.1.2`) from your marketplace and restart or resume +Codex through the ATC shim to start a new MCP process. Existing MCP processes keep +the environment with which they started. Previously omitted activity records +are not backfilled by this update. + +The configuration forwards variable names rather than fixed session values. +Without parent activity context, GitKB keeps its normal behavior. The plugin does +not forward API credentials, generic provider thread IDs, or a global ATC session +ID as a substitute for the activity contract. + ## Documentation - [Getting Started](https://gitkb.com/docs/getting-started/quick-start/) diff --git a/tests/mcp-contract.py b/tests/mcp-contract.py new file mode 100644 index 0000000..02f70d4 --- /dev/null +++ b/tests/mcp-contract.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Guard the packaged MCP launch contract, including its credential boundary.""" +import json +import sys +import unittest +from pathlib import Path + +FORWARDED = { + "SESSION_ACTIVITY_RESOURCE_ID", "SESSION_ACTIVITY_RESOURCE_KIND", + "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", + "SESSION_ACTIVITY_SINK_COMMAND", "SESSION_ACTIVITY_SINK_ARGS_JSON", + "ATC_ROOT", "ATC_CONFIG", +} +PLUGIN_ROOT = Path(sys.argv.pop(1)) + + +class LaunchContract(unittest.TestCase): + def test_parent_context_is_forwarded_by_name_only(self): + """Require the activity/registry allowlist while rejecting fixed environment values.""" + config = json.loads((PLUGIN_ROOT / ".mcp.json").read_text()) + self.assertEqual(set(config["mcpServers"]), {"gitkb"}) + server = config["mcpServers"]["gitkb"] + names = server["env_vars"] + self.assertIsInstance(names, list) + self.assertTrue(all(isinstance(name, str) for name in names)) + self.assertEqual(set(names), FORWARDED) + self.assertEqual(len(names), len(FORWARDED), "duplicate forwarding names") + self.assertNotIn("env", server, "do not bake session identity into the plugin") + self.assertEqual(server["command"], "git-kb") + self.assertEqual(server["args"], ["mcp"]) + + def test_cache_version_changes_with_launch_contract(self): + """Ensure the installable version cannot reuse either pre-fix cache entry.""" + manifest = json.loads((PLUGIN_ROOT / ".codex-plugin/plugin.json").read_text()) + version = tuple(int(part) for part in manifest["version"].split(".")) + self.assertEqual(len(version), 3) + self.assertGreaterEqual(version, (0, 1, 2), "old cache versions lack this contract") + self.assertEqual(manifest["mcpServers"], "./.mcp.json") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/mcp-startup.py b/tests/mcp-startup.py new file mode 100644 index 0000000..e04426a --- /dev/null +++ b/tests/mcp-startup.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Install the real package in an isolated Codex home and inspect its MCP child. + +Uses only initialize and mcpServerStatus/list; never starts a thread or model turn. +The fake GitKB server captures synthetic context without running an activity sink. +""" +import argparse +import json +import os +import selectors +import shlex +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +NAMES = ( + "SESSION_ACTIVITY_RESOURCE_ID", "SESSION_ACTIVITY_RESOURCE_KIND", + "SESSION_ACTIVITY_PROVIDER", "SESSION_ACTIVITY_CONTEXT_FILE", + "SESSION_ACTIVITY_SINK_COMMAND", "SESSION_ACTIVITY_SINK_ARGS_JSON", + "ATC_ROOT", "ATC_CONFIG", +) +FORBIDDEN = ("MCP_ENV_UNRELATED_SECRET", "OPENAI_API_KEY", "ATC_SESSION_ID", "CODEX_THREAD_ID") + + +def run(codex, args, env, cwd): + """Run a bounded plugin installation command with only the fixture environment.""" + result = subprocess.run([codex, *args], env=env, cwd=cwd, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30) + if result.returncode: + raise AssertionError(f"Codex {args} failed: {result.stdout} {result.stderr}") + + +def inspect_child(codex, env, root, capture): + """Negotiate packaged MCP tools, capture context, and clean up the owned process group.""" + capture.unlink(missing_ok=True) + with (root / "stderr.log").open("w+") as stderr: + process = subprocess.Popen([codex, "app-server"], env=env, cwd=root, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=stderr, start_new_session=True) + selector = selectors.DefaultSelector() + selector.register(process.stdout, selectors.EVENT_READ) + pending = bytearray() + + def send(message): + """Write one newline-delimited app-server request or notification.""" + process.stdin.write((json.dumps(message) + "\n").encode()) + process.stdin.flush() + + def response(request_id): + """Read the matching reply with a deadline, ignoring asynchronous notifications.""" + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + while b"\n" in pending: + line, _, rest = pending.partition(b"\n") + pending[:] = rest + message = json.loads(line) + if message.get("id") == request_id: + if "error" in message: + raise AssertionError(message["error"]) + return message["result"] + if selector.select(timeout=0.1): + chunk = os.read(process.stdout.fileno(), 65536) + if not chunk: + break + pending.extend(chunk) + stderr.flush() + stderr.seek(0) + raise AssertionError(f"No response to {request_id}: {stderr.read()[-4000:]}") + + try: + send({"id": 1, "method": "initialize", "params": { + "clientInfo": {"name": "gitkb-package-test", "version": "1"}, + "capabilities": {"experimentalApi": True}}}) + response(1) + send({"method": "initialized"}) + send({"id": 2, "method": "mcpServerStatus/list", "params": {}}) + servers = response(2)["data"] + server = next(item for item in servers if item["name"] == "gitkb") + assert server["pluginId"] == "gitkb@gitkb", server + assert "context_probe" in server["tools"], server + assert capture.exists(), "packaged MCP child did not start" + return json.loads(capture.read_text()) + finally: + selector.close() + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + process.stdin.close() + process.stdout.close() + + +def main(): + """Verify session isolation and the credential boundary through a real package install.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--codex", required=True, help="Provider Codex binary, not an ATC shim") + parser.add_argument("--marketplace", default=".") + args = parser.parse_args() + codex = shutil.which(args.codex) + if not codex: + parser.error("Codex binary not found") + codex = str(Path(codex).resolve()) + marketplace = str(Path(args.marketplace).resolve()) + with tempfile.TemporaryDirectory(prefix="gitkb-mcp-context-") as directory: + root = Path(directory) + (root / "bin").mkdir() + (root / "codex").mkdir() + capture = root / "context.json" + fixture = root / "mcp_fixture.py" + fixture.write_text('''import json, os, sys +if sys.argv[1:] != ["mcp"]: + sys.exit(0) +''' + f"names = {NAMES + FORBIDDEN!r}\n" + + f"with open({str(capture)!r}, 'w') as output:\n" + + " json.dump({name: os.environ[name] for name in names if name in os.environ}, output)\n" + '''for line in sys.stdin: + message = json.loads(line) + if "id" not in message: + continue + method = message["method"] + if method == "initialize": + result = {"protocolVersion": message["params"]["protocolVersion"], + "capabilities": {"tools": {}}, "serverInfo": {"name": "gitkb-fixture", "version": "1"}} + elif method == "tools/list": + result = {"tools": [{"name": "context_probe", "description": "Launch boundary probe", + "inputSchema": {"type": "object", "properties": {}}}]} + elif method == "resources/list": + result = {"resources": []} + elif method == "resources/templates/list": + result = {"resourceTemplates": []} + else: + print(json.dumps({"jsonrpc": "2.0", "id": message["id"], + "error": {"code": -32601, "message": "Method not found"}}), flush=True) + continue + print(json.dumps({"jsonrpc": "2.0", "id": message["id"], "result": result}), flush=True) +''') + shim = root / "bin/git-kb" + shim.write_text(f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(fixture))} \"$@\"\n") + shim.chmod(0o755) + # Construct the environment: never inherit the developer's keys, session or home. + base_env = {"HOME": directory, "CODEX_HOME": str(root / "codex"), + "PATH": str(root / "bin") + os.pathsep + os.defpath, + "TMPDIR": directory} + node = shutil.which("node") + if node: + # npm Codex launchers use /usr/bin/env node; keep that interpreter reachable. + base_env["PATH"] += os.pathsep + str(Path(node).parent) + run(codex, ["plugin", "marketplace", "add", marketplace, "--json"], base_env, root) + run(codex, ["plugin", "add", "gitkb@gitkb", "--json"], base_env, root) + for session in ("alpha", "beta", None): + expected = {} if session is None else dict(zip(NAMES, ( + f"xses-{session}", "external", "codex", + str(root / f"{session} path 'quoted' ΓΌ.json"), + str(root / "sink path"), json.dumps(["activity", "record", "--json"]), + str(root / f"{session} registry"), str(root / f"{session} config.toml")))) + env = dict(base_env, **expected, **{name: "synthetic-canary" for name in FORBIDDEN}) + observed = inspect_child(codex, env, root, capture) + assert observed == expected, f"{session or 'unshimmed'}: expected {expected}, got {observed}" + print(f"PASS: {session or 'unshimmed'} MCP context and credential isolation") + + +if __name__ == "__main__": + main()