LogoLogo
CommunityBlogLicense
latest
latest
  • Overview
  • Social Registry
    • Features
      • Individuals and Households
        • 📔User Guides
          • 📔Create an Individual Registrant
          • 📔Create a Group and Add Individual Registrants to the Group
          • 📔Import CSV file to Social Registry
      • Offline Capabilities
        • ODK Importer
          • 📔User Guide
            • 📔Configure and Import ODK Form
            • 📔Import Specific ODK Forms using ODK Instance ID
        • Enumerator ID
      • Online Self Registration
      • Online Assisted Registration
        • 📔User Guides
          • 📔Create a New Household
          • 📔Create a New Individual in Registration Portal
          • 📔Create a New Portal User
          • 📔Configure Portal User to Limit Accessing Location
      • Deduplication
        • 📔User Guides
          • 📔Configure ID Deduplication, Deduplicate, and Save Duplicate Groups/Individuals
        • Deduplicator Service
      • Locking of Records
      • Dynamic Registry
      • Document Storage
      • Configurability
        • 📔User Guide
          • 📔Configure ID Types
          • 📔Configure Registrant Tags
          • 📔Configure Gender Types
          • 📔Configure Relationships
          • 📔Configure Group Types
          • 📔Configure Group Membership Kind
      • Role Based Access Control
        • 📔User Guide
          • 📔Create User
          • 📔Assign a Role to a User
      • Geo Targeting
      • Data Sharing
      • Multi-language Support
        • 📔User Guides
          • 📔Set Language Preference
      • Privacy and Security
      • Interoperability
      • Real-time Reporting
      • Monitoring and Reporting
      • ID Integration
        • ID Validation and Tokenisation
        • ID Authentication
          • 📔User Guides
            • 📔Configure eSignet Auth Provider for ID Authentication
            • 📔ID Authentication Process
            • 📔eSignet Client Creation
        • eSignet Integration
        • Fayda ID Integration
      • Verifiable Credentials Issuance
        • 📔User Guides
          • 📔Configure Inji to download Social Registry VCs
      • Automatic Computation of PMT
      • Record Revision History
      • SPAR Integration for Account Info
      • Unique Social ID
      • Audit Logs
      • Rapid Deployment Framework
      • Performance & Scale
      • Draft and Publish
      • Claim and Attest
    • Versions
    • Deployment
      • Domain names and Certificates
      • Install Odoo Modules
      • Packaging
        • 📘Docker Packaging Guide
        • 📘Helm Packaging Guide
    • Developer Zone
      • Technology Stack
      • API Reference
        • Search APIs
        • Individual APIs
        • Group APIs
      • Repositories
      • Background Tasks
      • Developer Install
        • 📘Developer Install of OpenG2P Package on Linux
      • Design Notes
        • Data Sharing
      • Odoo Modules
        • G2P Registry Datashare: RabbitMQ
        • ODK App User Mapping
      • Performance Testing
  • PBMS
    • Features
      • Program Management
        • Role of a Program Manager
        • Program Life Cycle
      • Program Disbursement Cycles
        • 📔User Guides
          • 📔Create Program Fund
          • 📔Create Cycle Manager for a Program
      • Beneficiary Management
        • Beneficiary Registry
          • 📔User Guides
            • 📔Create an Individual Registrant
            • 📔Create a Group and Add Individual Registrants to the Group
            • 📔Assign a Program to a Group
            • 📔Assign a Program to an Individual
        • Beneficiary Registry Configurations
          • 📔User Guides
            • 📔Configure ID Types
            • 📔Configure Registrant Tags
            • 📔Configure Gender Types
            • 📔Configure Relationships
            • 📔Configure Group Types
            • 📔Configure Group Membership Kind
        • Registration
          • 📔User Guides
            • 📔Import CSV File to Registry Module
      • ID Verification
      • Eligibility
        • Proxy Means Test
        • 📔User Guides
          • 📔Create Eligibility Manager Types
            • 📔Configure Default Eligibility Manager
            • 📔Create ID Document Eligibility Manager
            • 📔Create Phone Number Eligibility Manager
          • 📔Configure Proxy Means Test
          • 📔Verify Eligibility of Enrolled Registrants
      • Deduplication
        • 📔User Guides
          • 📔Deduplicate Registrants
          • 📔Create Deduplication Manager Types
            • 📔Configure Default Deduplication Manager
            • 📔Create ID Deduplication Manager
            • 📔Create Phone Number Deduplication
      • Enrolment
        • 📔User Guides
          • 📔Enroll Registrants into Program
          • 📔Auto-Enroll New Registrants into a Program
          • 📔Enroll Eligible Individual Registrants into a Program
      • Entitlement
        • 📔User Guides
          • 📔Multi-Stage Approval
          • 📔Create Entitlement Manager Type
            • 📔Create Default Entitlement Manager
            • 📔Create Voucher Entitlement Manager
            • 📔Configure Cash Entitlement Manager
          • 📔Create Entitlement Voucher Template
          • 📔Configure the Payments File with QR Code
          • 📔Configure Default Cycle Managers
          • 📔Export Beneficiaries Approved Entitlement
      • Disbursement
        • Payment Batches
        • In-Kind Transfer
          • 📔User Guides
            • 📔Create a Product in Inventory
            • 📔Configure In-Kind Entitlement Manager
            • 📔Create and Approve Program Cycle
            • 📔Verify Eligibility of Registrants in a Cycle
        • Digital Cash Transfer
        • e-Voucher
        • 📔User Guides
          • Prepare and Send Payment
      • Self Service Portal
        • 📔User Guides
          • 📔Create Form and Map with Program
          • 📔Configure Login Providers for Beneficiary Portal
          • 📔Self Register Online
      • Document Management
      • Multi-tenancy
      • Notifications
        • 📔User Guides
          • 📔Send Notifications to Individual Registrants
          • 📔Create Notification Manager Types
            • 📔Create SMS Notification Manager
            • 📔Create Email Notification Manager
            • 📔Create Fast2SMS Notification Manager
          • 📔Create Notification Manager under Program
      • Accounting
      • Administration
        • RBAC
          • 📔User Guides
            • 📔Create User and Assign Role
            • 📔Configure Keycloak Authentication Provider for User Log in
        • i18n
      • ODK Importer
        • 📔User Guides
          • 📔Configure and Import ODK Form
          • 📔Import Specific ODK Forms using ODK Instance ID
          • 📔Import Social Registry Data into PBMS
      • MTS Connector
        • 📔User Guides
          • 📔Create MTS Connector
            • 📔Create ODK MTS Connector
            • 📔Create OpenG2P Registry MTS Connector
      • Audit Logs
      • Service Provider Portal
        • 📔User Guides
          • 📔Submit Reimbursement Using the Service Provider Portal
          • 📔Reimburse the Service Provider
      • Interoperability
      • Privacy and Security
      • Periodic Biometric Authentication for Beneficiaries
      • Beneficiary Exit Process
      • Verifiable Credential Issuance
        • 📔User Guides
          • 📔Configure Inji to download Beneficiary VCs
      • Deduplication
      • Manual In-Kind Entitlement
      • Print Disbursement Summary
      • Monitoring & Reporting
        • Logging
      • Priority List
      • Offline Capabilities
      • Grievance Redress Mechanism
    • Versions
    • Developer Zone
      • Odoo Modules
        • G2P Enumerator
        • OpenG2P Registry MTS Connector
        • G2P Documents Store
        • MTS Connector
        • G2P Formio
        • G2P Registry: Rest API Extension Demo
        • G2P Registry: Additional Info REST API
        • G2P Registry: Bank Details Rest API
        • G2P Registry: Additional Info
        • G2P Registry: Membership
        • G2P Registry: Groups
        • G2P Registry: Individual
        • G2P Registry: Base
        • G2P Registry: Rest API
        • G2P Registry: Bank Details
        • G2P Registry: Security
        • G2P Service Provider Beneficiary Management
        • OpenG2P Program Payment (Payment Hub EE)
        • OpenG2P Program Payments: In Files
        • G2P Program : Program Registrant Info Rest API
        • OpenG2P Entitlement: Differential
        • OpenG2P Program: Approval
        • OpenG2P Program: Assessment
        • G2P Program: Registrant Info
        • OpenG2P Program Payment: Simple Mpesa Payment Manager
        • OpenG2P Programs: Cycleless
        • OpenG2P Entitlement: In-Kind
        • G2P Notifications: Wiserv SMS Service Provider
        • G2P: Proxy Means Test
        • G2P Programs: REST API
        • G2P Program Payment (Payment Interoperability Layer)
        • OpenG2P Entitlement: Voucher
        • OpenG2P Programs: Reimbursement
        • OpenG2P Program Payment: Cash
        • OpenG2P Program: Documents
        • OpenG2P Program Payment: G2P Connect Payment Manager
        • OpenG2P Programs: Autoenrol
        • G2P ODK Importer
        • OpenID Connect Authentication
        • G2P Auth: OIDC - Reg ID
        • G2P OpenID VCI: Base
        • G2P OpenID VCI: Programs
        • G2P OpenID VCI: Rest API
        • G2P Program Datashare: RabbitMQ
      • Developer Install on Linux
      • Repositories
        • openg2p-fastapi-common
          • OpenG2P FastAPI Common
          • OpenG2P FastAPI Auth
          • OpenG2P Common: G2P Connect ID Mapper
        • social-payments-account-registry
        • g2p-bridge
        • openg2p-packaging
        • openg2p-security
        • spar-load-test
        • 4sure
        • G2P SelfServicePortal
      • Technology Stack
    • Deployment
      • i18n
      • Installation of Odoo Modules
      • Domain names and Certificates
      • Helm Charts
  • SPAR
    • Features
      • SPAR Mapper
      • SPAR Self Service
      • Privacy & Security
      • Interoperability
      • Performance & Scale
      • Monitoring & Reporting
    • Deployment
      • Domain Names and Certificates
      • Helm Charts
    • 📔User Guides
      • 📔Link FA (Self Service)
      • 📔Link FA (Admin)
    • Development
      • Jira Board
      • Testing
        • Unit Testing
        • Functional Testing
        • Performance Testing
          • Mapper
            • Resolve API
            • Link API
            • Unlink API
            • Update API
      • Developer Install
        • SPAR Mapper API
        • SPAR Self Service API
        • SPAR Self Service UI
      • Repositories
      • API Reference
      • Tech Guides
    • Releases
      • 1.0.0
      • 1.1.0
  • G2P Bridge
    • Features
      • Extensibility - Connect to Sponsor Banks
      • Account Mapper Resolution
      • Reconciliation with Sponsor Bank
      • Scaling for High Volumes
      • Interoperability
      • Privacy & Security
      • Monitoring & Reporting
    • Deployment
      • Deployment of G2P Bridge
      • Deployment of Example Bank
      • Bank Connector Interface Guide
      • PBMS Configuration
    • Developer Zone
      • Design
        • IN APIs from PBMS
          • create_disbursement_envelope
          • cancel_disbursement_envelope
          • create_disbursements
          • cancel_disbursements
          • get_disbursement_envelope_status
          • get_disbursement_status
        • OUT APIs to Mapper
          • resolve
        • OUT APIs to Bank
          • check_funds_with_bank
          • block_funds_with_bank
          • disburse_funds_from_bank
        • IN APIs from Bank
          • upload_mt940
        • Helper Tables
          • benefit_program_configuration
        • Configuration parameters
        • Bank Connectors
        • Physical Organization
        • Example Bank
          • example-bank-models
          • example-bank-api
          • example-bank-celery
      • Testing
        • Unit Testing
        • Functional Testing
        • Performance Testing
      • Repositories
      • Developer Install
        • G2P Bridge
        • Example Bank
      • API Reference
    • Tech Guides
    • User Guides
    • Releases
      • 1.0.2
  • PBMS-Gen2
    • Developer Zone
      • Design
        • Concept
        • PBMS (Odoo)
  • Utilities and Tools
    • ODK
      • 📔User Guides
        • 📔Create a Project for a Program
        • 📔Create a Form
        • 📔Upload a Form
        • 📔Upload revised Form
        • 📔Test a Form
        • 📔Publish a Form
        • 📔Provide Form Access to Field Agent
        • 📔Download a Form on ODK Collect
        • 📔Delete a Form
        • 📔Register Offline
    • 4Sure Verifier App
      • Installation Guide for 4Sure Application
      • 📔User Guides
        • 📔Verify Digital Credentials using 4Sure Application
        • 📔Verify and Populate the form in ODK Collect using 4Sure Application
      • 4Sure Test Summary
    • Smartscanner
      • 📔User Guides
    • Registration Tool Kit
    • Unified Conversation Agent (UCA)
      • Modal Context Protocol(MCP)
      • Model Context Protocol (MCP) Implementation in UCA
      • Social Benefits Assistant with FastMCP
  • Testing
    • Test Workflow
    • Automation Framework
  • Monitoring and Reporting
    • Apache Superset
    • Reporting Framework
      • 📔User Guides
        • 📔Connector Creation Guide
        • 📔Dashboards Creation Guide
        • 📔Installation & Troubleshooting
      • Kafka Connect Transform Reference
    • System Logging
    • System Health
  • Privacy and Security
    • Key Manager
  • Data Share
    • OpenG2P - IUDX
  • Interoperability
  • Deployment
    • Base Infrastructure
      • Wireguard Bastion
        • Install WireGuard Client on Android Device
        • Wireguard Access to Users
        • Install WireGuard Client on Desktop
      • NFS Server
      • Rancher Cluster
      • OpenG2P Cluster
        • Kubernetes
          • Firewall
          • Istio
          • Adding Nodes to Cluster
          • Deleting Nodes from Cluster
        • Prometheus & Grafana
        • Fluentd & OpenSearch
          • DEPRECATED - OpenSearch
        • Landing Page For OpenG2P
      • Load Balancer
        • Nginx
        • AWS
    • Resource Requirements
    • Helm Charts
    • Upgrades
    • Production
    • OpenG2P In a Box
    • Packaging
    • Versioning
    • Additional Guides
      • Automatic Build and Upload of Private Dockers
      • Generate SSL Certificates using Letsencrypt
      • Packaging Odoo based Docker
      • AWS
        • Create ACM Certificate on AWS
        • Create Security Group on AWS
        • Domain mapping on AWS Route53
        • Make Environment Publicly Accessible using AWS LB Configuration
      • Private Access Channel
      • Odoo Post Install Configuration
      • Pulling Docker from Private Repository on Docker Hub
      • Keycloak Client Creation
      • Troubleshooting: "fsnotify watcher" warning
      • Uninstalling Applications from Rancher UI
      • Access a Database from Outside the Cluster
      • Configure External Database to Connect OpenG2P Environment
      • Configure IPSec VPN Gateway to Connect to External Systems using Strongswan
      • Troubleshooting
        • PostgreSQL Database not Starting due to Replication Checkpoint Error
        • No Space Left on the Device Warning
      • Restart Deployment or StatefulSets to Redistribute Pods across Nodes
      • Rerun Jobs in Kubernetes Cluster
      • Finding URLs in the System
      • Transitioning PostgreSQL From Docker on K8s to Standalone PostgreSQL
      • Restore a PVC from an NFS Folder and Attach it to a Pod
      • View System Logs on the OpenSearch Dashboard
      • Set up Slack alerts for a Kubernetes cluster
      • Importing Dashboards on the Superset UI for OpenG2P Applications
      • Scaling Down an Environment to Optimize Resource Usage
      • Kubernetes Master Nodes
      • Enabling Keycloak User Self-Registration
      • Automating Cache Cleanup on K8s Cluster Nodes with Cron Job
      • Set Up Slack Alerts for a Standalone Node using Netdata
    • Persistent Storage
      • Resizing Persistent Volume Claim in Kubernetes Cluster
  • 📒Guides
    • 📔User Guides
      • PBMS
        • 📔Create Program
        • 📔Configure Payment Manager in Program
        • 📔Create Eligibility Manager under Program
        • 📔Create Program Manager for a Program
        • 📔Create Manager Type
          • 📔Create Payment Manager Types
            • 📔Create Payment Hub EE Payment Manager
            • 📔Create Payment Interoperability Layer Payment Manager
            • 📔Create Default Payment Manager
            • 📔Create Cash Payment Manager
            • 📔Create File Payment Manager
        • 📔Configure Entitlement Manager under Program
        • 📔Archive, Delete, End, and Re-activate a Program
        • 📔Configure Default Program Manager
        • 📔Create Deduplication Manager under Program
    • Documentation Guides
      • Documentation Guidelines
        • Embed a Miro diagram
      • OpenG2P Module Doc Template
  • Use Cases
    • Farmer Registry
      • Reference Design: Farmer Registry
  • Releases
    • 1.1.0
      • Release Notes
  • License
    • OpenG2P Support Policy
  • Community
    • Contributing
    • Code of Conduct
  • Blogs
    • OpenG2P and SDG Goals
Powered by GitBook
LogoLogo

Copyright © 2024 OpenG2P. This work is licensed under Creative Commons Attribution International LicenseCC-BY-4.0 unless otherwise noted.

On this page
  • Introduction
  • Key Features
  • Why FastMCP?
  • Architecture Overview
  • System Architecture:
  • Key Architectural Decisions
  • Communication Flow
  • FastMCP Integration
  • What is FastMCP?
  • Integration Approach
  • Benefits of FastMCP Integration
  • System Components
  • Overview
  • Component Interaction
  • Database Architecture
  • Eligibility Server
  • Architecture
  • Key Components
  • Data Models
  • Grievance Server
  • Architecture
  • Key Components
  • Data Models
  • MCP Client
  • Architecture
  • Key Features
  • Conversation Management

Was this helpful?

  1. Utilities and Tools
  2. Unified Conversation Agent (UCA)

Social Benefits Assistant with FastMCP

FastMCP is a higher-level, decorator-based Python framework that simplifies building Model Context Protocol (MCP) servers by providing an interface for registering tools, resources, and prompts.


Introduction

The Social Benefits Assistant is a sophisticated system designed to help users navigate social benefit programs and handle grievances. Built using the Model Context Protocol (MCP) framework with FastMCP implementation, it provides a modern, scalable architecture for AI-powered assistance.

