Skip to content

Commit 93d0f38

Browse files
authored
Feat/automatic agent context apm setup (#74)
* feat(agent-context): install user-scoped APM skills and fix cached MCP queries * chore(release): prepare v0.2.8 metadata * fix(opencode): write V2 mcp.servers format and migrate V1 entries OpenCode V2 silently ignores servers defined directly under `mcp` instead of `mcp.servers` (anomalyco/opencode#56602). The global config is also invisible to `mcp list` (#55811). Migrate the registration to write `mcp.servers.<name>` and remove any leftover V1 flat entry during container creation.
1 parent 5dc5d2a commit 93d0f38

30 files changed

Lines changed: 540 additions & 90 deletions

File tree

‎.github/workflows/test-feature.yaml‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,25 +86,38 @@ jobs:
8686
echo "CONSUMER_WORKSPACE=${workspace}" >> "$GITHUB_ENV"
8787
mkdir -p "$workspace/.devcontainer/features"
8888
cp -R features/src/agent-context "$workspace/.devcontainer/features/"
89-
cp features/test/agent-context/test.sh "$workspace/test.sh"
89+
cp features/test/agent-context/test.sh \
90+
features/test/agent-context/test_apm_setup.sh \
91+
features/test/agent-context/test_container_setup.sh \
92+
features/test/agent-context/seed_mcp_config.sh "$workspace/"
9093
node - "$workspace" <<'JS'
9194
const fs = require('fs');
9295
const path = require('path');
96+
const workspace = process.argv[2];
9397
const config = {
9498
image: 'mcr.microsoft.com/devcontainers/javascript-node:4-24',
9599
remoteUser: 'node',
96100
features: { './features/agent-context': {} },
97-
postCreateCommand: 'touch "$HOME/.claude.json" && python3 /usr/local/share/agent-context/register_mcp.py',
101+
containerEnv: {
102+
AGENT_CONTEXT_APM_PACKAGE_ROOT: '/tmp/agent-context-apm-packages',
103+
VSCODE_AGENT_FOLDER: '/home/node/.vscode-server',
104+
},
105+
onCreateCommand: 'bash seed_mcp_config.sh',
98106
};
99-
fs.writeFileSync(path.join(process.argv[2], '.devcontainer/devcontainer.json'), JSON.stringify(config));
107+
fs.writeFileSync(
108+
path.join(workspace, '.devcontainer/devcontainer.json'),
109+
JSON.stringify(config),
110+
);
100111
JS
101-
devcontainer up --workspace-folder "$workspace"
112+
devcontainer up --workspace-folder "$workspace" \
113+
--update-remote-user-uid-default never \
114+
--mount "type=bind,source=${GITHUB_WORKSPACE}/packages,target=/tmp/agent-context-apm-packages"
102115
103116
- name: Verify installed server and registration as remote user
104117
run: |
105118
devcontainer exec --workspace-folder "$CONSUMER_WORKSPACE" bash test.sh
106-
devcontainer exec --workspace-folder "$CONSUMER_WORKSPACE" \
107-
bash -euc 'uv --version; python3 -c '\''import json, os; from pathlib import Path; config = json.loads((Path.home() / ".claude.json").read_text()); command = config["mcpServers"]["score-codegraph"]["command"]; assert os.access(command, os.X_OK), command'\'''
119+
devcontainer exec --workspace-folder "$CONSUMER_WORKSPACE" bash test_container_setup.sh
120+
devcontainer exec --workspace-folder "$CONSUMER_WORKSPACE" bash test_apm_setup.sh
108121
- name: Remove consumer container
109122
if: always()
110123
run: |

‎apm.yml‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# *******************************************************************************
1313

1414
name: eclipse-score-apm-marketplace
15-
version: 0.2.3
15+
version: 0.2.8
1616
description: Eclipse S-CORE Agent Context Attention Layer packages
1717
license: Apache-2.0
1818
marketplace:
@@ -42,27 +42,27 @@ marketplace:
4242
- name: apm-setup
4343
description: Central setup MCP server for local APM package state.
4444
source: ./packages/apm-setup
45-
version: "0.2.3"
45+
version: "0.2.8"
4646
category: Productivity
4747
- name: context-discipline
4848
description: Context discipline package for working memory management and local learning orchestration. Integrates graphify (external) for code structure queries.
4949
source: ./packages/context-discipline
50-
version: "0.2.3"
50+
version: "0.2.8"
5151
category: Productivity
5252
- name: graphify-codegraph
5353
description: Graphify package for code structure queries. Integrates graphify (external) for code structure queries.
5454
source: ./packages/graphify-codegraph
55-
version: "0.2.3"
55+
version: "0.2.8"
5656
category: Productivity
5757
- name: sdlc-harness
5858
description: Traceable SDLC lifecycle, implementation evidence, and progress reporting tooling for AI agents.
5959
source: ./packages/sdlc-harness
60-
version: "0.2.3"
60+
version: "0.2.8"
6161
category: Productivity
6262
- name: metamodel-flow
6363
description: Normative S-CORE artifact model guidance generated from the docs-as-code metamodel.
6464
source: ./packages/metamodel-flow
65-
version: "0.2.3"
65+
version: "0.2.8"
6666
category: Productivity
6767

6868

‎features/src/agent-context/README.md‎

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
# agent-context devcontainer feature
55

66
Installs the pinned `graphify-codegraph` MCP server and registers it for the coding
7-
agents found in the container (Claude Code, Copilot CLI, opencode, Codex). The
8-
repository needs no change; the graph is built or downloaded on first use, see
7+
agents found in the container (VS Code Copilot Chat, Claude Code, OpenCode, Codex).
8+
The repository needs no change; the graph is built or downloaded on first use, see
99
[graphify-codegraph](../../../packages/graphify-codegraph/README.md).
1010

1111
The feature also exposes the pinned Graphify CLI on `PATH`. Run `graphify --help` to get available commands like `graphify benchmark`.
@@ -24,18 +24,45 @@ On Debian/Ubuntu images, the feature installs missing Python, Git, curl, and
2424
a shared system location so non-root remote users can run it. The feature is
2525
published by the `Release` workflow together with each release.
2626

27+
## APM and VS Code Copilot
28+
29+
Container creation installs the pinned APM CLI (`0.35.0`) and the
30+
`graphify-codegraph` and `apm-setup` packages for the user-level `agent-skills`
31+
target. Their shared skills are stored in `~/.agents/skills/`; APM state stays
32+
under `~/.apm/`. No APM manifest, lockfile, or generated instructions are
33+
written into the consumer checkout.
34+
35+
APM 0.35.0 requires Git 2.26 or newer for its Git URL-rewrite safety check.
36+
The feature reports a clear error rather than proceeding if the existing Git is
37+
older.
38+
39+
The MCP servers are registered in the VS Code user-profile `mcp.json`, normally
40+
`~/.vscode-server/data/User/mcp.json`. Existing servers and other configuration
41+
are preserved. Set `VSCODE_AGENT_FOLDER` when the remote server uses a
42+
non-default location. Existing profile-specific MCP files are updated as well.
43+
44+
Here, Copilot means **VS Code Copilot Chat**. APM's global `--target copilot`
45+
path is partial and writes Copilot CLI configuration; it is not the VS Code
46+
Chat user-profile MCP config. The feature uses APM's cross-tool skills target
47+
and separately registers the MCP servers using VS Code's supported user-profile
48+
configuration. It does not infer that Copilot CLI is installed from a `copilot`
49+
command on `PATH`.
50+
51+
The APM package source defaults to the repository's `main` ref. Set
52+
`AGENT_CONTEXT_APM_REF` to a branch, tag, or commit to use another revision.
53+
2754
## Consumer Repository Files
2855

2956
Automatic graph preparation stores downloaded or built graphs under `~/.local/share/score-agent/` by default, outside the consumer repository.
3057
Published graphs take precedence over existing local graphs and are served without immediate local regeneration, even when the nightly revision differs from checkout HEAD.
3158
The resolver rechecks the registry daily, keeps usable cached graphs when offline, and builds locally only when no graph is available or `force_local` is explicitly requested.
32-
Installing this feature alone does not deploy APM instructions, skills, hooks, or project manifests.
59+
Installing this feature deploys APM skills to user scope; it does not create
60+
APM instructions, skills, hooks, or manifests in the consumer repository.
3361

34-
APM installation and graph/context setup remain available; their generated outputs should be placed outside the consumer checkout rather than disabling these workflows.
62+
Graph/context setup remains available; generated outputs stay outside the
63+
consumer checkout rather than disabling these workflows.
3564
Context-discipline sessions, observations, and agent salts default to repository-keyed user state under `$XDG_STATE_HOME/score-agent/` or `~/.local/state/score-agent/`; `.score-local/` requires an explicit runtime storage override.
3665
The setup MCP generates graphs in the same user cache as the graph runtime and prepares the same user state as the context runtime without modifying consumer ignore rules.
37-
APM supports `install --root DIR` and `compile --root DIR` for redirected output, or `install --global` and `compile --global` for supported user-scoped harness deployment.
38-
Keep relocated instructions, skills, hooks, and MCP configuration discoverable through supported harness configuration; writing them into a cache alone does not register them.
3966
See [APM's installation destinations](https://microsoft.github.io/apm/consumer/install-packages/#where-files-land).
4067
This README is documentation, not an instruction automatically loaded by coding agents; reusable agent guidance is shipped through the APM packages.
4168
Existing consumer artifacts are not automatically deleted or migrated by this change.
@@ -51,3 +78,6 @@ npx --yes @devcontainers/[email protected] features test --project-folder features -f a
5178
CI tests AMD64 and ARM64 installations and a non-root consumer devcontainer.
5279
The tests require a successful MCP initialization and tool listing, not just
5380
the presence of an executable.
81+
The consumer test also verifies the pinned APM CLI, user-scoped skills, VS Code
82+
user MCP registration, preservation of existing MCP config, and a clean
83+
consumer checkout.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
22
"id": "agent-context",
3-
"version": "0.2.3",
3+
"version": "0.2.8",
44
"name": "S-CORE agent context",
55
"description": "Registers the S-CORE code graph MCP server for the coding agents in the container.",
66
"documentationURL": "https://github.com/eclipse-score/mcp-servers/tree/main/features/src/agent-context",
77
"licenseURL": "https://github.com/eclipse-score/mcp-servers/blob/main/LICENSE",
8-
"postCreateCommand": "python3 /usr/local/share/agent-context/register_mcp.py"
8+
"postCreateCommand": "bash /usr/local/share/agent-context/setup_apm.sh"
99
}

‎features/src/agent-context/install.sh‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
# *******************************************************************************
1414
set -euo pipefail
1515

16-
SOURCE=git+https://github.com/eclipse-score/mcp-servers@a85a027acff417ef2718c07daf62491e98cdb4fd#subdirectory=packages/graphify-codegraph # v0.2.3
16+
SOURCE=git+https://github.com/eclipse-score/mcp-servers@0df389d81bf6e4c0d4f532513312edfe8fb4edab#subdirectory=packages/graphify-codegraph # v0.2.8
17+
APM_VERSION=0.35.0
1718
SHARE=/usr/local/share/agent-context
1819

1920
if ! command -v python3 >/dev/null 2>&1 || \
@@ -38,8 +39,14 @@ fi
3839

3940
install -d -m 0755 "${SHARE}"
4041
install -m 0644 "$(dirname "$0")/register_mcp.py" "${SHARE}/register_mcp.py"
42+
install -m 0644 "$(dirname "$0")/setup_apm.sh" "${SHARE}/setup_apm.sh"
4143
UV_TOOL_DIR="${SHARE}/tools" \
4244
UV_TOOL_BIN_DIR=/usr/local/bin \
4345
UV_PYTHON_INSTALL_DIR="${SHARE}/python" \
4446
"${UV}" tool install --python 3.12 --force \
4547
--with-executables-from graphifyy "${SOURCE}"
48+
UV_TOOL_DIR="${SHARE}/tools" \
49+
UV_TOOL_BIN_DIR=/usr/local/bin \
50+
UV_PYTHON_INSTALL_DIR="${SHARE}/python" \
51+
"${UV}" tool install --python 3.12 --force \
52+
"apm-cli==${APM_VERSION}"

‎features/src/agent-context/register_mcp.py‎

Lines changed: 110 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
#!/usr/bin/env python3
22
# SPDX-License-Identifier: Apache-2.0
33
# Copyright (c) 2026 Contributors to the Eclipse Foundation
4-
"""Register the S-CORE code graph MCP server for the coding agents in this container.
5-
6-
Only the ``score-codegraph`` entry is added or updated, other settings are kept.
7-
Configs that cannot be parsed are left untouched. Never fails container creation.
8-
"""
4+
"""Register agent-context MCP servers while preserving existing client config."""
95

106
import json
7+
import os
118
import shutil
129
import sys
1310
from collections.abc import Callable
@@ -23,6 +20,15 @@ def warn(message: str) -> None:
2320

2421

2522
def update_json(path: Path, key: str, entry: dict[str, Any]) -> bool:
23+
return update_json_mapping(path, key, {NAME: entry})
24+
25+
26+
def update_json_mapping(
27+
path: Path,
28+
key: str,
29+
entries: dict[str, dict[str, Any]],
30+
remove_keys: tuple[str, ...] = (),
31+
) -> bool:
2632
data: Any = {}
2733
if path.exists():
2834
try:
@@ -40,7 +46,9 @@ def update_json(path: Path, key: str, entry: dict[str, Any]) -> bool:
4046
if not isinstance(servers, dict):
4147
warn(f"skipping {path}: {key} is not a mapping")
4248
return False
43-
servers[NAME] = entry
49+
for name in remove_keys:
50+
servers.pop(name, None)
51+
servers.update(entries)
4452
path.parent.mkdir(parents=True, exist_ok=True)
4553
partial = path.with_name(path.name + ".agent-context")
4654
partial.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
@@ -54,6 +62,59 @@ def update_json(path: Path, key: str, entry: dict[str, Any]) -> bool:
5462
return True
5563

5664

65+
def vscode_user_mcp_paths(home: Path) -> list[Path]:
66+
agent_folder = os.environ.get("VSCODE_AGENT_FOLDER")
67+
if agent_folder:
68+
server_roots = [Path(agent_folder).expanduser()]
69+
else:
70+
server_roots = [home / ".vscode-server", home / ".vscode-server-insiders"]
71+
existing_roots = [root for root in server_roots if root.exists()]
72+
server_roots = existing_roots or server_roots[:1]
73+
74+
paths: list[Path] = []
75+
for server_root in server_roots:
76+
user_dir = server_root / "data" / "User"
77+
paths.append(user_dir / "mcp.json")
78+
profiles_dir = user_dir / "profiles"
79+
if profiles_dir.is_dir():
80+
paths.extend(sorted(profiles_dir.glob("*/mcp.json")))
81+
return paths
82+
83+
84+
def update_vscode_user_mcp(home: Path, graph_command: str) -> list[str]:
85+
setup_package = home / ".apm" / "apm_modules" / "_local" / "apm-setup"
86+
if not setup_package.is_dir():
87+
warn(
88+
"skipping VS Code MCP registration: "
89+
f"APM package not found at {setup_package}"
90+
)
91+
return []
92+
93+
uv_command = shutil.which("uv") or "uv"
94+
workspace = Path(
95+
os.environ.get("AGENT_CONTEXT_WORKSPACE", str(Path.cwd()))
96+
).resolve()
97+
entries = {
98+
"graphify-codegraph": {
99+
"type": "stdio",
100+
"command": graph_command,
101+
"args": ["--repo-path", str(workspace)],
102+
},
103+
"apm-setup": {
104+
"type": "stdio",
105+
"command": uv_command,
106+
"args": ["run", "--project", str(setup_package), "apm-setup"],
107+
},
108+
}
109+
updated = []
110+
for path in vscode_user_mcp_paths(home):
111+
if update_json_mapping(
112+
path, "servers", entries, remove_keys=("score-codegraph",)
113+
):
114+
updated.append("vscode-copilot-chat")
115+
return updated
116+
117+
57118
def update_codex(path: Path, command: str) -> bool:
58119
"""Update or add the MCP server entry in Codex TOML config."""
59120
import re
@@ -71,6 +132,46 @@ def update_codex(path: Path, command: str) -> bool:
71132
return True
72133

73134

135+
def _update_opencode(path: Path, command: str) -> bool:
136+
"""Register for OpenCode V2 (mcp.servers) and clean up V1 (mcp.<name>)."""
137+
data: dict[str, Any] = {}
138+
if path.exists():
139+
try:
140+
data = json.loads(path.read_text(encoding="utf-8") or "{}")
141+
except json.JSONDecodeError:
142+
warn(f"skipping {path}: not valid JSON")
143+
return False
144+
if not isinstance(data, dict):
145+
warn(f"skipping {path}: unexpected content")
146+
return False
147+
if not path.exists():
148+
data["$schema"] = "https://opencode.ai/config.json"
149+
mcp = data.setdefault("mcp", {})
150+
if not isinstance(mcp, dict):
151+
warn(f"skipping {path}: mcp is not a mapping")
152+
return False
153+
# Remove legacy V1 flat entry (issue #56602)
154+
mcp.pop(NAME, None)
155+
servers = mcp.setdefault("servers", {})
156+
if not isinstance(servers, dict):
157+
warn(f"skipping {path}: mcp.servers is not a mapping")
158+
return False
159+
servers[NAME] = {
160+
"type": "local",
161+
"command": [command],
162+
}
163+
path.parent.mkdir(parents=True, exist_ok=True)
164+
partial = path.with_name(path.name + ".agent-context")
165+
partial.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
166+
if path.exists():
167+
original_mode = path.stat().st_mode
168+
partial.replace(path)
169+
path.chmod(original_mode)
170+
else:
171+
partial.replace(path)
172+
return True
173+
174+
74175
def register(home: Path, which: Which = shutil.which) -> list[str]:
75176
"""Register the server for every agent that is installed or configured."""
76177
command = which("graphify-codegraph") or str(
@@ -84,21 +185,10 @@ def register(home: Path, which: Which = shutil.which) -> list[str]:
84185
p, "mcpServers", {"type": "stdio", "command": command, "args": []}
85186
),
86187
),
87-
(
88-
"copilot",
89-
home / ".copilot" / "mcp-config.json",
90-
lambda p: update_json(
91-
p,
92-
"mcpServers",
93-
{"type": "local", "command": command, "args": [], "tools": ["*"]},
94-
),
95-
),
96188
(
97189
"opencode",
98190
home / ".config" / "opencode" / "opencode.json",
99-
lambda p: update_json(
100-
p, "mcp", {"type": "local", "command": [command], "enabled": True}
101-
),
191+
lambda p: _update_opencode(p, command),
102192
),
103193
("codex", home / ".codex" / "config.toml", lambda p: update_codex(p, command)),
104194
]
@@ -114,6 +204,7 @@ def register(home: Path, which: Which = shutil.which) -> list[str]:
114204
except OSError as exc:
115205
warn(f"could not register for {agent}: {exc}")
116206
continue
207+
registered.extend(update_vscode_user_mcp(home, command))
117208
return registered
118209

119210

@@ -130,7 +221,7 @@ def main() -> int:
130221
except OSError as exc:
131222
warn(f"registration failed: {exc}")
132223
return 0
133-
print(f"agent-context: registered {NAME} for {', '.join(agents) or 'no agent'}")
224+
print(f"agent-context: registered for {', '.join(agents) or 'no agent'}")
134225
return 0
135226

136227

0 commit comments

Comments
 (0)