fix(mcp): tolerate current bd JSON shapes (#4253)

* fix(mcp): tolerate current bd JSON shapes

* Regenerate llms-full docs artifact (bd-588e1)
This commit is contained in:
Julian Knutsen 2026-05-29 14:28:49 -07:00 • committed by GitHub
commit 6d7eb5b3b1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 295 additions and 369 deletions

View file

@ -6,14 +6,14 @@ import os
import re
import sys
from abc import ABC, abstractmethod
from typing import Any, List, Optional
from typing import Any
from .config import load_config
from .models import (
AddDependencyParams,
ClaimIssueParams,
BlockedIssue,
BlockedParams,
ClaimIssueParams,
CloseIssueParams,
CreateIssueParams,
InitParams,
@ -27,7 +27,7 @@ from .models import (
)
def _sanitize_issue_deps(issue: dict) -> dict:
def _sanitize_issue_deps(issue: dict[str, Any]) -> dict[str, Any]:
"""Strip raw dependency records that don't match the LinkedIssue schema.
bd list/ready/blocked --json returns raw dep records (issue_id, depends_on_id,
@ -40,11 +40,9 @@ def _sanitize_issue_deps(issue: dict) -> dict:
("dependents", "dependent_count"),
]:
raw = issue.get(field)
if isinstance(raw, list) and raw:
# Check if these are raw dep records (have depends_on_id) vs enriched
if isinstance(raw[0], dict) and "depends_on_id" in raw[0]:
issue[count_field] = len(raw)
issue[field] = []
if isinstance(raw, list) and raw and isinstance(raw[0], dict) and "depends_on_id" in raw[0]:
issue[count_field] = len(raw)
issue[field] = []
return issue
@ -99,12 +97,12 @@ class BdClientBase(ABC):
"""Abstract base class for bd clients (CLI or daemon)."""
@abstractmethod
async def ready(self, params: Optional[ReadyWorkParams] = None) -> List[Issue]:
async def ready(self, params: ReadyWorkParams | None = None) -> list[Issue]:
"""Get ready work (issues with no blockers)."""
pass
@abstractmethod
async def list_issues(self, params: Optional[ListIssuesParams] = None) -> List[Issue]:
async def list_issues(self, params: ListIssuesParams | None = None) -> list[Issue]:
"""List issues with optional filters."""
pass
@ -129,12 +127,12 @@ class BdClientBase(ABC):
pass
@abstractmethod
async def close(self, params: CloseIssueParams) -> List[Issue]:
async def close(self, params: CloseIssueParams) -> list[Issue]:
"""Close one or more issues."""
pass
@abstractmethod
async def reopen(self, params: ReopenIssueParams) -> List[Issue]:
async def reopen(self, params: ReopenIssueParams) -> list[Issue]:
"""Reopen one or more closed issues."""
pass
@ -154,12 +152,12 @@ class BdClientBase(ABC):
pass
@abstractmethod
async def blocked(self, params: Optional[BlockedParams] = None) -> List[BlockedIssue]:
async def blocked(self, params: BlockedParams | None = None) -> list[BlockedIssue]:
"""Get blocked issues."""
pass
@abstractmethod
async def init(self, params: Optional[InitParams] = None) -> str:
async def init(self, params: InitParams | None = None) -> str:
"""Initialize a new beads database."""
pass
@ -176,10 +174,10 @@ class BdClientBase(ABC):
@abstractmethod
async def repair_deps(self, fix: bool = False) -> dict[str, Any]:
"""Find and optionally fix orphaned dependency references.
Args:
fix: If True, automatically remove orphaned dependencies
Returns:
Dict with orphans_found, orphans list, and fixed count if fix=True
"""
@ -188,10 +186,10 @@ class BdClientBase(ABC):
@abstractmethod
async def detect_pollution(self, clean: bool = False) -> dict[str, Any]:
"""Detect test issues that leaked into production database.
Args:
clean: If True, delete detected test issues
Returns:
Dict with detected test issues and deleted count if clean=True
"""
@ -200,11 +198,11 @@ class BdClientBase(ABC):
@abstractmethod
async def validate(self, checks: str | None = None, fix_all: bool = False) -> dict[str, Any]:
"""Run database validation checks.
Args:
checks: Comma-separated list of checks (orphans,duplicates,pollution,conflicts)
fix_all: If True, auto-fix all fixable issues
Returns:
Dict with validation results for each check
"""
@ -305,7 +303,6 @@ class BdCliClient(BdClientBase):
env["BEADS_DB"] = self.beads_db
# Log database routing for debugging
import sys
if self.beads_dir:
db_info = f"BEADS_DIR={self.beads_dir}"
elif self.beads_db:
@ -390,7 +387,9 @@ class BdCliClient(BdClientBase):
if version < min_version:
min_ver_str = ".".join(str(x) for x in min_version)
cur_ver_str = ".".join(str(x) for x in version)
install_cmd = "curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash"
install_cmd = (
"curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash"
)
raise BdVersionError(
f"bd version {cur_ver_str} is too old. "
f"This MCP server requires bd >= {min_ver_str}. "
@ -491,7 +490,7 @@ class BdCliClient(BdClientBase):
if not data:
raise BdCommandError(f"Issue not found: {params.issue_id}")
data = data[0]
if not isinstance(data, dict):
raise BdCommandError(f"Invalid response for show {params.issue_id}")
@ -567,7 +566,7 @@ class BdCliClient(BdClientBase):
if not data:
raise BdCommandError(f"Issue not found: {params.issue_id}")
data = data[0]
if not isinstance(data, dict):
raise BdCommandError(f"Invalid response for update {params.issue_id}")
@ -868,13 +867,13 @@ BdClient = BdCliClient
def create_bd_client(
prefer_daemon: bool = False,
bd_path: Optional[str] = None,
beads_dir: Optional[str] = None,
beads_db: Optional[str] = None,
actor: Optional[str] = None,
no_auto_flush: Optional[bool] = None,
no_auto_import: Optional[bool] = None,
working_dir: Optional[str] = None,
bd_path: str | None = None,
beads_dir: str | None = None,
beads_db: str | None = None,
actor: str | None = None,
no_auto_flush: bool | None = None,
no_auto_import: bool | None = None,
working_dir: str | None = None,
) -> BdClientBase:
"""Create a bd CLI client.

View file

@ -66,7 +66,8 @@ class Config(BaseSettings):
f"bd executable not found at: {v}\n\n"
+ "The beads Claude Code plugin requires the bd CLI to be installed.\n\n"
+ "Install bd CLI:\n"
+ " curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh | bash\n\n"
+ " curl -fsSL https://raw.githubusercontent.com/gastownhall/beads/main/scripts/install.sh "
+ "| bash\n\n"
+ "Or visit: https://github.com/gastownhall/beads#installation\n\n"
+ "After installation, restart Claude Code to reload the MCP server."
)

View file

@ -1,7 +1,7 @@
"""Pydantic models for beads issue tracker types."""
from datetime import datetime
from typing import Literal, Any
from typing import Literal
from pydantic import BaseModel, Field, field_validator
@ -38,12 +38,14 @@ OperationAction = Literal["created", "updated", "claimed", "closed", "reopened"]
# These lightweight models reduce context window usage by ~80% for list operations.
# Use full Issue model only when detailed information is needed (show command).
class IssueMinimal(BaseModel):
"""Minimal issue model for list views (~80% smaller than full Issue).
Use this for ready_work, list_issues, and other bulk operations.
For full details including dependencies, use Issue model via show().
"""
id: str
title: str
status: IssueStatus
@ -68,6 +70,7 @@ class CompactedResult(BaseModel):
When results exceed threshold, returns preview + metadata instead of full data.
This prevents context window overflow for large issue lists.
"""
compacted: bool = True
total_count: int
preview: list[IssueMinimal]
@ -81,6 +84,7 @@ class BriefIssue(BaseModel):
Use for quick scans where only identification + priority needed.
~95% smaller than full Issue.
"""
id: str
title: str
status: IssueStatus
@ -93,6 +97,7 @@ class BriefDep(BaseModel):
Use with brief_deps=True to get full issue but compact dependencies.
~90% smaller than full LinkedIssue.
"""
id: str
title: str
status: IssueStatus
@ -106,6 +111,7 @@ class OperationResult(BaseModel):
Default response for create/update/close/reopen when verbose=False.
~97% smaller than returning full Issue object.
"""
id: str
action: OperationAction
message: str | None = None
@ -115,6 +121,7 @@ class OperationResult(BaseModel):
# ORIGINAL MODELS (unchanged for backward compatibility)
# =============================================================================
class IssueBase(BaseModel):
"""Base issue model with shared fields."""

View file

@ -17,9 +17,10 @@ import logging
import os
import signal
import sys
from collections.abc import Awaitable, Callable
from functools import wraps
from types import FrameType
from typing import Any, Awaitable, Callable, TypeVar
from typing import Any, TypeVar
from fastmcp import FastMCP
@ -50,8 +51,8 @@ from beads_mcp.tools import (
beads_list_issues,
beads_quickstart,
beads_ready_work,
beads_repair_deps,
beads_reopen_issue,
beads_repair_deps,
beads_show_issue,
beads_stats,
beads_update_issue,
@ -219,7 +220,8 @@ def require_context(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitabl
workspace = current_workspace.get() or os.environ.get("BEADS_WORKING_DIR")
if not workspace:
raise ValueError(
"Context not set. Either provide workspace_root parameter or call context(workspace_root='...') first."
"Context not set. Either provide workspace_root parameter or call "
"context(workspace_root='...') first."
)
return await func(*args, **kwargs)
@ -354,7 +356,9 @@ _TOOL_CATALOG = {
@mcp.tool(
name="discover_tools",
description="List available beads tools (names and brief descriptions only). Use get_tool_info() for full details.",
description=(
"List available beads tools (names and brief descriptions only). Use get_tool_info() for full details."
),
)
async def discover_tools() -> dict[str, Any]:
"""Discover available beads tools without loading full schemas.
@ -391,7 +395,10 @@ async def get_tool_info(tool_name: str) -> dict[str, Any]:
"parameters": {
"limit": "int (1-100, default 10) - Max issues to return",
"priority": "int (0-4, optional) - Filter by priority",
"issue_type": "str (optional) - Filter by type (task, bug, feature, epic, chore, decision, merge-request, or custom)",
"issue_type": (
"str (optional) - Filter by type (task, bug, feature, epic, chore, "
"decision, merge-request, or custom)"
),
"assignee": "str (optional) - Filter by assignee",
"labels": "list[str] (optional) - AND filter: must have ALL labels",
"labels_any": "list[str] (optional) - OR filter: must have at least one",
@ -556,7 +563,9 @@ async def get_tool_info(tool_name: str) -> dict[str, Any]:
"name": "context",
"description": "Manage workspace context for beads operations",
"parameters": {
"action": "str (optional) - set|show|init (default: show if no args, set if workspace_root provided)",
"action": (
"str (optional) - set|show|init (default: show if no args, set if workspace_root provided)"
),
"workspace_root": "str (optional) - Workspace path for set/init actions",
"prefix": "str (optional) - Issue ID prefix for init action",
},
@ -602,10 +611,7 @@ async def context(
"""
# Infer action if not explicitly provided
if action is None:
if workspace_root is not None:
action = "set"
else:
action = "show"
action = "set" if workspace_root is not None else "show"
action = action.lower()
@ -820,7 +826,10 @@ def _truncate_description(issue: Issue, max_length: int) -> Issue:
@mcp.tool(
name="ready",
description="Find tasks that have no blockers and are ready to be worked on. Returns minimal format for context efficiency.",
description=(
"Find tasks that have no blockers and are ready to be worked on. "
"Returns minimal format for context efficiency."
),
)
@with_workspace
async def ready_work(
@ -889,7 +898,10 @@ async def ready_work(
total_count=len(minimal_issues),
preview=minimal_issues[:PREVIEW_COUNT],
preview_count=PREVIEW_COUNT,
hint=f"Showing {PREVIEW_COUNT} of {len(minimal_issues)} ready issues. Use show(issue_id) for full details.",
hint=(
f"Showing {PREVIEW_COUNT} of {len(minimal_issues)} ready issues. "
"Use show(issue_id) for full details."
),
)
return minimal_issues
@ -897,7 +909,9 @@ async def ready_work(
@mcp.tool(
name="list",
description="List all issues with optional filters. When status='blocked', returns BlockedIssue with blocked_by info.",
description=(
"List all issues with optional filters. When status='blocked', returns BlockedIssue with blocked_by info."
),
)
@with_workspace
async def list_issues(
@ -969,7 +983,10 @@ async def list_issues(
total_count=len(minimal_issues),
preview=minimal_issues[:PREVIEW_COUNT],
preview_count=PREVIEW_COUNT,
hint=f"Showing {PREVIEW_COUNT} of {len(minimal_issues)} issues. Use show(issue_id) for full details or add filters to narrow results.",
hint=(
f"Showing {PREVIEW_COUNT} of {len(minimal_issues)} issues. "
"Use show(issue_id) for full details or add filters to narrow results."
),
)
return minimal_issues
@ -1083,8 +1100,6 @@ async def claim_issue(
brief: If True (default), return minimal OperationResult; if False, return full Issue
"""
issue = await beads_claim_issue(issue_id=issue_id)
if issue is None:
return None
if brief:
return OperationResult(id=issue.id, action="claimed")
return issue
@ -1138,8 +1153,12 @@ async def update_issue(
external_ref=external_ref,
)
if issue is None:
return None
if isinstance(issue, list):
if not issue:
return None
if brief:
return [OperationResult(id=item.id, action="updated") for item in issue]
return issue
if brief:
return OperationResult(id=issue.id, action="updated")
return issue

View file

@ -51,11 +51,7 @@ def resolve_workspace_root(path: str) -> str:
local_beads = os.path.join(worktree_root, ".beads")
main_beads = os.path.join(main_repo_root, ".beads")
if (
worktree_root != main_repo_root
and not os.path.isdir(local_beads)
and os.path.isdir(main_beads)
):
if worktree_root != main_repo_root and not os.path.isdir(local_beads) and os.path.isdir(main_beads):
return main_repo_root
return worktree_root

View file

@ -4,7 +4,6 @@ This module provides safety checks to prevent test pollution in production datab
"""
import os
import sys
from pathlib import Path
import pytest
@ -13,25 +12,25 @@ import pytest
def pytest_configure(config):
"""Called before test collection starts - ensure we're not polluting production."""
# CRITICAL (bd-2c5a): Prevent tests from polluting production database
# Set test mode flag
os.environ["BEADS_TEST_MODE"] = "1"
# Get the project root (where .git exists)
current_dir = Path(__file__).parent.absolute()
project_root = current_dir
while project_root.parent != project_root:
if (project_root / ".git").exists():
break
project_root = project_root.parent
# If BEADS_DB or BEADS_WORKING_DIR point to production .beads/, fail immediately
beads_db = os.environ.get("BEADS_DB", "")
working_dir = os.environ.get("BEADS_WORKING_DIR", "")
production_beads = str(project_root / ".beads")
if beads_db and beads_db.startswith(production_beads):
pytest.exit(
f"PRODUCTION DATABASE POLLUTION DETECTED (bd-2c5a):\n"
@ -41,18 +40,20 @@ def pytest_configure(config):
f" Remove BEADS_DB env var or point it to a temp directory.",
returncode=1,
)
if working_dir and working_dir.startswith(str(project_root)):
# Working dir in project is OK ONLY if it's not the project root itself
if Path(working_dir).resolve() == project_root.resolve():
pytest.exit(
f"PRODUCTION DATABASE POLLUTION RISK (bd-2c5a):\n"
f" BEADS_WORKING_DIR={working_dir}\n"
f" Project root: {project_root}\n"
f" Tests should use isolated temp directories.\n"
f" Remove BEADS_WORKING_DIR or set it to a temp directory.",
returncode=1,
)
if (
working_dir
and working_dir.startswith(str(project_root))
and Path(working_dir).resolve() == project_root.resolve()
):
pytest.exit(
f"PRODUCTION DATABASE POLLUTION RISK (bd-2c5a):\n"
f" BEADS_WORKING_DIR={working_dir}\n"
f" Project root: {project_root}\n"
f" Tests should use isolated temp directories.\n"
f" Remove BEADS_WORKING_DIR or set it to a temp directory.",
returncode=1,
)
def pytest_runtest_setup(item):
@ -64,6 +65,7 @@ def pytest_runtest_setup(item):
if beads_db and ".beads/beads.db" in beads_db:
# Get temp directory
import tempfile
if not beads_db.startswith(tempfile.gettempdir()):
pytest.fail(
f"Test {item.name} is using production database (bd-2c5a):\n"

View file

@ -197,9 +197,7 @@ async def test_ready_with_issue_type(bd_client, mock_process):
@pytest.mark.asyncio
async def test_ready_invalid_response(bd_client, mock_process):
"""Test ready method with invalid response type."""
mock_process.communicate = AsyncMock(
return_value=(json.dumps({"error": "not a list"}).encode(), b"")
)
mock_process.communicate = AsyncMock(return_value=(json.dumps({"error": "not a list"}).encode(), b""))
with patch("asyncio.create_subprocess_exec", return_value=mock_process):
params = ReadyWorkParams(limit=10)
@ -235,9 +233,7 @@ async def test_list_issues(bd_client, mock_process):
@pytest.mark.asyncio
async def test_list_issues_invalid_response(bd_client, mock_process):
"""Test list_issues method with invalid response type."""
mock_process.communicate = AsyncMock(
return_value=(json.dumps({"error": "not a list"}).encode(), b"")
)
mock_process.communicate = AsyncMock(return_value=(json.dumps({"error": "not a list"}).encode(), b""))
with patch("asyncio.create_subprocess_exec", return_value=mock_process):
params = ListIssuesParams(status="open")
@ -492,9 +488,7 @@ async def test_close(bd_client, mock_process):
@pytest.mark.asyncio
async def test_close_invalid_response(bd_client, mock_process):
"""Test close method with invalid response type."""
mock_process.communicate = AsyncMock(
return_value=(json.dumps({"error": "not a list"}).encode(), b"")
)
mock_process.communicate = AsyncMock(return_value=(json.dumps({"error": "not a list"}).encode(), b""))
with (
patch("asyncio.create_subprocess_exec", return_value=mock_process),
@ -596,9 +590,7 @@ async def test_reopen_with_reason(bd_client, mock_process):
@pytest.mark.asyncio
async def test_reopen_invalid_response(bd_client, mock_process):
"""Test reopen method with invalid response type."""
mock_process.communicate = AsyncMock(
return_value=(json.dumps({"error": "not a list"}).encode(), b"")
)
mock_process.communicate = AsyncMock(return_value=(json.dumps({"error": "not a list"}).encode(), b""))
with (
patch("asyncio.create_subprocess_exec", return_value=mock_process),
@ -744,9 +736,7 @@ async def test_blocked(bd_client, mock_process):
@pytest.mark.asyncio
async def test_blocked_invalid_response(bd_client, mock_process):
"""Test blocked method with invalid response type."""
mock_process.communicate = AsyncMock(
return_value=(json.dumps({"error": "not a list"}).encode(), b"")
)
mock_process.communicate = AsyncMock(return_value=(json.dumps({"error": "not a list"}).encode(), b""))
with patch("asyncio.create_subprocess_exec", return_value=mock_process):
result = await bd_client.blocked()

View file

@ -1,6 +1,5 @@
"""Real integration tests for BdClient using actual bd binary."""
import os
import shutil
import tempfile
from pathlib import Path
@ -34,49 +33,44 @@ def bd_executable():
@pytest.fixture
def temp_db():
"""Create a temporary database file."""
fd, db_path = tempfile.mkstemp(suffix=".db", prefix="beads_test_", dir="/tmp")
os.close(fd)
# Remove the file so bd init can create it
os.unlink(db_path)
yield db_path
# Cleanup
if os.path.exists(db_path):
os.unlink(db_path)
def temp_workspace():
"""Create a temporary workspace for an embedded Dolt beads database."""
with tempfile.TemporaryDirectory(prefix="beads_test_workspace_") as temp_dir:
yield temp_dir
@pytest.fixture
async def bd_client(bd_executable, temp_db):
"""Create BdClient with temporary database - fully hermetic."""
client = BdClient(bd_path=bd_executable, beads_db=temp_db)
async def bd_client(bd_executable, temp_workspace, monkeypatch):
"""Create BdClient with an isolated workspace database."""
monkeypatch.delenv("BEADS_DB", raising=False)
monkeypatch.delenv("BEADS_DIR", raising=False)
monkeypatch.delenv("BD_DB", raising=False)
monkeypatch.delenv("BEADS_WORKING_DIR", raising=False)
# Initialize database with explicit BEADS_DB - no chdir needed!
env = os.environ.copy()
# Clear any existing BEADS_DB to ensure we use only temp_db
env.pop("BEADS_DB", None)
env["BEADS_DB"] = temp_db
client = BdClient(
bd_path=bd_executable,
beads_dir="",
beads_db="",
working_dir=temp_workspace,
)
import asyncio
# Use temp dir for subprocess to run in (prevents .beads/ discovery)
with tempfile.TemporaryDirectory(prefix="beads_test_workspace_", dir="/tmp") as temp_dir:
process = await asyncio.create_subprocess_exec(
bd_executable,
"init",
"--prefix",
"test",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
cwd=temp_dir, # Run in temp dir, not project dir
)
stdout, stderr = await process.communicate()
process = await asyncio.create_subprocess_exec(
bd_executable,
"init",
"--prefix",
"test",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=temp_workspace,
)
_stdout, stderr = await process.communicate()
if process.returncode != 0:
pytest.fail(f"Failed to initialize test database: {stderr.decode()}")
if process.returncode != 0:
pytest.fail(f"Failed to initialize test database: {stderr.decode()}")
yield client
yield client
@pytest.mark.asyncio
@ -161,9 +155,7 @@ async def test_update_issue(bd_client):
@pytest.mark.asyncio
async def test_claim_issue(bd_client):
"""Test atomic claim with real bd."""
created = await bd_client.create(
CreateIssueParams(title="Issue to claim", priority=2, issue_type="task")
)
created = await bd_client.create(CreateIssueParams(title="Issue to claim", priority=2, issue_type="task"))
claimed = await bd_client.claim(ClaimIssueParams(issue_id=created.id))
@ -427,7 +419,7 @@ async def test_init_creates_beads_directory(bd_executable):
from beads_mcp.models import InitParams
# Create a temporary directory to test in
with tempfile.TemporaryDirectory(prefix="beads_init_test_", dir="/tmp") as temp_dir:
with tempfile.TemporaryDirectory(prefix="beads_init_test_") as temp_dir:
temp_path = Path(temp_dir)
beads_dir = temp_path / ".beads"
@ -445,11 +437,11 @@ async def test_init_creates_beads_directory(bd_executable):
assert beads_dir.exists(), f".beads directory not created in {temp_dir}"
assert beads_dir.is_dir(), ".beads exists but is not a directory"
# Verify database file was created (always named beads.db, prefix is for issue IDs)
db_files = list(beads_dir.glob("*.db"))
assert len(db_files) > 0, "No database file created in .beads/"
assert any("beads.db" == db.name for db in db_files), (
f"Expected beads.db database file: {[db.name for db in db_files]}"
# Verify the embedded Dolt database was created under .beads/.
embedded_dir = beads_dir / "embeddeddolt"
assert embedded_dir.exists(), "No embedded Dolt directory created in .beads/"
assert any(path.name == ".dolt" for path in embedded_dir.glob("*/.dolt")), (
f"Expected an embedded Dolt database under {embedded_dir}"
)
# Verify success message

View file

@ -5,9 +5,13 @@ can be configured via environment variables.
"""
import os
import pytest
import subprocess
import sys
from pathlib import Path
import pytest
MCP_ROOT = Path(__file__).resolve().parents[1]
class TestCompactionConfigEnvironmentVariables:
@ -19,7 +23,7 @@ class TestCompactionConfigEnvironmentVariables:
env = os.environ.copy()
env.pop("BEADS_MCP_COMPACTION_THRESHOLD", None)
env.pop("BEADS_MCP_PREVIEW_COUNT", None)
code = """
import sys
import os
@ -37,9 +41,9 @@ print(f"preview={server.PREVIEW_COUNT}")
env=env,
capture_output=True,
text=True,
cwd="/Users/stevey/src/dave/beads/integrations/beads-mcp"
cwd=MCP_ROOT,
)
assert "threshold=20" in result.stdout
assert "preview=5" in result.stdout
@ -48,7 +52,7 @@ print(f"preview={server.PREVIEW_COUNT}")
env = os.environ.copy()
env["BEADS_MCP_COMPACTION_THRESHOLD"] = "50"
env["BEADS_MCP_PREVIEW_COUNT"] = "10"
code = """
import os
os.environ['BEADS_MCP_COMPACTION_THRESHOLD'] = '50'
@ -63,9 +67,9 @@ print(f"preview={server.PREVIEW_COUNT}")
env=env,
capture_output=True,
text=True,
cwd="/Users/stevey/src/dave/beads/integrations/beads-mcp"
cwd=MCP_ROOT,
)
assert "threshold=50" in result.stdout or "threshold=20" in result.stdout # May be cached
# Due to module caching, we test the function directly instead
@ -74,12 +78,13 @@ print(f"preview={server.PREVIEW_COUNT}")
# Save original env vars
orig_threshold = os.environ.pop("BEADS_MCP_COMPACTION_THRESHOLD", None)
orig_preview = os.environ.pop("BEADS_MCP_PREVIEW_COUNT", None)
try:
# Import and call the function
from beads_mcp.server import _get_compaction_settings
threshold, preview = _get_compaction_settings()
assert threshold == 20
assert preview == 5
finally:
@ -94,11 +99,12 @@ print(f"preview={server.PREVIEW_COUNT}")
# Set custom values
os.environ["BEADS_MCP_COMPACTION_THRESHOLD"] = "100"
os.environ["BEADS_MCP_PREVIEW_COUNT"] = "15"
try:
from beads_mcp.server import _get_compaction_settings
threshold, preview = _get_compaction_settings()
assert threshold == 100
assert preview == 15
finally:
@ -109,9 +115,10 @@ print(f"preview={server.PREVIEW_COUNT}")
def test_get_compaction_settings_validates_threshold_minimum(self):
"""Test validation: threshold must be >= 1."""
os.environ["BEADS_MCP_COMPACTION_THRESHOLD"] = "0"
try:
from beads_mcp.server import _get_compaction_settings
with pytest.raises(ValueError, match="BEADS_MCP_COMPACTION_THRESHOLD must be >= 1"):
_get_compaction_settings()
finally:
@ -121,9 +128,10 @@ print(f"preview={server.PREVIEW_COUNT}")
"""Test validation: preview_count must be >= 1."""
os.environ["BEADS_MCP_COMPACTION_THRESHOLD"] = "20"
os.environ["BEADS_MCP_PREVIEW_COUNT"] = "0"
try:
from beads_mcp.server import _get_compaction_settings
with pytest.raises(ValueError, match="BEADS_MCP_PREVIEW_COUNT must be >= 1"):
_get_compaction_settings()
finally:
@ -134,10 +142,13 @@ print(f"preview={server.PREVIEW_COUNT}")
"""Test validation: preview_count must be <= threshold."""
os.environ["BEADS_MCP_COMPACTION_THRESHOLD"] = "10"
os.environ["BEADS_MCP_PREVIEW_COUNT"] = "20"
try:
from beads_mcp.server import _get_compaction_settings
with pytest.raises(ValueError, match="BEADS_MCP_PREVIEW_COUNT must be <= BEADS_MCP_COMPACTION_THRESHOLD"):
with pytest.raises(
ValueError, match="BEADS_MCP_PREVIEW_COUNT must be <= BEADS_MCP_COMPACTION_THRESHOLD"
):
_get_compaction_settings()
finally:
os.environ.pop("BEADS_MCP_COMPACTION_THRESHOLD", None)
@ -147,11 +158,12 @@ print(f"preview={server.PREVIEW_COUNT}")
"""Test edge case: preview_count == threshold."""
os.environ["BEADS_MCP_COMPACTION_THRESHOLD"] = "5"
os.environ["BEADS_MCP_PREVIEW_COUNT"] = "5"
try:
from beads_mcp.server import _get_compaction_settings
threshold, preview = _get_compaction_settings()
assert threshold == 5
assert preview == 5
finally:
@ -162,11 +174,12 @@ print(f"preview={server.PREVIEW_COUNT}")
"""Test large custom values."""
os.environ["BEADS_MCP_COMPACTION_THRESHOLD"] = "1000"
os.environ["BEADS_MCP_PREVIEW_COUNT"] = "100"
try:
from beads_mcp.server import _get_compaction_settings
threshold, preview = _get_compaction_settings()
assert threshold == 1000
assert preview == 100
finally:
@ -179,16 +192,16 @@ class TestCompactionConfigDocumentation:
def test_environment_variables_documented_in_code(self):
"""Test that environment variables are documented in server.py comments."""
with open("/Users/stevey/src/dave/beads/integrations/beads-mcp/src/beads_mcp/server.py") as f:
with open(MCP_ROOT / "src" / "beads_mcp" / "server.py") as f:
content = f.read()
assert "BEADS_MCP_COMPACTION_THRESHOLD" in content
assert "BEADS_MCP_PREVIEW_COUNT" in content
def test_environment_variables_documented_in_context_engineering_md(self):
"""Test that configuration is documented in CONTEXT_ENGINEERING.md."""
with open("/Users/stevey/src/dave/beads/integrations/beads-mcp/CONTEXT_ENGINEERING.md") as f:
with open(MCP_ROOT / "CONTEXT_ENGINEERING.md") as f:
content = f.read()
# Should mention that settings are configurable or reference bd-4u2b
assert "configurable" in content.lower() or "bd-4u2b" in content or "environment" in content.lower()

View file

@ -1,9 +1,7 @@
"""Tests for MCP server lifecycle management."""
import asyncio
import signal
import sys
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import pytest
@ -15,22 +13,22 @@ def test_cleanup_handlers_registered():
import beads_mcp.server as server
# Verify cleanup function exists and is callable
assert hasattr(server, 'cleanup')
assert hasattr(server, "cleanup")
assert callable(server.cleanup)
# Verify signal handler exists and is callable
assert hasattr(server, 'signal_handler')
assert hasattr(server, "signal_handler")
assert callable(server.signal_handler)
# Verify global state exists
assert hasattr(server, '_cleanup_done')
assert hasattr(server, "_cleanup_done")
def test_cleanup_function_safe_to_call_multiple_times():
"""Test that cleanup function can be called multiple times safely."""
import beads_mcp.server as server
from beads_mcp.server import cleanup
import beads_mcp.server as server
server._cleanup_done = False
# Call cleanup multiple times - should not raise
@ -43,25 +41,25 @@ def test_signal_handler_calls_cleanup():
"""Test that signal handler calls cleanup and exits."""
from beads_mcp.server import signal_handler
with patch('beads_mcp.server.cleanup') as mock_cleanup:
with patch('sys.exit') as mock_exit:
# Call signal handler
signal_handler(signal.SIGTERM, None)
with patch("beads_mcp.server.cleanup") as mock_cleanup, patch("sys.exit") as mock_exit:
# Call signal handler
signal_handler(signal.SIGTERM, None)
# Verify cleanup was called
assert mock_cleanup.called
# Verify cleanup was called
assert mock_cleanup.called
# Verify exit was called
assert mock_exit.called
# Verify exit was called
assert mock_exit.called
def test_cleanup_logs_lifecycle_events(caplog):
"""Test that cleanup logs informative messages."""
import logging
from beads_mcp.server import cleanup
# Reset state
import beads_mcp.server as server
from beads_mcp.server import cleanup
server._cleanup_done = False
with caplog.at_level(logging.INFO):

View file

@ -22,7 +22,7 @@ from beads_mcp.models import CompactedResult, Issue, IssueMinimal
@pytest.fixture
def sample_issues(count=25):
"""Create a list of sample issues for testing compaction.
Default creates 25 issues to exceed the COMPACTION_THRESHOLD (20).
"""
now = datetime(2024, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
@ -64,7 +64,7 @@ def _apply_compaction(
hint_prefix: str = "",
) -> list[IssueMinimal] | CompactedResult:
"""Apply compaction logic - copy of server's compaction for testing.
This function contains the core compaction logic that's used in the MCP tools.
"""
if len(minimal_issues) > threshold:
@ -73,7 +73,10 @@ def _apply_compaction(
total_count=len(minimal_issues),
preview=minimal_issues[:preview_count],
preview_count=preview_count,
hint=f"{hint_prefix}Showing {preview_count} of {len(minimal_issues)} issues. Use show(issue_id) for full details.",
hint=(
f"{hint_prefix}Showing {preview_count} of {len(minimal_issues)} issues. "
"Use show(issue_id) for full details."
),
)
return minimal_issues
@ -386,7 +389,7 @@ class TestConversionToMinimal:
# Minimal should be significantly smaller
ratio = minimal_size / issue_size
assert ratio < 0.3, f"Minimal {ratio*100:.1f}% of full size (expected <30%)"
assert ratio < 0.3, f"Minimal {ratio * 100:.1f}% of full size (expected <30%)"
class TestCompactionWithFilters:

View file

@ -54,7 +54,7 @@ async def temp_db(bd_executable):
# Return the .beads directory path (not the db file)
beads_dir = os.path.join(temp_dir, ".beads")
yield beads_dir
# Cleanup
@ -157,9 +157,7 @@ async def test_show_issue_tool(mcp_client):
async def test_list_issues_tool(mcp_client):
"""Test list_issues tool."""
# Create some issues first
await mcp_client.call_tool(
"create", {"title": "Issue 1", "priority": 0, "issue_type": "bug", "brief": False}
)
await mcp_client.call_tool("create", {"title": "Issue 1", "priority": 0, "issue_type": "bug", "brief": False})
await mcp_client.call_tool(
"create", {"title": "Issue 2", "priority": 1, "issue_type": "feature", "brief": False}
)
@ -265,14 +263,10 @@ async def test_reopen_issue_tool(mcp_client):
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
await mcp_client.call_tool(
"close", {"issue_id": issue_id, "reason": "Done"}
)
await mcp_client.call_tool("close", {"issue_id": issue_id, "reason": "Done"})
# Reopen issue with brief=False to get full Issue object
reopen_result = await mcp_client.call_tool(
"reopen", {"issue_ids": [issue_id], "brief": False}
)
reopen_result = await mcp_client.call_tool("reopen", {"issue_ids": [issue_id], "brief": False})
reopened_issues = json.loads(reopen_result.content[0].text)
assert len(reopened_issues) >= 1
@ -331,8 +325,7 @@ async def test_reopen_with_reason_tool(mcp_client):
# Reopen with reason and brief=False
reopen_result = await mcp_client.call_tool(
"reopen",
{"issue_ids": [issue_id], "reason": "Found regression", "brief": False}
"reopen", {"issue_ids": [issue_id], "reason": "Found regression", "brief": False}
)
reopened_issues = json.loads(reopen_result.content[0].text)
@ -487,9 +480,7 @@ async def test_ready_work_with_priority_filter(mcp_client):
import json
# Create issues with different priorities
await mcp_client.call_tool(
"create", {"title": "P0 issue", "priority": 0, "issue_type": "bug", "brief": False}
)
await mcp_client.call_tool("create", {"title": "P0 issue", "priority": 0, "issue_type": "bug", "brief": False})
await mcp_client.call_tool(
"create", {"title": "P1 issue", "priority": 1, "issue_type": "task", "brief": False}
)
@ -627,8 +618,9 @@ async def test_context_init_action(bd_executable):
Uses a fresh temp directory without an existing database.
"""
import os
import tempfile
import shutil
import tempfile
from beads_mcp import tools
from beads_mcp.server import mcp
@ -742,16 +734,12 @@ async def test_update_brief_default(mcp_client):
import json
# Create issue first
create_result = await mcp_client.call_tool(
"create", {"title": "Update brief test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Update brief test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
# Update with default brief=True
update_result = await mcp_client.call_tool(
"update", {"issue_id": issue_id, "status": "blocked"}
)
update_result = await mcp_client.call_tool("update", {"issue_id": issue_id, "status": "blocked"})
data = json.loads(update_result.content[0].text)
assert data["id"] == issue_id
@ -765,9 +753,7 @@ async def test_update_brief_false(mcp_client):
import json
# Create issue first
create_result = await mcp_client.call_tool(
"create", {"title": "Update full test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Update full test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
@ -787,9 +773,7 @@ async def test_claim_brief_default(mcp_client):
"""Test claim returns OperationResult by default (brief=True)."""
import json
create_result = await mcp_client.call_tool(
"create", {"title": "Claim brief test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Claim brief test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
@ -804,9 +788,7 @@ async def test_claim_brief_false(mcp_client):
"""Test claim returns full Issue when brief=False."""
import json
create_result = await mcp_client.call_tool(
"create", {"title": "Claim full test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Claim full test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
@ -823,16 +805,12 @@ async def test_close_brief_default(mcp_client):
import json
# Create issue first
create_result = await mcp_client.call_tool(
"create", {"title": "Close brief test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Close brief test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
# Close with default brief=True
close_result = await mcp_client.call_tool(
"close", {"issue_id": issue_id, "reason": "Done"}
)
close_result = await mcp_client.call_tool("close", {"issue_id": issue_id, "reason": "Done"})
data = json.loads(close_result.content[0].text)
assert isinstance(data, list)
@ -847,16 +825,12 @@ async def test_close_brief_false(mcp_client):
import json
# Create issue first
create_result = await mcp_client.call_tool(
"create", {"title": "Close full test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Close full test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
# Close with brief=False
close_result = await mcp_client.call_tool(
"close", {"issue_id": issue_id, "reason": "Done", "brief": False}
)
close_result = await mcp_client.call_tool("close", {"issue_id": issue_id, "reason": "Done", "brief": False})
data = json.loads(close_result.content[0].text)
assert isinstance(data, list)
@ -872,18 +846,14 @@ async def test_reopen_brief_default(mcp_client):
import json
# Create and close issue first
create_result = await mcp_client.call_tool(
"create", {"title": "Reopen brief test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Reopen brief test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
await mcp_client.call_tool("close", {"issue_id": issue_id})
# Reopen with default brief=True
reopen_result = await mcp_client.call_tool(
"reopen", {"issue_ids": [issue_id]}
)
reopen_result = await mcp_client.call_tool("reopen", {"issue_ids": [issue_id]})
data = json.loads(reopen_result.content[0].text)
assert isinstance(data, list)
@ -906,9 +876,7 @@ async def test_show_brief(mcp_client):
issue_id = created["id"]
# Show with brief=True
show_result = await mcp_client.call_tool(
"show", {"issue_id": issue_id, "brief": True}
)
show_result = await mcp_client.call_tool("show", {"issue_id": issue_id, "brief": True})
data = json.loads(show_result.content[0].text)
# BriefIssue has only: id, title, status, priority
@ -940,9 +908,7 @@ async def test_show_fields_projection(mcp_client):
issue_id = created["id"]
# Show with specific fields
show_result = await mcp_client.call_tool(
"show", {"issue_id": issue_id, "fields": ["id", "title", "priority"]}
)
show_result = await mcp_client.call_tool("show", {"issue_id": issue_id, "fields": ["id", "title", "priority"]})
data = json.loads(show_result.content[0].text)
# Should have only requested fields
@ -958,20 +924,17 @@ async def test_show_fields_projection(mcp_client):
async def test_show_fields_invalid(mcp_client):
"""Test show with invalid fields raises error."""
import json
from fastmcp.exceptions import ToolError
# Create issue first
create_result = await mcp_client.call_tool(
"create", {"title": "Invalid fields test", "brief": False}
)
create_result = await mcp_client.call_tool("create", {"title": "Invalid fields test", "brief": False})
created = json.loads(create_result.content[0].text)
issue_id = created["id"]
# Show with invalid field should raise ToolError
with pytest.raises(ToolError) as exc_info:
await mcp_client.call_tool(
"show", {"issue_id": issue_id, "fields": ["id", "nonexistent_field"]}
)
await mcp_client.call_tool("show", {"issue_id": issue_id, "fields": ["id", "nonexistent_field"]})
# Verify error message mentions invalid field
assert "Invalid field" in str(exc_info.value)
@ -992,9 +955,7 @@ async def test_show_max_description_length(mcp_client):
issue_id = created["id"]
# Show with truncation
show_result = await mcp_client.call_tool(
"show", {"issue_id": issue_id, "max_description_length": 50}
)
show_result = await mcp_client.call_tool("show", {"issue_id": issue_id, "max_description_length": 50})
data = json.loads(show_result.content[0].text)
# Description should be truncated
@ -1008,12 +969,8 @@ async def test_list_brief(mcp_client):
import json
# Create some issues
await mcp_client.call_tool(
"create", {"title": "List brief 1", "priority": 1, "brief": False}
)
await mcp_client.call_tool(
"create", {"title": "List brief 2", "priority": 2, "brief": False}
)
await mcp_client.call_tool("create", {"title": "List brief 1", "priority": 1, "brief": False})
await mcp_client.call_tool("create", {"title": "List brief 2", "priority": 2, "brief": False})
# List with brief=True
result = await mcp_client.call_tool("list", {"brief": True})
@ -1037,9 +994,7 @@ async def test_ready_brief(mcp_client):
import json
# Create a ready issue
await mcp_client.call_tool(
"create", {"title": "Ready brief test", "priority": 1, "brief": False}
)
await mcp_client.call_tool("create", {"title": "Ready brief test", "priority": 1, "brief": False})
# Ready with brief=True
result = await mcp_client.call_tool("ready", {"brief": True, "limit": 100})
@ -1062,14 +1017,10 @@ async def test_blocked_brief(mcp_client):
import json
# Create blocking dependency
blocking_result = await mcp_client.call_tool(
"create", {"title": "Blocker for brief test", "brief": False}
)
blocking_result = await mcp_client.call_tool("create", {"title": "Blocker for brief test", "brief": False})
blocking = json.loads(blocking_result.content[0].text)
blocked_result = await mcp_client.call_tool(
"create", {"title": "Blocked for brief test", "brief": False}
)
blocked_result = await mcp_client.call_tool("create", {"title": "Blocked for brief test", "brief": False})
blocked = json.loads(blocked_result.content[0].text)
await mcp_client.call_tool(
@ -1097,14 +1048,10 @@ async def test_show_brief_deps(mcp_client):
import json
# Create two issues with dependency
dep_result = await mcp_client.call_tool(
"create", {"title": "Dependency issue", "brief": False}
)
dep_result = await mcp_client.call_tool("create", {"title": "Dependency issue", "brief": False})
dep_issue = json.loads(dep_result.content[0].text)
main_result = await mcp_client.call_tool(
"create", {"title": "Main issue", "brief": False}
)
main_result = await mcp_client.call_tool("create", {"title": "Main issue", "brief": False})
main_issue = json.loads(main_result.content[0].text)
await mcp_client.call_tool(
@ -1113,9 +1060,7 @@ async def test_show_brief_deps(mcp_client):
)
# Show with brief_deps=True
show_result = await mcp_client.call_tool(
"show", {"issue_id": main_issue["id"], "brief_deps": True}
)
show_result = await mcp_client.call_tool("show", {"issue_id": main_issue["id"], "brief_deps": True})
data = json.loads(show_result.content[0].text)
# Full issue data

View file

@ -21,9 +21,7 @@ import pytest
from beads_mcp.tools import (
_canonicalize_path,
_connection_pool,
_pool_lock,
_resolve_workspace_root,
beads_create_issue,
beads_list_issues,
beads_ready_work,
current_workspace,
@ -106,7 +104,7 @@ class TestConcurrentMultiProject:
current_workspace.reset(token)
# Call all three projects concurrently
results = await asyncio.gather(
await asyncio.gather(
call_ready(temp_projects["a"]),
call_ready(temp_projects["b"]),
call_ready(temp_projects["c"]),
@ -144,7 +142,7 @@ class TestConcurrentMultiProject:
current_workspace.reset(token)
# Call same project multiple times concurrently
results = await asyncio.gather(
await asyncio.gather(
call_ready(temp_projects["a"]),
call_ready(temp_projects["a"]),
call_ready(temp_projects["a"]),
@ -337,7 +335,6 @@ class TestCrossProjectIsolation:
# Mock different responses for each project
canonical_a = os.path.realpath(temp_projects["a"])
canonical_b = os.path.realpath(temp_projects["b"])
def create_client_with_data(**kwargs: Any) -> AsyncMock:
client = get_mock(kwargs["working_dir"])
@ -478,6 +475,7 @@ class TestEdgeCases:
async def test_no_workspace_raises_error(self):
"""Test calling without workspace raises helpful error."""
import os
from beads_mcp import tools
# Clear context and env
@ -485,9 +483,11 @@ class TestEdgeCases:
os.environ.pop("BEADS_WORKING_DIR", None)
# No ContextVar set, no env var, and auto-detect fails
with pytest.raises(Exception) as exc_info:
with patch("beads_mcp.tools._find_beads_db_in_tree", return_value=None):
await beads_ready_work()
with (
pytest.raises(Exception) as exc_info,
patch("beads_mcp.tools._find_beads_db_in_tree", return_value=None),
):
await beads_ready_work()
assert "No beads workspace found" in str(exc_info.value)

View file

@ -10,8 +10,7 @@ These tests verify that all subprocess calls use stdin=DEVNULL.
import asyncio
import subprocess
import sys
from unittest.mock import AsyncMock, MagicMock, call, patch
from unittest.mock import AsyncMock, MagicMock, patch
import pytest

View file

@ -145,9 +145,7 @@ async def test_beads_create_issue_with_labels(sample_issue):
mock_client.create = AsyncMock(return_value=sample_issue)
with patch("beads_mcp.tools._get_client", return_value=mock_client):
issue = await beads_create_issue(
title="New issue", labels=["bug", "urgent"]
)
issue = await beads_create_issue(title="New issue", labels=["bug", "urgent"])
assert issue.id == "bd-1"
mock_client.create.assert_called_once()
@ -156,9 +154,7 @@ async def test_beads_create_issue_with_labels(sample_issue):
@pytest.mark.asyncio
async def test_beads_update_issue(sample_issue):
"""Test beads_update_issue tool."""
updated_issue = sample_issue.model_copy(
update={"status": "blocked"}
)
updated_issue = sample_issue.model_copy(update={"status": "blocked"})
mock_client = AsyncMock()
mock_client.update = AsyncMock(return_value=updated_issue)
@ -174,9 +170,7 @@ async def test_beads_update_issue(sample_issue):
@pytest.mark.asyncio
async def test_beads_claim_issue(sample_issue):
"""Test beads_claim_issue tool."""
claimed_issue = sample_issue.model_copy(
update={"status": "in_progress", "assignee": "agent-a"}
)
claimed_issue = sample_issue.model_copy(update={"status": "in_progress", "assignee": "agent-a"})
mock_client = AsyncMock()
mock_client.claim = AsyncMock(return_value=claimed_issue)
@ -192,9 +186,7 @@ async def test_beads_claim_issue(sample_issue):
@pytest.mark.asyncio
async def test_beads_close_issue(sample_issue):
"""Test beads_close_issue tool."""
closed_issue = sample_issue.model_copy(
update={"status": "closed", "closed_at": "2024-01-02T00:00:00Z"}
)
closed_issue = sample_issue.model_copy(update={"status": "closed", "closed_at": "2024-01-02T00:00:00Z"})
mock_client = AsyncMock()
mock_client.close = AsyncMock(return_value=[closed_issue])
@ -209,9 +201,7 @@ async def test_beads_close_issue(sample_issue):
@pytest.mark.asyncio
async def test_beads_reopen_issue(sample_issue):
"""Test beads_reopen_issue tool."""
reopened_issue = sample_issue.model_copy(
update={"status": "open", "closed_at": None}
)
reopened_issue = sample_issue.model_copy(update={"status": "open", "closed_at": None})
mock_client = AsyncMock()
mock_client.reopen = AsyncMock(return_value=[reopened_issue])
@ -227,12 +217,8 @@ async def test_beads_reopen_issue(sample_issue):
@pytest.mark.asyncio
async def test_beads_reopen_multiple_issues(sample_issue):
"""Test beads_reopen_issue with multiple issues."""
reopened_issue1 = sample_issue.model_copy(
update={"id": "bd-1", "status": "open", "closed_at": None}
)
reopened_issue2 = sample_issue.model_copy(
update={"id": "bd-2", "status": "open", "closed_at": None}
)
reopened_issue1 = sample_issue.model_copy(update={"id": "bd-1", "status": "open", "closed_at": None})
reopened_issue2 = sample_issue.model_copy(update={"id": "bd-2", "status": "open", "closed_at": None})
mock_client = AsyncMock()
mock_client.reopen = AsyncMock(return_value=[reopened_issue1, reopened_issue2])
@ -249,16 +235,12 @@ async def test_beads_reopen_multiple_issues(sample_issue):
@pytest.mark.asyncio
async def test_beads_reopen_issue_with_reason(sample_issue):
"""Test beads_reopen_issue with reason parameter."""
reopened_issue = sample_issue.model_copy(
update={"status": "open", "closed_at": None}
)
reopened_issue = sample_issue.model_copy(update={"status": "open", "closed_at": None})
mock_client = AsyncMock()
mock_client.reopen = AsyncMock(return_value=[reopened_issue])
with patch("beads_mcp.tools._get_client", return_value=mock_client):
issues = await beads_reopen_issue(
issue_ids=["bd-1"], reason="Found regression"
)
issues = await beads_reopen_issue(issue_ids=["bd-1"], reason="Found regression")
assert len(issues) == 1
assert issues[0].status == "open"
@ -273,9 +255,7 @@ async def test_beads_add_dependency_success():
mock_client.add_dependency = AsyncMock(return_value=None)
with patch("beads_mcp.tools._get_client", return_value=mock_client):
result = await beads_add_dependency(
issue_id="bd-2", depends_on_id="bd-1", dep_type="blocks"
)
result = await beads_add_dependency(issue_id="bd-2", depends_on_id="bd-1", dep_type="blocks")
assert "Added dependency" in result
assert "bd-2" in result
@ -289,14 +269,10 @@ async def test_beads_add_dependency_error():
from beads_mcp.bd_client import BdError
mock_client = AsyncMock()
mock_client.add_dependency = AsyncMock(
side_effect=BdError("Dependency already exists")
)
mock_client.add_dependency = AsyncMock(side_effect=BdError("Dependency already exists"))
with patch("beads_mcp.tools._get_client", return_value=mock_client):
result = await beads_add_dependency(
issue_id="bd-2", depends_on_id="bd-1", dep_type="blocks"
)
result = await beads_add_dependency(issue_id="bd-2", depends_on_id="bd-1", dep_type="blocks")
assert "Error" in result
mock_client.add_dependency.assert_called_once()
@ -319,9 +295,10 @@ async def test_beads_quickstart():
@pytest.mark.asyncio
async def test_client_lazy_initialization(tmp_path):
"""Test that client is lazily initialized on first use."""
from beads_mcp import tools
import os
from beads_mcp import tools
# Set workspace for the test
test_workspace = str(tmp_path)
os.environ["BEADS_WORKING_DIR"] = test_workspace
@ -410,18 +387,12 @@ async def test_update_issue_multiple_fields(sample_issue):
@pytest.mark.asyncio
async def test_update_issue_routes_closed_to_close(sample_issue):
"""Test that update with status=closed routes to close tool."""
closed_issue = sample_issue.model_copy(
update={"status": "closed", "closed_at": "2024-01-02T00:00:00Z"}
)
closed_issue = sample_issue.model_copy(update={"status": "closed", "closed_at": "2024-01-02T00:00:00Z"})
mock_client = AsyncMock()
mock_client.close = AsyncMock(return_value=[closed_issue])
with patch("beads_mcp.tools._get_client", return_value=mock_client):
result = await beads_update_issue(
issue_id="bd-1",
status="closed",
notes="Task completed"
)
result = await beads_update_issue(issue_id="bd-1", status="closed", notes="Task completed")
# Should route to close, not update
assert isinstance(result, list)
@ -434,18 +405,12 @@ async def test_update_issue_routes_closed_to_close(sample_issue):
@pytest.mark.asyncio
async def test_update_issue_routes_open_to_reopen(sample_issue):
"""Test that update with status=open routes to reopen tool."""
reopened_issue = sample_issue.model_copy(
update={"status": "open", "closed_at": None}
)
reopened_issue = sample_issue.model_copy(update={"status": "open", "closed_at": None})
mock_client = AsyncMock()
mock_client.reopen = AsyncMock(return_value=[reopened_issue])
with patch("beads_mcp.tools._get_client", return_value=mock_client):
result = await beads_update_issue(
issue_id="bd-1",
status="open",
notes="Needs more work"
)
result = await beads_update_issue(issue_id="bd-1", status="open", notes="Needs more work")
# Should route to reopen, not update
assert isinstance(result, list)

View file

@ -290,6 +290,7 @@ def test_find_beads_db_prefers_redirect_over_parent():
# --- GH#2997: embedded Dolt and other backend detection ---
def test_find_beads_db_embedded_dolt():
"""Embedded Dolt projects have no *.db file; detect via metadata.json."""
with tempfile.TemporaryDirectory() as tmpdir:
@ -334,9 +335,7 @@ def test_find_beads_db_redirect_to_dolt():
main_dir.mkdir()
main_beads = main_dir / ".beads"
main_beads.mkdir()
(main_beads / "metadata.json").write_text(
'{"backend":"dolt","dolt_mode":"embedded"}'
)
(main_beads / "metadata.json").write_text('{"backend":"dolt","dolt_mode":"embedded"}')
(main_beads / "embeddeddolt").mkdir()
worker = Path(tmpdir) / "worker"

View file

@ -7,7 +7,6 @@ NOTE: These tests may have flaky behavior due to path caching issues.
See bd-4aao for details.
"""
import asyncio
import json
import os
import shutil
@ -36,7 +35,7 @@ def bd_executable():
@pytest.fixture
async def git_worktree_with_separate_dbs(bd_executable):
"""Create a git repo with a worktree, each with its own beads database.
Returns:
tuple: (main_repo_path, worktree_path, temp_dir)
"""
@ -44,7 +43,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
temp_dir = tempfile.mkdtemp(prefix="beads_worktree_separate_")
main_repo = Path(temp_dir) / "main"
worktree = Path(temp_dir) / "worktree"
try:
# Initialize main git repo
main_repo.mkdir()
@ -61,7 +60,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
check=True,
capture_output=True,
)
# Create initial commit
readme = main_repo / "README.md"
readme.write_text("# Test Repo\n")
@ -72,7 +71,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
check=True,
capture_output=True,
)
# Initialize beads in main repo BEFORE creating worktree
init_result = subprocess.run(
["bd", "init", "--prefix", "main"],
@ -84,7 +83,9 @@ async def git_worktree_with_separate_dbs(bd_executable):
raise RuntimeError(f"bd init in main failed: {init_result.stderr}")
# Verify main repo has .beads directory (database is always beads.db, prefix is for issue IDs)
assert (main_repo / ".beads").exists(), f"Main repo should have .beads directory. Init output: {init_result.stdout} {init_result.stderr}"
assert (main_repo / ".beads").exists(), (
f"Main repo should have .beads directory. Init output: {init_result.stdout} {init_result.stderr}"
)
assert (main_repo / ".beads" / "beads.db").exists(), "Main repo should have database"
# Create a worktree AFTER initializing beads in main
@ -94,7 +95,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
check=True,
capture_output=True,
)
# Commit the .beads directory to git in main repo
subprocess.run(["git", "add", ".beads"], cwd=main_repo, check=True, capture_output=True)
subprocess.run(
@ -106,7 +107,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
# Re-sync after commit to avoid staleness check issues
subprocess.run(["bd", "sync"], cwd=main_repo, capture_output=True)
# Initialize beads in worktree (separate database, different prefix)
init_result = subprocess.run(
["bd", "init", "--prefix", "feature"],
@ -118,9 +119,11 @@ async def git_worktree_with_separate_dbs(bd_executable):
raise RuntimeError(f"bd init in worktree failed: {init_result.stderr}")
# Verify worktree has its own .beads directory (database is always beads.db)
assert (worktree / ".beads").exists(), f"Worktree should have .beads directory. Init output: {init_result.stdout} {init_result.stderr}"
assert (worktree / ".beads").exists(), (
f"Worktree should have .beads directory. Init output: {init_result.stdout} {init_result.stderr}"
)
assert (worktree / ".beads" / "beads.db").exists(), "Worktree should have database"
# Commit the worktree's .beads (will replace/update main's .beads on feature branch)
subprocess.run(["git", "add", ".beads"], cwd=worktree, check=True, capture_output=True)
result = subprocess.run(
@ -137,7 +140,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
subprocess.run(["bd", "sync"], cwd=worktree, capture_output=True)
yield main_repo, worktree, temp_dir
finally:
# Cleanup
shutil.rmtree(temp_dir, ignore_errors=True)
@ -148,7 +151,7 @@ async def git_worktree_with_separate_dbs(bd_executable):
async def test_separate_databases_are_isolated(git_worktree_with_separate_dbs, bd_executable):
"""Test that each worktree has its own isolated database."""
main_repo, worktree, temp_dir = git_worktree_with_separate_dbs
# Create issue in main repo
result = subprocess.run(
["bd", "create", "Main repo issue", "-p", "1", "--json"],
@ -159,7 +162,7 @@ async def test_separate_databases_are_isolated(git_worktree_with_separate_dbs, b
assert result.returncode == 0, f"Create in main failed: {result.stderr}"
main_issue = json.loads(result.stdout)
assert main_issue["id"].startswith("main-"), f"Expected main- prefix, got {main_issue['id']}"
# Create issue in worktree
result = subprocess.run(
["bd", "create", "Worktree issue", "-p", "1", "--json"],
@ -170,7 +173,7 @@ async def test_separate_databases_are_isolated(git_worktree_with_separate_dbs, b
assert result.returncode == 0, f"Create in worktree failed: {result.stderr}"
worktree_issue = json.loads(result.stdout)
assert worktree_issue["id"].startswith("feature-"), f"Expected feature- prefix, got {worktree_issue['id']}"
# List issues in main repo
result = subprocess.run(
["bd", "list", "--json"],
@ -192,11 +195,11 @@ async def test_separate_databases_are_isolated(git_worktree_with_separate_dbs, b
assert result.returncode == 0
worktree_issues = json.loads(result.stdout)
worktree_ids = [issue["id"] for issue in worktree_issues]
# Verify isolation - main repo shouldn't see worktree issues and vice versa
assert "main-1" in main_ids, "Main repo should see its own issue"
assert "feature-1" not in main_ids, "Main repo should NOT see worktree issue"
assert "feature-1" in worktree_ids, "Worktree should see its own issue"
assert "main-1" not in worktree_ids, "Worktree should NOT see main repo issue (yet)"
@ -206,7 +209,7 @@ async def test_separate_databases_are_isolated(git_worktree_with_separate_dbs, b
async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executable):
"""Test that changes sync between worktrees via git commits and merges."""
main_repo, worktree, temp_dir = git_worktree_with_separate_dbs
# Create and commit issue in main repo
result = subprocess.run(
["bd", "create", "Shared issue", "-p", "1", "--json"],
@ -215,7 +218,6 @@ async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executabl
text=True,
)
assert result.returncode == 0
main_issue = json.loads(result.stdout)
# Export to JSONL (should happen automatically, but force it)
subprocess.run(
@ -224,7 +226,7 @@ async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executabl
check=True,
capture_output=True,
)
# Commit the JSONL file
subprocess.run(["git", "add", ".beads/issues.jsonl"], cwd=main_repo, check=True, capture_output=True)
subprocess.run(
@ -233,7 +235,7 @@ async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executabl
check=True,
capture_output=True,
)
# Switch worktree to main branch temporarily to pull changes
subprocess.run(
["git", "fetch", "origin", "master:master"],
@ -245,7 +247,7 @@ async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executabl
cwd=worktree,
capture_output=True, # May have conflicts, handle below
)
# Import the changes into worktree database
result = subprocess.run(
["bd", "import", "-i", ".beads/issues.jsonl"],
@ -264,8 +266,7 @@ async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executabl
)
assert result.returncode == 0
worktree_issues = json.loads(result.stdout)
worktree_ids = [issue["id"] for issue in worktree_issues]
# After import, worktree should see the main repo issue
# (with potentially remapped ID due to prefix difference)
assert len(worktree_issues) >= 1, "Worktree should have at least one issue after import"
@ -276,23 +277,22 @@ async def test_changes_sync_via_git(git_worktree_with_separate_dbs, bd_executabl
async def test_mcp_works_with_separate_databases(git_worktree_with_separate_dbs, monkeypatch):
"""Test that MCP server works independently in each worktree."""
from beads_mcp import tools
from beads_mcp.bd_client import BdCliClient
main_repo, worktree, temp_dir = git_worktree_with_separate_dbs
# Configure MCP for worktree
tools._connection_pool.clear()
monkeypatch.setenv("BEADS_WORKING_DIR", str(worktree))
# Reset context
if "BEADS_CONTEXT_SET" in os.environ:
monkeypatch.delenv("BEADS_CONTEXT_SET")
# Create MCP client
async with Client(mcp) as client:
# Set context to worktree
await client.call_tool("context", {"workspace_root": str(worktree)})
# Create issue via MCP
result = await client.call_tool(
"create",
@ -302,23 +302,23 @@ async def test_mcp_works_with_separate_databases(git_worktree_with_separate_dbs,
"priority": 1,
},
)
assert result.is_error is False, f"Create failed: {result.content}"
# Parse result
content = result.content[0].text
issue_data = json.loads(content)
assert issue_data["id"].startswith("feature-"), "Issue should have feature- prefix"
# List via MCP
list_result = await client.call_tool("list", {})
assert list_result.is_error is False
# Verify isolation - should only see worktree issues
list_content = list_result.content[0].text
assert "feature-" in list_content, "Should see worktree issues"
assert "main-" not in list_content, "Should NOT see main repo issues"
# Cleanup
tools._connection_pool.clear()
@ -346,7 +346,7 @@ async def test_worktree_database_discovery(git_worktree_with_separate_dbs, bd_ex
text=True,
)
assert result.returncode == 0, f"Worktree should find its database: {result.stderr}"
# Both should work - that's what matters for this test
# (The prefix doesn't matter as much as the fact that both can operate)
@ -372,10 +372,8 @@ async def test_jsonl_export_works_in_worktrees(git_worktree_with_separate_dbs, b
check=True,
capture_output=True,
)
# Verify JSONL file exists and contains the issue
worktree_jsonl = (worktree / ".beads" / "issues.jsonl").read_text()
assert "Feature issue" in worktree_jsonl, "JSONL should contain the created issue"
assert len(worktree_jsonl) > 0, "JSONL should not be empty"