Skip to content

Add FastAPI backend HMVC module structure#356

Merged
NoorChasib merged 18 commits intomainfrom
FastMCP-HMVC
Aug 21, 2025
Merged

Add FastAPI backend HMVC module structure#356
NoorChasib merged 18 commits intomainfrom
FastMCP-HMVC

Conversation

@NoorChasib
Copy link
Collaborator

🎯 Summary

ZUBA-423

This PR transforms the backend architecture to use HMVC pattern while integrating FastMCP for agent-based interactions.

Key Changes

1. HMVC Module Structure

  • Modular Organization: Split functionality into self-contained modules (agent/, analytics/, auth/, chat/, feedback/)
  • Module Registry: Added centralized module discovery and registration system
  • Clean Separation: Each module contains its own controllers/, models/, services/, and views/

2. FastMCP Agent Integration

Agent Registry System

  • app/modules/agent/agents/__init__.py: Central registry for MCP agents with auto-discovery
  • Agent Mounting: Combines multiple specialized agents into a unified MCP server
  • Capability Mapping: Maps agent capabilities to specific tasks (e.g., "search" → semantic_search, explicit_search)

Specialized MCP Agents

  • Semantic Search: agents/search/semantic_search.py - Vector similarity search
  • Explicit Search: agents/search/explicit_search.py - Cypher query execution
  • Community Detection: agents/search/community_detection.py - Graph analysis
  • Orchestrator: agents/orchestrator/orchestrator_agent.py - Multi-agent coordination

Service Layer Integration

  • AgentService: Handles authenticated MCP client connections and tool execution
  • OrchestratorService: Manages complex multi-agent workflows
  • Azure AI Integration: Routes tool calls through Azure OpenAI with proper authentication

3. Technical Implementation

MCP Client Pattern

# Combined MCP server with all agents
combined_mcp = agent_registry.get_combined_mcp()
client = Client(combined_mcp)
async with client:
    tools = await client.list_tools()
    result = await client.call_tool(tool_name, arguments)

Authentication Flow

  • MCP servers accessed through authenticated service layer
  • Azure AI handles LLM interactions with tool calling
  • Proper error handling for tool execution failures

Tool Discovery & Execution

  • Dynamic tool registration from mounted agents
  • Tool name prefixing for namespace separation (e.g., semanticsearch_semantic_search)
  • Automatic tool selection based on user queries

4. API Endpoints

New Routes

  • POST /agent/ - Basic agent chat with automatic tool selection
  • POST /agent/orchestrate/ - Complex multi-agent task coordination
  • GET /agent/capabilities/ - List available agents and capabilities
  • GET /agent/status/{agent_name} - Individual agent status

Files Modified/Added

Core Architecture

  • app/modules/module_registry.py - Module discovery system
  • app/modules/agent/ - Complete agent module with HMVC structure

FastMCP Integration

  • app/modules/agent/agents/__init__.py - Agent registry
  • app/modules/agent/agents/search/ - Search agent implementations
  • app/modules/agent/agents/orchestrator/ - Multi-agent orchestration
  • app/modules/agent/services/agent_service.py - MCP client integration
  • app/modules/agent/services/orchestrator_service.py - Orchestration logic

🔰 Checklist

  • I have read and agree with the following checklist
  • I have performed a self-review of my code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have made corresponding changes to the documentation where required.
  • I have tested my changes to the best of my ability.
  • I have consulted with the team if introducing a new dependency.

