Skip to content

Refactor: extract typed internal API clients for MCP tools #494

Closed

Description

@phernandez

Refactor: extract typed internal API clients for MCP tools

Why

Many MCP tools are thin HTTP clients + formatting with hardcoded paths. This duplicates URL construction, error mapping, and response validation across tools.

Scope

  • Introduce typed internal clients such as:
    • ProjectApi
    • KnowledgeApi
    • ResourceApi
    • SearchApi
  • Each client:
    • exposes typed methods (e.g. resolve_identifier, read_resource, recent_activity)
    • centralizes path building and error handling
  • MCP tools become adapters that call these clients and format results.

Acceptance criteria

  • No hardcoded API paths inside individual MCP tools (or significantly reduced).
  • Centralized error mapping produces consistent ToolError/user messaging.
  • MCP layer stays at 100% (practical) coverage.

Dependencies

  • Best after containers + config injection so tools get a client instance/factory.

Activity

  1. claude commented on Dec 31, 2025

    @claude
    Contributor

    Claude finished @phernandez's task in 2m 1s —— View job


    Issue Triage Complete

    • Read project documentation and understand codebase structure
    • Examine current MCP tools to understand duplication patterns
    • Check if dependencies are met (containers + config injection)
    • Classify issue type, priority, and complexity
    • Add appropriate labels
    • Provide triage assessment and recommendations

    Triage Analysis

    Issue Classification:

    Current State Assessment

    I've examined the MCP tools codebase and identified the following patterns:

    Duplication Found:

    1. URL Construction: Each tool builds paths like /v2/projects/{project_id}/resource/{entity_id} manually
    2. Error Handling: Tools duplicate error-to-ToolError mapping logic
    3. Response Validation: Each tool validates and deserializes responses independently
    4. Identifier Resolution: The resolve_entity_id() function in utils.py is shared, but project/entity lookup patterns are duplicated

    Example from read_note.py (lines 103-117):

    entity_path = memory_url_path(identifier)
    entity_id = await resolve_entity_id(client, active_project.id, entity_path)
    response = await call_get(
        client,
        f"/v2/projects/{active_project.id}/resource/{entity_id}",  # Hardcoded path
        params={"page": page, "page_size": page_size},
    )

    Example from recent_activity.py (lines 254-258):

    response = await call_get(
        client,
        f"/v2/projects/{active_project.id}/memory/recent",  # Hardcoded path
        params=params,
    )
    activity_data = GraphContext.model_validate(response.json())  # Manual validation

    Proposed Architecture

    The issue proposes introducing typed internal API clients:

    • ProjectApi: Project-level operations
    • KnowledgeApi: Entity/knowledge graph operations
    • ResourceApi: Resource content operations
    • SearchApi: Search operations

    This would centralize:

    1. Path construction
    2. Error mapping to consistent ToolError messages
    3. Response validation with Pydantic models
    4. Common patterns (pagination, filtering, etc.)

    Dependency Status

    This refactor depends on:

    1. Issue Refactor: explicit config injection (only roots read ConfigManager) #496 - Explicit config injection (only roots read ConfigManager)

      • Status: Open
      • Why needed: API clients should receive config/client via DI, not read ConfigManager directly
    2. Issue Refactor: introduce ProjectResolver and unify project selection across MCP/API/CLI #493 - Introduce ProjectResolver and unify project selection

      • Status: Open
      • Why needed: API clients need unified project resolution logic
    3. Issue Refactor: reduce coupling + centralize cloud_mode/config wiring #490 - Reduce coupling + centralize cloud_mode/config wiring

      • Status: Open
      • Why needed: Ensure clean separation before adding new abstraction layer

    Assessment: The dependency chain needs to be resolved first. This refactor would be significantly easier after those structural improvements are in place.

    Related Work

    Already Complete:

    Alignment:
    The project follows a "repository pattern for data access" (CLAUDE.md line 58), and the proposed API clients would extend this pattern to the MCP tool layer.

    Recommendations

    1. Implementation Sequence:

    2. Design Considerations:

    • Use Pydantic models for all request/response validation
    • Keep clients thin - they should wrap HTTP calls, not contain business logic
    • Follow the existing call_get/call_post pattern from tools/utils.py
    • Maintain the context manager pattern for client lifecycle
    • Consider async context managers for API client instances if needed

    3. Coverage Strategy:

    • Each API client should have comprehensive unit tests
    • MCP tool tests should continue to verify end-to-end behavior
    • Use mocks for API clients in tool tests to maintain fast execution

    4. Migration Risk:

    • Low: Tools already use context managers and standardized utilities
    • Medium: Need to ensure error messages remain user-friendly (currently very detailed)
    • Medium: Must maintain 100% coverage requirement during migration

    Labels Applied

    • ✅ enhancement - Technical improvement to existing functionality

    Note: Attempted to add component-specific labels, but they don't exist in this repository yet.

    Next Steps

    For project maintainers:

    1. Resolve dependency issues Refactor: explicit config injection (only roots read ConfigManager) #496, Refactor: introduce ProjectResolver and unify project selection across MCP/API/CLI #493, Refactor: reduce coupling + centralize cloud_mode/config wiring #490 first
    2. Review and approve the proposed API client architecture
    3. Consider whether to create additional labels (e.g., mcp, technical-debt, complex)

    For implementation:

    1. Wait for dependency resolution
    2. Create a design document with API client interfaces
    3. Start with a proof-of-concept for one client (ResourceApi recommended)
    4. Get feedback before scaling to other clients

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions