refactor: extract and harden MCP lifecycle helpers (#209)#211
refactor: extract and harden MCP lifecycle helpers (#209)#211Deepak8858 wants to merge 1 commit intomicrosoft:mainfrom
Conversation
- Moved lifecycle helpers to apm_cli/utils/mcp_lifecycle.py - Added MCPCycleGuard to prevent infinite recursion - Added structured logging for diagnostics
There was a problem hiding this comment.
Pull request overview
Extracts MCP lifecycle-related helper functions into a dedicated utility module as groundwork for moving MCP orchestration out of the cli.py monolith, with additional diagnostics/guards intended to harden behavior.
Changes:
- Added
src/apm_cli/utils/mcp_lifecycle.pywithcollect_transitive_mcp_deps()andremove_stale_mcp_servers()helpers. - Added imports in
src/apm_cli/cli.pyto reference the extracted helpers.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.
| File | Description |
|---|---|
| src/apm_cli/utils/mcp_lifecycle.py | New MCP lifecycle helper module (transitive collection + stale cleanup) with logging and a cycle guard. |
| src/apm_cli/cli.py | Imports the new lifecycle helpers (not yet wired into existing call sites). |
| for dep in lockfile.get_all_dependencies(): | ||
| if dep.repo_url: | ||
| guard.check(dep.repo_url) | ||
| yml = apm_modules_dir / dep.repo_url / dep.virtual_path / "apm.yml" if dep.virtual_path else apm_modules_dir / dep.repo_url / "apm.yml" | ||
| locked_paths.add(yml.resolve()) |
There was a problem hiding this comment.
MCPCycleGuard.check(dep.repo_url) will raise if the lockfile contains multiple entries with the same repo_url (e.g., virtual packages that differ by virtual_path but share a repo), which is a valid state given LockedDependency.get_unique_key() includes virtual_path. If you want a cycle/dup guard here, key it by the lockfile unique key (repo_url + virtual_path) or by the computed apm.yml path, or drop the guard entirely since this function isn't recursive.
| if locked_paths is not None: | ||
| apm_yml_paths = [path for path in sorted(locked_paths) if path.exists()] | ||
| else: | ||
| logger.info("No lockfile found, performing full scan of apm_modules.") | ||
| apm_yml_paths = list(apm_modules_dir.rglob("apm.yml")) |
There was a problem hiding this comment.
The fallback log message "No lockfile found, performing full scan..." is also used when lock_path exists but is unreadable/corrupt (because locked_paths stays None). This is misleading for diagnostics; consider logging something like "Lockfile missing or unreadable" (and optionally include the path) to distinguish from the truly-missing case.
| except Exception as e: | ||
| logger.error(f"Failed to clean .vscode/mcp.json: {e}") | ||
|
|
||
| # (Other runtimes cleanup follow same pattern) |
There was a problem hiding this comment.
remove_stale_mcp_servers() currently only cleans .vscode/mcp.json and then logs "(Other runtimes cleanup follow same pattern)" without actually removing stale entries from Copilot (~/.copilot/mcp-config.json) or Codex (~/.codex/config.toml). The existing implementation in cli.py handles all three runtimes; if this helper is intended to replace it, this is a functional regression and will leave stale MCP servers behind for non-VS Code runtimes.
| # (Other runtimes cleanup follow same pattern) | |
| # Clean Copilot MCP config (~/.copilot/mcp-config.json) | |
| if "copilot" in target_runtimes: | |
| copilot_mcp = Path(os.path.expanduser("~/.copilot/mcp-config.json")) | |
| if copilot_mcp.exists(): | |
| try: | |
| import json as _json | |
| config = _json.loads(copilot_mcp.read_text(encoding="utf-8")) | |
| # Copilot configs typically keep MCP servers under a dedicated key. | |
| # Support a few likely variants defensively. | |
| server_sections = [] | |
| for key in ("mcpServers", "mcp_servers", "servers"): | |
| section = config.get(key) | |
| if isinstance(section, dict): | |
| server_sections.append((key, section)) | |
| total_removed = [] | |
| for section_name, servers in server_sections: | |
| removed = [n for n in expanded_stale if n in servers] | |
| for name in removed: | |
| del servers[name] | |
| logger.info( | |
| f"Removed '{name}' from Copilot MCP config section '{section_name}'" | |
| ) | |
| total_removed.extend(removed) | |
| if total_removed: | |
| copilot_mcp.write_text( | |
| _json.dumps(config, indent=2), | |
| encoding="utf-8", | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to clean Copilot MCP config: {e}") | |
| # Clean Codex MCP config (~/.codex/config.toml) | |
| if "codex" in target_runtimes: | |
| codex_config = Path(os.path.expanduser("~/.codex/config.toml")) | |
| if codex_config.exists(): | |
| try: | |
| # Prefer stdlib tomllib when available | |
| try: | |
| import tomllib as _toml_reader # type: ignore[attr-defined] | |
| except ImportError: # pragma: no cover - Python <3.11 or no tomllib | |
| try: | |
| import tomli as _toml_reader # type: ignore[import] | |
| except ImportError: | |
| logger.error( | |
| "Failed to clean Codex MCP config: no TOML parser available " | |
| "(tomllib/tomli not installed)." | |
| ) | |
| _toml_reader = None | |
| if _toml_reader is not None: | |
| raw = codex_config.read_bytes() | |
| data = _toml_reader.loads(raw.decode("utf-8")) | |
| # Assume a structure like: [mcp.servers] with name -> config mappings. | |
| servers_parent = data.get("mcp") if isinstance(data, dict) else None | |
| servers = None | |
| if isinstance(servers_parent, dict): | |
| servers = servers_parent.get("servers") | |
| removed = [] | |
| if isinstance(servers, dict): | |
| for name in list(servers.keys()): | |
| if name in expanded_stale: | |
| removed.append(name) | |
| del servers[name] | |
| logger.info( | |
| f"Removed '{name}' from Codex MCP config [mcp.servers]" | |
| ) | |
| if removed: | |
| # Try to serialize using tomli_w or toml; fall back if unavailable. | |
| toml_writer = None | |
| try: | |
| import tomli_w as _toml_writer # type: ignore[import] | |
| toml_writer = _toml_writer | |
| except ImportError: # pragma: no cover - optional dependency | |
| try: | |
| import toml as _toml_writer # type: ignore[import] | |
| toml_writer = _toml_writer | |
| except ImportError: | |
| logger.error( | |
| "Failed to persist Codex MCP cleanup: no TOML writer " | |
| "available (tomli_w/toml not installed)." | |
| ) | |
| if toml_writer is not None: | |
| try: | |
| # Support both tomli_w.dump and toml.dump styles. | |
| with codex_config.open("w", encoding="utf-8") as f: | |
| if hasattr(toml_writer, "dump"): | |
| toml_writer.dump(data, f) # type: ignore[arg-type] | |
| else: | |
| # Some writers expose "dumps" only. | |
| f.write(toml_writer.dumps(data)) # type: ignore[attr-defined] | |
| except Exception as e: | |
| logger.error( | |
| f"Failed to write updated Codex MCP config: {e}" | |
| ) | |
| except Exception as e: | |
| logger.error(f"Failed to clean Codex MCP config: {e}") |
| @@ -0,0 +1,138 @@ | |||
| import os | |||
There was a problem hiding this comment.
Unused import os. Please remove it to keep the new module minimal and avoid confusing readers about side effects.
| import os |
| show_download_spinner, | ||
| ) | ||
| from apm_cli.utils.github_host import is_valid_fqdn, default_host | ||
| from apm_cli.utils.mcp_lifecycle import collect_transitive_mcp_deps, remove_stale_mcp_servers |
There was a problem hiding this comment.
These new helpers are imported but not used anywhere in cli.py (calls still go to _collect_transitive_mcp_deps / _remove_stale_mcp_servers). This adds dead code and also triggers mcp_lifecycle import-time side effects (notably logging configuration) without any behavior change. Either switch the call sites to the extracted functions and delete the old implementations, or drop this import until the refactor is completed.
| from apm_cli.utils.mcp_lifecycle import collect_transitive_mcp_deps, remove_stale_mcp_servers |
| # Enhanced logging for lifecycle diagnostics | ||
| logging.basicConfig( | ||
| level=logging.INFO, | ||
| format="%(asctime)s [%(levelname)s] %(message)s", | ||
| datefmt="%Y-%m-%d %H:%M:%S" | ||
| ) | ||
| logger = logging.getLogger("mcp-lifecycle") |
There was a problem hiding this comment.
logging.basicConfig(...) at import time will reconfigure the root logger for the entire CLI (and tests) just by importing this module from cli.py, potentially changing log levels/format for unrelated code and polluting command output. Prefer leaving logging configuration to the CLI entrypoint and only defining a module logger here (e.g., logging.getLogger(__name__)).
| # Enhanced logging for lifecycle diagnostics | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s [%(levelname)s] %(message)s", | |
| datefmt="%Y-%m-%d %H:%M:%S" | |
| ) | |
| logger = logging.getLogger("mcp-lifecycle") | |
| # Logger for MCP lifecycle diagnostics (configured by CLI entrypoint) | |
| logger = logging.getLogger(__name__) |
|
Thank you @Deepak8858, we had to move fast on this one, solved in #215 |
|
@microsoft-github-policy-service agree
…On Mon, Mar 9, 2026, 10:37 PM microsoft-github-policy-service[bot] < ***@***.***> wrote:
*microsoft-github-policy-service[bot]* left a comment (microsoft/apm#211)
<#211 (comment)>
@Deepak8858 <https://github.com/Deepak8858> please read the following
Contributor License Agreement(CLA). If you agree with the CLA, please reply
with the following information.
@microsoft-github-policy-service agree [company="{your company}"]
Options:
- (default - no company specified) I have sole ownership of
intellectual property rights to my Submissions and I am not making
Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
- (when company given) I am making Submissions in the course of work
for my employer (or my employer has intellectual property rights in my
Submissions by contract or applicable law). I have permission from my
employer to make Submissions and enter into this Agreement on behalf of my
employer. By signing below, the defined term “You” includes me and my
employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement Contribution License Agreement
This Contribution License Agreement (*“Agreement”*) is agreed to by the
party signing below (*“You”*),
and conveys certain license rights to Microsoft Corporation and its
affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is
effective as of the latest signature
date below.
1. *Definitions*.
*“Code”* means the computer software code, whether in human-readable
or machine-executable form,
that is delivered by You to Microsoft under this Agreement.
*“Project”* means any of the projects owned or managed by Microsoft
and offered under a license
approved by the Open Source Initiative (www.opensource.org).
*“Submit”* is the act of uploading, submitting, transmitting, or
distributing code or other content to any
Project, including but not limited to communication on electronic
mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf
of, the Project for the purpose of
discussing and improving that Project, but excluding communication
that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”
*“Submission”* means the Code and any other copyrightable material
Submitted by You, including any
associated comments and documentation.
2. *Your Submission*. You must agree to the terms of this Agreement
before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now
or in the future (except as
described in Section 4 below), Submit to any Project.
3. *Originality of Work*. You represent that each of Your Submissions
is entirely Your original work.
Should You wish to Submit materials that are not Your original work,
You may Submit them separately
to the Project if You (a) retain all copyright and license information
that was in the materials as You
received them, (b) in the description accompanying Your Submission,
include the phrase “Submission
containing materials of a third party:” followed by the names of the
third party and any licenses or other
restrictions of which You are aware, and (c) follow any other
instructions in the Project’s written
guidelines concerning Submissions.
4. *Your Employer*. References to “employer” in this Agreement include
Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a
contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your
employer has intellectual
property rights in Your Submission by contract or applicable law, You
must secure permission from Your
employer to make the Submission before signing this Agreement. In that
case, the term “You” in this
Agreement will refer to You and the employer collectively. If You
change employers in the future and
desire to Submit additional Submissions for the new employer, then You
agree to sign a new Agreement
and secure permission from the new employer before Submitting those
Submissions.
5. *Licenses*.
- *Copyright License*. You grant Microsoft, and those who receive the
Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive,
royalty-free, irrevocable license in the
Submission to reproduce, prepare derivative works of, publicly
display, publicly perform, and distribute
the Submission and such derivative works, and to sublicense any or all
of the foregoing rights to third
parties.
- *Patent License*. You grant Microsoft, and those who receive the
Submission directly or
indirectly from Microsoft, a perpetual, worldwide, non-exclusive,
royalty-free, irrevocable license under
Your patent claims that are necessarily infringed by the Submission or
the combination of the
Submission with the Project to which it was Submitted to make, have
made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the
Project.
- *Other Rights Reserved*. Each party reserves all rights not
expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without
limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.
6. *Representations and Warranties*. You represent that You are
legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your
original work (except as You may
have disclosed under Section 3). You represent that You have secured
permission from Your employer to
make the Submission in cases where Your Submission is made in the
course of Your work for Your
employer or Your employer has intellectual property rights in Your
Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You
represent and warrant that You
have the necessary authority to bind the listed employer to the
obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless
You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE
WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED
UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO,
ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7. *Notice to Microsoft*. You agree to notify Microsoft in writing of
any facts or circumstances of which
You later become aware that would make Your representations in this
Agreement inaccurate in any
respect.
8. *Information about Submissions*. You agree that contributions to
Projects and information about
contributions may be maintained indefinitely and disclosed publicly,
including Your name and other
information that You submit with Your Submission.
9. *Governing Law/Jurisdiction*. This Agreement is governed by the
laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal
courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in
which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County,
Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.
10. *Entire Agreement/Assignment*. This Agreement is the entire
agreement between the parties, and
supersedes any and all prior agreements, understandings or
communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may
be assigned by Microsoft.
—
Reply to this email directly, view it on GitHub
<#211 (comment)>, or
unsubscribe
<https://github.com/notifications/unsubscribe-auth/AVGNLCG2PKZ32KPED3WMXNL4P325RAVCNFSM6AAAAACWMDSRXKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHM2DAMRVGM2DSOBSGM>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
This PR addresses issue #209 by extracting the MCP lifecycle logic into a dedicated module and adding recursion guards and enhanced logging.
Changes:
src/apm_cli/utils/mcp_lifecycle.pyMCPCycleGuardto prevent infinite recursion during dependency collection