Key Features

  • Program Eligibility Assessment: Helps users find relevant social programs and assess their eligibility

  • Grievance Management: Handles user complaints, creates tickets, and tracks status

  • Natural Language Interface: Powered by Ollama LLMs for conversational interactions

  • Modular Architecture: Separate MCP servers for different subsystems

  • Standardized Communication: Uses MCP protocol for all inter-component communication

Why FastMCP?

FastMCP provides a cleaner, more ergonomic interface for building MCP servers. Key advantages include:

  • Decorator-based tool registration

  • Built-in support for resources and prompts

  • Standard transport mechanisms (stdio, SSE, WebSocket)

  • Proper context management

  • Type-safe implementations


Architecture Overview

The Social Benefits Assistant uses a distributed architecture based on the Model Context Protocol (MCP). The system consists of three main components:

System Architecture:

Key Architectural Decisions

  1. Separation of Concerns: Each subsystem (eligibility, grievance) has its own MCP server

  2. Standard Protocol: All communication uses the MCP protocol

  3. LLM Integration: Ollama serves as the intelligent routing layer

  4. Tool-Based Interface: Each server exposes functionality through MCP tools

  5. Resource Management: Static data is exposed through MCP resources

  6. Prompt Templates: Response formatting is handled through MCP prompts

Communication Flow

  1. User sends query to the MCP client

  2. Client uses Ollama to analyze intent

  3. Based on intent, client calls appropriate MCP server(s)

  4. Server processes request using tools

  5. Server returns results via MCP protocol

  6. Client formats response using prompts and Ollama

  7. Final response is presented to user


FastMCP Integration

What is FastMCP?

FastMCP is a higher-level interface for the Model Context Protocol that simplifies the creation of MCP servers. It provides a more ergonomic API compared to the low-level MCP implementation.

Integration Approach

Our integration of FastMCP involved:

1. Server Creation

Instead of using the low-level Server class, we use FastMCP:

from mcp.server.fastmcp import FastMCPeligibility_server = FastMCP(    name="EligibilityServer",    instructions="Eligibility subsystem for Social Benefits Assistant...")

2. Tool Registration

Tools are registered using decorators instead of manual registration:

@eligibility_server.tool(description="Extract user profile details from query")async def extract_user_details(query: str, ctx: Context) -> UserProfile:    # Tool implementation    pass

3. Resource Definition

Resources are defined with decorators for dynamic content:

@eligibility_server.resource("program://{program_id}/eligibility")async def program_eligibility_resource(program_id: int) -> str:    # Resource implementation    pass

4. Prompt Templates

Prompts are registered for response formatting:

@eligibility_server.prompt()def eligibility_response(programs: List[Dict], analysis: List[Dict], user_profile: Dict) -> List:    # Prompt implementation    pass

5. Context Management

FastMCP provides a Context object for accessing MCP features:

async def my_tool(param: str, ctx: Context) -> str:    # Access session, logging, progress reporting    await ctx.report_progress(50, 100)    await ctx.info("Processing...")    return result

Benefits of FastMCP Integration

  1. Cleaner Code: Decorator-based registration is more intuitive

  2. Type Safety: Better type hints and validation

  3. Built-in Features: Automatic parameter validation, error handling

  4. Standard Patterns: Follows Python conventions

  5. Easier Testing: Better separation of concerns


System Components

Overview

The Social Benefits Assistant consists of three main components:

  1. Eligibility Server: Handles program search and eligibility assessment

  2. Grievance Server: Manages user complaints and ticket tracking

  3. MCP Client: Orchestrates communication and provides user interface

Each component is built using FastMCP and follows standard MCP patterns.

Component Interaction

A[User Query] --> B[MCP Client]    B --> C{Intent Analysis}    C -->|Eligibility Query| D[Eligibility Server]    C -->|Grievance Query| E[Grievance Server]    D --> F[Database]    E --> G[Database]    D --> H[FAISS Index]    B --> I[Ollama LLM]

Database Architecture

The system uses two databases:

  1. Program Database (program_db):

    • Stores program information

    • Used by Eligibility Server

    • Includes FAISS index for semantic search

  2. Grievance Database (grievance_db.sqlite):

    • Stores user memberships

    • Tracks complaints and tickets

    • Used by Grievance Server


Eligibility Server

The Eligibility Server is responsible for helping users find relevant social benefit programs and assess their eligibility.