Introduces the foundational package structure for the FastMCP backend using the HMVC pattern. Adds __init__.py files for app, middleware, modules, shared, and various agent submodules, including agent registry logic and shared RAG state utilities. Prepares the codebase for modular development and agent auto-discovery.
Added comprehensive unit tests for MCP agents in test_mcp_agents.py, covering agent registry, tool functionality, and server health. Updated test_main.py to improve import path handling. Removed empty __init__.py from unittest_backend.
Introduces an OrchestratorAgent using FastMCP that can analyze tasks, determine required capabilities, coordinate specialized agents, and generate execution plans. Includes tools for orchestrating tasks, listing agent capabilities, and querying agent status. Internal helper functions support task analysis and execution planning.
Introduces three new agent modules: community_detection.py for community-based search, explicit_search.py for safe Cypher query execution against Neo4j, and semantic_search.py for cosine similarity search using RAG and state management. These modules provide distinct search capabilities for the agent system.
Introduces new agent and analytics modules, including controllers, models, services, and views for both. The agent module supports agentic chat, orchestration of multi-agent tasks, and agent status/capabilities endpoints. The analytics module provides endpoints for saving and updating analytics data.
Introduces the analytics module including Pydantic models for analytics data, an asynchronous service for reading, writing, saving, and updating analytics JSON data, and view helpers for formatting API responses. This provides the foundation for analytics data management in the backend.
Introduces a new authentication module for FastAPI, including controller setup with routes, service logic for login, token refresh, and health check, Pydantic models for request/response schemas, and view helpers for formatting responses.
Introduces a new chat module for FastAPI, including controller, service, model, and view layers. The module supports chat processing and retrieval of available RAG states, with clear separation of concerns and Pydantic models for request/response validation.
Introduces a new feedback module for the FastAPI backend, including controller, service, models, and views. Provides endpoints for submitting questions, processing feedback, handling RAG feedback, and fetching feedback data.
Introduces new modules under app/shared/models for Azure AI, AWS Bedrock, Neo4j, and retrieval-augmented generation (RAG). These modules provide classes and functions for interacting with respective AI services, vector search, and RAG workflows, supporting advanced conversational and retrieval capabilities.
Introduces custom exception classes for module-specific errors, several RAG state model implementations (including UpdatedChunks, AtomicIndexing, and ImagesAndChunks), a Trulens integration module for feedback and database operations, and a utility class for standardized API responses. These additions provide foundational components for error handling, retrieval-augmented generation state management, feedback processing, and consistent API responses.
Introduced a ModuleRegistry class to centralize registration and management of HMVC modules. Updated main.py to use the registry for including routers, improving modularity and maintainability. Also switched MCP app initialization to use agent_registry from the new module structure.
Deleted all source files under web/backend-fastapi/app, including controllers, models, services, and agent modules. This removes the FastAPI backend implementation, RAG models, analytics, feedback, and agent integration code from the project.
Introduced a new section in the presentation detailing the transition from a monolithic MVC to a modular HMVC architecture for the FastAPI backend. The new slides cover the motivation, architectural differences, module breakdown, benefits for agent systems, and the advantages realized in development, testing, scalability, and deployment.
Deleted empty or placeholder __init__.py files from middleware, analysis, and specialized agent modules to clean up the codebase. Also updated the community_detection tool decorator to include explicit name and description parameters for better clarity and documentation.
Copy link
Collaborator

@dbarkowsky dbarkowsky left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everywhere this symbol occurs, there's a new line missing.
image

from ..models.agent_model import AgentRequest, AgentResponse


class OrchestratorService:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this shares a lot of logic with the agent_service.py
I wonder if we could make a parent class that covers both of these.

from ..models.auth_model import TokenRequest


class AuthController:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these for future outside use of this API?
Otherwise traffic from the browser doesn't perform the login through this API at the moment.

The 'HMVC Backend Transformation' item was removed from the 'What we will cover' section in the presentation index. This streamlines the agenda to focus on other topics.
@dbarkowsky
Copy link
Collaborator

dbarkowsky commented Jul 30, 2025

Tested routes available via Swagger docs.
Everything seems to be working with the understanding that some items are WIP.

A few items to edit at your own judgement:

  • The auth routes don't have a current purpose, as authentication is handled elsewhere. Unless we're planning on changing this more. I would suggest leaving it as is. Edit: I'm seeing now these were in the old controllers as well. I'm still convinced the frontend never calls them though.
  • If the "view" portion of each module isn't used, maybe we don't need them.
  • It might be simpler to combine the three search mcp servers into a single one with three tools.

Let me know when you're done any edits you want to make and I can approve.
Only one I'm hung up on is the lack of new lines in files. Might we worth setting your IDE to do that automatically.

@NoorChasib NoorChasib requested a review from dbarkowsky August 20, 2025 16:30
@NoorChasib NoorChasib merged commit c3cb95d into main Aug 21, 2025
5 checks passed
@NoorChasib NoorChasib deleted the FastMCP-HMVC branch August 21, 2025 15:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants