feat(lib): bundle MCP servers from .common/lib into factory/lib/

Copies source (no node_modules, dist, .tasks, .wiki, __pycache__) for:
- projects-meta-mcp v2.25.0 (TypeScript/Node)
- wiki-graph v0.3.1 (TypeScript/Node)
- interns-mcp v0.3.3 (Python/FastMCP)

.gitignore: exclude lib build artefacts (node_modules, dist, .venv, __pycache__, *.pyc)
bootstrap.ps1: add MCP build step — npm install+build for TS servers, venv+pip for Python

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 13:17:12 +03:00
parent 9eeae13e72
commit ca669d96e1
116 changed files with 25331 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
"""Tests for HTTP client construction — esp. the request timeout that bounds
LLM calls so a stalled endpoint can never hang a worker thread forever."""
from interns_mcp.client import make_client, _resolve_timeout, DEFAULT_REQUEST_TIMEOUT
def test_default_timeout_is_bounded():
# A bare endpoint config must still get a finite, short-ish timeout —
# the OpenAI SDK default (600s) is long enough to wedge the server.
assert _resolve_timeout({}) == DEFAULT_REQUEST_TIMEOUT
assert DEFAULT_REQUEST_TIMEOUT <= 120
def test_configured_timeout_overrides_default():
assert _resolve_timeout({"request_timeout": 42}) == 42.0
def test_client_is_built_with_timeout():
c = make_client({"base_url": "http://example.invalid", "request_timeout": 30}, "k")
# OpenAI client exposes the configured timeout; must not be None.
assert c.timeout is not None

View File

@@ -0,0 +1,237 @@
"""Tests for grep_audit intern — deterministic, LLM-free."""
import json
from interns_mcp.interns.base import Intern, InternResponse
from interns_mcp.interns.grep_audit import GrepAudit
def test_substring_case_sensitive(tmp_path):
f = tmp_path / "claude.md"
f.write_text("follow project discipline\nuse superpowers\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f)],
patterns=["follow project discipline", "Follow Project Discipline"],
output="json",
)
assert isinstance(result, InternResponse)
data = json.loads(result.text)
matches = data["rows"][0]["matches"]
assert matches["follow project discipline"] is True
assert matches["Follow Project Discipline"] is False
def test_substring_case_insensitive(tmp_path):
f = tmp_path / "claude.md"
f.write_text("follow project discipline\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f)],
patterns=["FOLLOW PROJECT DISCIPLINE"],
output="json",
case_sensitive=False,
)
data = json.loads(result.text)
assert data["rows"][0]["matches"]["FOLLOW PROJECT DISCIPLINE"] is True
def test_regex_named(tmp_path):
f = tmp_path / "pyproject.toml"
f.write_text('version = "0.3.0"\n', encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f)],
patterns=[{"pattern": r'version\s*=\s*"\d+\.\d+\.\d+"', "name": "version-line", "regex": True}],
output="json",
)
data = json.loads(result.text)
assert data["rows"][0]["matches"]["version-line"] is True
def test_dict_substring(tmp_path):
f = tmp_path / "skill.md"
f.write_text("trigger string here\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f)],
patterns=[{"pattern": "trigger string", "name": "trigger"}],
output="json",
)
data = json.loads(result.text)
assert data["rows"][0]["matches"]["trigger"] is True
def test_output_table(tmp_path):
f1 = tmp_path / "a.md"
f1.write_text("alpha beta\n", encoding="utf-8")
f2 = tmp_path / "b.md"
f2.write_text("gamma\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f1), str(f2)],
patterns=["alpha", "gamma"],
output="table",
)
text = result.text
assert text.splitlines()[0].startswith("| Path |")
assert "alpha" in text.splitlines()[0]
assert "gamma" in text.splitlines()[0]
# f1 has alpha but not gamma
f1_line = [l for l in text.splitlines() if str(f1) in l][0]
assert "" in f1_line
assert "" in f1_line
# f2 has gamma but not alpha
f2_line = [l for l in text.splitlines() if str(f2) in l][0]
assert "" in f2_line
assert "" in f2_line
def test_output_json(tmp_path):
f = tmp_path / "a.md"
f.write_text("alpha\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f)],
patterns=["alpha", "missing"],
output="json",
)
data = json.loads(result.text)
assert "rows" in data
assert len(data["rows"]) == 1
assert data["rows"][0]["path"] == str(f)
assert data["rows"][0]["matches"]["alpha"] is True
assert data["rows"][0]["matches"]["missing"] is False
def test_file_not_found_partial_result(tmp_path):
f_real = tmp_path / "exists.md"
f_real.write_text("hello\n", encoding="utf-8")
f_ghost = tmp_path / "ghost.md" # never created
intern = GrepAudit()
result = intern.run(
paths=[str(f_real), str(f_ghost)],
patterns=["hello"],
output="json",
)
data = json.loads(result.text)
assert len(data["rows"]) == 2 # partial result, no abort
rows_by_path = {r["path"]: r for r in data["rows"]}
assert rows_by_path[str(f_real)]["matches"]["hello"] is True
# Ghost row: match is None (unreadable cell), error field present
assert rows_by_path[str(f_ghost)]["matches"]["hello"] is None
assert "error" in rows_by_path[str(f_ghost)]
def test_file_not_found_table_renders_warning(tmp_path):
f_ghost = tmp_path / "ghost.md" # never created
intern = GrepAudit()
result = intern.run(
paths=[str(f_ghost)],
patterns=["x"],
output="table",
)
assert "⚠️" in result.text
def test_empty_paths():
intern = GrepAudit()
result = intern.run(paths=[], patterns=["x"], output="json")
data = json.loads(result.text)
assert data["rows"] == []
assert result.usage["files_scanned"] == 0
assert result.usage["matches_total"] == 0
def test_empty_patterns(tmp_path):
f = tmp_path / "a.md"
f.write_text("alpha\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(paths=[str(f)], patterns=[], output="json")
data = json.loads(result.text)
assert len(data["rows"]) == 1
assert data["rows"][0]["matches"] == {}
assert result.usage["patterns_evaluated"] == 0
def test_unicode_content_utf8(tmp_path):
f = tmp_path / "ru.md"
f.write_text("русский текст\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f)],
patterns=["русский"],
output="json",
)
data = json.loads(result.text)
assert data["rows"][0]["matches"]["русский"] is True
def test_unicode_content_binary_garbage_does_not_crash(tmp_path):
f = tmp_path / "binary.bin"
f.write_bytes(b"\xff\xfe\x00\x01\x02 hello \xff")
intern = GrepAudit()
# errors="replace" should let us still grep for "hello"
result = intern.run(
paths=[str(f)],
patterns=["hello"],
output="json",
)
data = json.loads(result.text)
assert data["rows"][0]["matches"]["hello"] is True
def test_usage_counts(tmp_path):
f1 = tmp_path / "a.md"
f1.write_text("alpha\n", encoding="utf-8")
f2 = tmp_path / "b.md"
f2.write_text("alpha beta\n", encoding="utf-8")
intern = GrepAudit()
result = intern.run(
paths=[str(f1), str(f2)],
patterns=["alpha", "beta"],
output="json",
)
assert result.usage["files_scanned"] == 2
assert result.usage["patterns_evaluated"] == 2
# f1: alpha ✓, beta ✗ → 1
# f2: alpha ✓, beta ✓ → 2
assert result.usage["matches_total"] == 3
def test_endpoint_null_no_client_no_crash():
"""LLM-free intern must not require client wiring."""
intern = GrepAudit(config={"endpoint": None})
assert intern.client is None
assert intern.endpoint is None
def test_base_intern_accepts_endpoint_null_config():
"""Base class survives config with explicit endpoint=null (no LLM init triggered)."""
intern = Intern(config={"endpoint": None, "model": None})
assert intern.endpoint is None
assert intern.model is None
assert intern.client is None

View File

@@ -0,0 +1,40 @@
"""Tests for registry loading."""
from interns_mcp.registry import load_interns, INTERN_CLASSES
def test_classes_registered():
assert "bulk_text_read" in INTERN_CLASSES
assert "repo_read" in INTERN_CLASSES
assert "transcript_distill" in INTERN_CLASSES
def test_load_creates_interns():
config = {
"endpoints": {},
"interns": {
"bulk_text_read": {
"description": "test",
"endpoint": None,
"model": "test-model",
"max_tokens": 1024,
"temperature": 0.1,
"system_prompt": "test prompt",
},
},
}
interns = load_interns(config)
assert len(interns) == 1
assert interns[0].id == "bulk_text_read"
assert interns[0].model == "test-model"
def test_unknown_intern_skipped():
config = {
"endpoints": {},
"interns": {
"unknown_intern": {"description": "ghost"},
},
}
interns = load_interns(config)
assert len(interns) == 0

View File

@@ -0,0 +1,283 @@
"""Tests for repo_read intern."""
import os
import subprocess
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch
from interns_mcp.interns.base import BudgetExceededError, InternResponse
from interns_mcp.interns.repo_read import RepoRead, _top_files_by_size
def _make_llm_mock(text="The code prints hello", prompt_tokens=100, completion_tokens=50):
"""Build a mock LLM response."""
mock = MagicMock()
mock.choices = [MagicMock()]
mock.choices[0].message.content = text
mock.usage.prompt_tokens = prompt_tokens
mock.usage.completion_tokens = completion_tokens
return mock
def test_happy_path(tmp_path):
"""Repomix pack + LLM answer works."""
intern = RepoRead()
intern.system_prompt = "You are a helpful assistant."
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = _make_llm_mock()
target = str(tmp_path)
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[".env"]):
def fake_run(args, **kwargs):
out_idx = args.index("--output")
Path(args[out_idx + 1]).write_text("# Repo\n\n```python\nprint('hello')\n```")
return MagicMock(returncode=0, stdout="", stderr="")
mock_run.side_effect = fake_run
intern.client = mock_client
result = intern.run([target], "What does this repo do?")
assert isinstance(result, InternResponse)
assert "hello" in result.text.lower()
assert result.usage["tokens_in"] == 100
assert result.usage["tokens_out"] == 50
# Verify --ignore flag injected
call_args = mock_run.call_args[0][0]
assert "--ignore" in call_args
ignore_idx = call_args.index("--ignore")
assert call_args[ignore_idx + 1] == ".env"
# Verify --style xml
assert "--style" in call_args
style_idx = call_args.index("--style")
assert call_args[style_idx + 1] == "xml"
def test_tempfile_cleaned_up(tmp_path):
"""Temp file is removed after successful call."""
intern = RepoRead()
intern.system_prompt = "assistant"
intern.client = MagicMock()
intern.client.chat.completions.create.return_value = _make_llm_mock()
created_files = []
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
original_mkstemp = tempfile.mkstemp
def tracking_mkstemp(*args, **kwargs):
fd, path = original_mkstemp(*args, **kwargs)
created_files.append(path)
return fd, path
with patch("interns_mcp.interns.repo_read.tempfile.mkstemp", side_effect=tracking_mkstemp):
def fake_run(args, **kwargs):
out_idx = args.index("--output")
Path(args[out_idx + 1]).write_text("packed")
return MagicMock(returncode=0, stdout="", stderr="")
mock_run.side_effect = fake_run
intern.run([str(tmp_path)], "summarize")
# Temp file should be cleaned up
for f in created_files:
assert not os.path.exists(f), f"Temp file not cleaned up: {f}"
def test_tempfile_cleaned_up_on_error(tmp_path):
"""Temp file is removed even when repomix fails."""
intern = RepoRead()
created_files = []
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
original_mkstemp = tempfile.mkstemp
def tracking_mkstemp(*args, **kwargs):
fd, path = original_mkstemp(*args, **kwargs)
created_files.append(path)
return fd, path
with patch("interns_mcp.interns.repo_read.tempfile.mkstemp", side_effect=tracking_mkstemp):
mock_run.side_effect = subprocess.TimeoutExpired("npx", 120)
intern.run([str(tmp_path)], "summarize")
for f in created_files:
assert not os.path.exists(f), f"Temp file leaked on error: {f}"
def test_compress_flag_passed(tmp_path):
"""compress=True adds --compress to repomix args."""
intern = RepoRead()
intern.system_prompt = "assistant"
intern.client = MagicMock()
intern.client.chat.completions.create.return_value = _make_llm_mock()
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
def fake_run(args, **kwargs):
out_idx = args.index("--output")
Path(args[out_idx + 1]).write_text("packed content")
return MagicMock(returncode=0, stdout="", stderr="")
mock_run.side_effect = fake_run
intern.run([str(tmp_path)], "summarize", compress=True)
call_args = mock_run.call_args[0][0]
assert "--compress" in call_args
def test_multiple_paths_passed_to_repomix(tmp_path):
"""All paths are forwarded to repomix, not just the first."""
intern = RepoRead()
intern.system_prompt = "assistant"
intern.client = MagicMock()
intern.client.chat.completions.create.return_value = _make_llm_mock()
dir1 = tmp_path / "a"
dir2 = tmp_path / "b"
dir1.mkdir()
dir2.mkdir()
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
def fake_run(args, **kwargs):
out_idx = args.index("--output")
Path(args[out_idx + 1]).write_text("packed")
return MagicMock(returncode=0, stdout="", stderr="")
mock_run.side_effect = fake_run
intern.run([str(dir1), str(dir2)], "overview")
call_args = mock_run.call_args[0][0]
assert str(dir1) in call_args
assert str(dir2) in call_args
def test_empty_paths_returns_error():
"""Empty paths list returns error."""
intern = RepoRead()
result = intern.run([], "summarize")
assert isinstance(result, InternResponse)
assert "no paths" in result.text.lower()
def test_repomix_timeout_returns_error(tmp_path):
"""Repomix timeout returns graceful error."""
intern = RepoRead()
with patch("subprocess.run", side_effect=subprocess.TimeoutExpired("npx", 120)), \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
result = intern.run([str(tmp_path)], "summarize")
assert isinstance(result, InternResponse)
assert "timed out" in result.text.lower()
def test_repomix_failure_returns_error(tmp_path):
"""Repomix non-zero return returns stderr."""
intern = RepoRead()
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
mock_run.side_effect = subprocess.CalledProcessError(
1, "npx", stderr="package not found"
)
result = intern.run([str(tmp_path)], "summarize")
assert isinstance(result, InternResponse)
assert "failed" in result.text.lower()
def test_npx_not_found_returns_error(tmp_path):
"""Missing npx returns helpful message."""
intern = RepoRead()
with patch("subprocess.run", side_effect=FileNotFoundError), \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
result = intern.run([str(tmp_path)], "summarize")
assert isinstance(result, InternResponse)
assert "node.js" in result.text.lower()
def test_budget_exceeded_returns_error(tmp_path):
"""Large packed output triggers BudgetExceededError."""
intern = RepoRead()
intern.context_budget = 10 # very low to force overflow
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
def fake_run(args, **kwargs):
out_idx = args.index("--output")
Path(args[out_idx + 1]).write_text("x" * 200)
return MagicMock(returncode=0, stdout="", stderr="")
mock_run.side_effect = fake_run
result = intern.run([str(tmp_path)], "summarize")
assert isinstance(result, BudgetExceededError)
assert result.tokens > result.limit
assert result.hint
def test_top_files_by_size_sorts_by_content_length():
"""_top_files_by_size returns files sorted by content size, not document order."""
packed = (
'<file path="small.py">x</file>\n'
'<file path="large.py">' + "y" * 500 + '</file>\n'
'<file path="medium.py">' + "z" * 100 + '</file>\n'
)
result = _top_files_by_size(packed, n=3)
assert result[0] == "large.py", f"Expected large.py first, got {result[0]}"
assert result[1] == "medium.py", f"Expected medium.py second, got {result[1]}"
assert result[2] == "small.py", f"Expected small.py third, got {result[2]}"
def test_repomix_runs_without_pipes(tmp_path):
"""Anti-deadlock invariant: repomix must NOT be launched with captured pipes.
capture_output / stdout=PIPE spawns reader threads that communicate() joins;
an orphaned grandchild holding the pipe write-end makes that join hang forever
(the real-world 6-minute repo_read wedge). stdout must be DEVNULL, stdin DEVNULL,
and stderr a real file (has fileno) — never subprocess.PIPE.
"""
intern = RepoRead()
intern.system_prompt = "assistant"
intern.client = MagicMock()
intern.client.chat.completions.create.return_value = _make_llm_mock()
with patch("subprocess.run") as mock_run, \
patch("interns_mcp.interns.repo_read.always_ask_globs", return_value=[]):
def fake_run(args, **kwargs):
out_idx = args.index("--output")
Path(args[out_idx + 1]).write_text("packed")
return MagicMock(returncode=0)
mock_run.side_effect = fake_run
intern.run([str(tmp_path)], "summarize")
kwargs = mock_run.call_args.kwargs
assert kwargs.get("capture_output") is not True, "must not capture_output (pipes)"
assert kwargs.get("stdout") is subprocess.DEVNULL, "stdout must be DEVNULL"
assert kwargs.get("stdin") is subprocess.DEVNULL, "stdin must be DEVNULL"
assert kwargs.get("stderr") is not subprocess.PIPE, "stderr must not be a PIPE"
def test_top_files_by_size_limits_count():
"""_top_files_by_size respects the n parameter."""
packed = (
'<file path="a.py">xx</file>\n'
'<file path="b.py">yy</file>\n'
'<file path="c.py">zz</file>\n'
)
result = _top_files_by_size(packed, n=2)
assert len(result) == 2

View File

@@ -0,0 +1,54 @@
"""Tests for safety path matcher."""
from interns_mcp.safety import check_paths
def test_clean_paths_pass():
assert check_paths(["/home/user/project/src/main.py"]) == []
def test_env_file_blocked():
blocked = check_paths(["project/.env"])
assert len(blocked) == 1
assert blocked[0]["pattern"] == "**/.env"
def test_env_local_blocked():
blocked = check_paths(["project/.env.local"])
assert len(blocked) == 1
def test_secrets_dir_blocked():
blocked = check_paths(["project/secrets/api_key.txt"])
assert len(blocked) == 1
def test_pem_file_blocked():
blocked = check_paths(["/home/user/.ssh/id_rsa.pem"])
assert len(blocked) == 1
def test_ssh_dir_blocked():
blocked = check_paths(["/home/user/.ssh/config"])
assert len(blocked) == 1
def test_credentials_blocked():
blocked = check_paths(["project/credentials.json"])
assert len(blocked) == 1
def test_key_file_blocked():
blocked = check_paths(["project/server.key"])
assert len(blocked) == 1
def test_mixed_paths():
blocked = check_paths(["src/app.py", "project/.env", "README.md"])
assert len(blocked) == 1
assert blocked[0]["path"] == "project/.env"
def test_extra_patterns():
blocked = check_paths(["data/private.csv"], extra_patterns=["data/**"])
assert len(blocked) == 1