Architecture

eligibility_server = FastMCP(    name="EligibilityServer",    instructions="Eligibility subsystem for Social Benefits Assistant...")

Key Components

1. Database Connection

Uses aiosqlite for async database operations:

@asynccontextmanagerasync def get_db_connection(db_path: str):    conn = await aiosqlite.connect(db_path)    conn.row_factory = aiosqlite.Row    try:        yield conn    finally:        await conn.close()

2. FAISS Integration

Semantic search using FAISS and HuggingFace embeddings:

embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")vector_store = FAISS.load_local(faiss_index_path, embeddings)retriever = vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 3})

3. Tools

extract_user_details

Extracts user profile information from queries:

@eligibility_server.tool(description="Extract user profile details from query")async def extract_user_details(query: str, ctx: Context) -> UserProfile:    # Implementation using pattern matching and NLP

search_programs

Finds relevant programs using semantic search:

@eligibility_server.tool(description="Search for relevant programs based on query")async def search_programs(query: str, ctx: Context) -> List[int]:    # FAISS-based semantic search

analyze_eligibility

Assesses eligibility for specific programs:

@eligibility_server.tool(description="Analyze program eligibility based on user profile")async def analyze_eligibility(    program_ids: List[int],     user_profile: Optional[UserProfile] = None,    ctx: Context = None) -> EligibilityResult:    # Rule-based eligibility analysis

4. Prompts

eligibility_response

Formats eligibility results for user presentation:

@eligibility_server.prompt()def eligibility_response(programs: List[Dict], analysis: List[Dict], user_profile: Dict) -> List:    # Response formatting logic

5. Resources

program_eligibility_resource

Provides eligibility information for specific programs:

@eligibility_server.resource("program://{program_id}/eligibility")async def program_eligibility_resource(program_id: int) -> str:    # Returns program eligibility criteria

Data Models

UserProfile

class UserProfile(BaseModel):    income_level: Optional[str] = None    family_size: Optional[int] = None    location: Optional[str] = None    housing_status: Optional[str] = None    employment_status: Optional[str] = None    age: Optional[int] = None    # ... other fields

ProgramInfo

class ProgramInfo(BaseModel):    id: int    name: str    description: str    eligibility_criteria: str    benefits: str    application_process: str

EligibilityAnalysis

class EligibilityAnalysis(BaseModel):    program_id: int    program_name: str    eligibility_likelihood: Literal["High", "Medium", "Low", "Unknown"]    matching_criteria: List[str]    missing_information: List[str]

Grievance Server

The Grievance Server handles user complaints, ticket creation, and status tracking.

Architecture

grievance_server = FastMCP(    name="GrievanceServer",    instructions="Grievance subsystem for Social Benefits Assistant...")

Key Components

1. Tools

identify_user_id

Checks if query contains a valid USER ID:

@grievance_server.tool(description="Identify if a user input contains a valid USER ID format")async def identify_user_id(query: str, ctx: Context) -> UserIdResult:    # Regex-based pattern matching for USER### format

verify_user

Verifies user credentials and retrieves information:

@grievance_server.tool(description="Verify if a user ID exists and retrieve user information")async def verify_user(user_id: str, ctx: Context) -> UserVerificationResult:    # Database lookup and verification

process_complaint

Analyzes complaints for completeness:

@grievance_server.tool(description="Process a complaint and determine if enough information has been collected")async def process_complaint(    complaint: str,     previous_parts: Optional[List[str]] = None,    is_follow_up: bool = False,    ctx: Context = None) -> ComplaintAnalysis:    # NLP-based complaint analysis

create_ticket

Creates support tickets for complaints:

@grievance_server.tool(description="Create a ticket in the database for a grievance")async def create_ticket(    user_id: str,     complaint: str,     program_id: Optional[int] = 0,    ctx: Context = None) -> TicketDetails:    # Ticket generation and database insertion

check_status

Checks program enrollment or ticket status:

@grievance_server.tool(description="Check status of a program enrollment or specific ticket")async def check_status(    user_id: str,     ticket_id: Optional[str] = None,    ctx: Context = None) -> StatusCheckResult:    # Status retrieval from database

2. Prompts

  • user_verification_response: Formats successful verification

  • verification_failed_response: Handles failed verification

  • ticket_creation_response: Confirms ticket creation

  • status_check_response: Presents status information

3. Resources

  • user_status_resource: Provides user status information

  • ticket_details_resource: Returns ticket details

Data Models

UserDetails

class UserDetails(BaseModel):    user_id: str    user_name: str    status: Optional[str] = None    enrollment_date: Optional[str] = None    program_id: Optional[int] = None

ComplaintAnalysis

class ComplaintAnalysis(BaseModel):    complaint: str    enough_detail: bool = False    program_mentioned: str = "Unspecified"    issue_category: str = "Other"    missing_information: List[str] = Field(default_factory=list)

MCP Client

The MCP Client serves as the central orchestrator, connecting to Ollama LLM and routing queries to appropriate MCP servers.

Architecture

The client implements the MCP protocol to communicate with FastMCP servers:

class MCPClientApp:    def __init__(        self,        eligibility_url: str = "http://localhost:8000/sse",        grievance_url: str = "http://localhost:8001/sse",        ollama_url: str = "http://localhost:11434",        model: str = "llama2:8b"    ):        # Initialize connections

Key Features

1. Ollama Integration

Direct integration with Ollama for LLM capabilities:

class OllamaClient:    async def generate(self, prompt: str, system_prompt: str = None) -> str:        # Ollama API communication

2. Intent Analysis

Determines which subsystem to use:

async def analyze_intent(self, query: str) -> str:    # Rule-based intent classification    # Returns "eligibility" or "grievance"

3. Server Connection

Establishes SSE connections to MCP servers:

async def connect_to_servers(self):    eligibility_streams = await sse_client(self.eligibility_url)    self.eligibility_session = await self._create_session(eligibility_streams)        grievance_streams = await sse_client(self.grievance_url)    self.grievance_session = await self._create_session(grievance_streams)

4. Query Processing

Routes queries based on intent:

async def process_query(self, query: str) -> str:    intent = await self.analyze_intent(query)        if intent == "grievance":        return await self.process_grievance_query(query)    else:        return await self.process_eligibility_query(query)

5. Tool Calling

Uses MCP protocol to call server tools:

# Example: Calling eligibility tooluser_details = await self.eligibility_session.call_tool(    "extract_user_details",    {"query": query, "ctx": {}})

Conversation Management

The client maintains conversation history with Ollama:

# Conversation history is tracked in OllamaClientself.conversation_history = []# History is included in each requestmessages = [    {"role": "system", "content": system_prompt},    *self.conversation_history,    {"role": "user", "content": prompt}]
PreviousModel Context Protocol (MCP) Implementation in UCANextTesting

Last updated 22 days ago

Was this helpful?