Sponsored by Deepsite.site

ContextualAgentRulesHub

Created By
oshvartz7 months ago
MCP (Model Context Protocol) server designed to manage and provide contextual rules for AI agents
Content

ContextualAgentRulesHub

Overview

ContextualAgentRulesHub is an MCP (Model Context Protocol) server that provides a flexible system for storing and retrieving agent rules that can be used by AI agents to follow context-specific guidelines. The MCP server exposes tools for efficient rule discovery and content retrieval, enabling AI agents to access only the rules relevant to their current task.

Motivation

Managing agent rules effectively can be challenging. Sharing rules across different agents or projects often leads to inconsistencies and difficulties in maintaining a centralized rule set. Furthermore, AI agents often operate with limited context windows. Sending a large, undifferentiated set of rules can consume valuable context space. AgentRulesHub aims to address these issues by:

  • Providing a structured way to organize and access rules.
  • Enabling agents to retrieve only the rules relevant to their current task, thus minimizing context length and improving efficiency.
  • Supporting context-based rule organization for project-specific guidelines.

Key Features

  • Context-Based Rule Organization: Rules can be associated with specific contexts (e.g., project names), allowing for both general and context-specific guidelines
  • Multi-Source Support: Extensible architecture supporting File, Database, Git Repository, and API sources
  • YAML-Based Storage: Human-readable rule storage with metadata and content separation
  • Efficient Indexing: Fast lookups by language, tags, context, and content search
  • Lazy Loading: Rule content is loaded only when needed for optimal performance
  • Flexible Querying: Support for complex queries combining language, tags, context, and text search
  • Tag-Based Organization: Flexible categorization system with AND/OR logic support

Task Flow

This section describes the typical flow of an AI agent interacting with the AgentRulesHub MCP server to retrieve and utilize rules for a given task.

  1. Task Initiation: An agent (e.g., Cline) begins a new task with an optional context (e.g., "TheProject" for a specific project).
  2. Retrieve Available Contexts (Optional): The agent can query the GetAllContexts tool to discover available contexts.
  3. Retrieve Rule Index: The agent queries the rules-hub MCP server using the GetAllRulesMetadata tool, optionally providing a context filter. This provides an index of all available rules, including their IDs, descriptions, languages, tags, and contexts.
  4. Identify Relevant Rules: Based on the current task's context (e.g., programming language, keywords, objectives) and the metadata received, the agent analyzes the rule index to identify which rules are relevant.
  5. Retrieve Rule Content: If relevant rules are identified, the agent uses the GetRuleContentById tool for each relevant rule ID to fetch its specific content.
  6. Utilize Rules: The agent incorporates the content of the retrieved rules to guide its actions, improve its output, or ensure adherence to specific guidelines for the task at hand.
sequenceDiagram
    participant Agent
    participant RulesHubServer as "rules-hub MCP Server"

    Agent->>RulesHubServer: 1. Request: GetAllContexts (Optional)
    RulesHubServer-->>Agent: 2. Response: Available Contexts
    Agent->>RulesHubServer: 3. Request: GetAllRulesMetadata(contextFilter?)
    RulesHubServer-->>Agent: 4. Response: Rules Index (Metadata)
    Agent->>Agent: 5. Analyze Task & Identify Relevant Rules
    alt Relevant Rules Found
        loop For Each Relevant Rule
            Agent->>RulesHubServer: 6. Request: GetRuleContentById (ruleId)
            RulesHubServer-->>Agent: 7. Response: Rule Content
        end
    end
    Agent->>Agent: 8. Utilize Rule Content for Task

Context-Based Rule Filtering

The context feature allows you to organize rules for specific projects or domains while maintaining a set of general rules that apply universally.

Context Behavior

  • No context filter: Returns only rules without context (general rules)
  • With context filter: Returns rules with no context OR rules matching the provided context

This ensures that general rules are always available, while context-specific rules are only returned when explicitly requested.

Example Use Cases

  1. General Development: No context filter - get all general coding standards
  2. Project-Specific Work: Context filter "TheProject" - get general rules plus TheProject-specific guidelines
  3. MCP Server Development: Context filter "mcp-server" - get general rules plus MCP-specific standards

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd ContextualAgentRulesHub
    
  2. Install dependencies:

    pip install -r requirements.txt
    

MCP Server Configuration

Installation for MCP Usage

  1. Install Python dependencies:

    pip install -r mcp-server/requirements.txt
    
  2. Configure your MCP client (e.g., Claude Desktop, Cline):

    Add the following to your MCP settings file:

    For Claude Desktop (claude_desktop_config.json):

    {
      "mcpServers": {
        "cotextual-agent-rules-hub": {
          "command": "python",
          "args": ["C:/path/to/ContextualAgentRulesHub/mcp-server/run_server.py"],
          "env": {
            "RulesLoaderOptions:0:SourceType": "YamlFile",
            "RulesLoaderOptions:0:Path": "C:/path/to/ContextualAgentRulesHub/rules"
          }
        }
      }
    }
    

    For Cline VSCode Extension (settings.json):

    {
      "cline.mcpServers": {
        "cotextual-agent-rules-hub": {
          "command": "python",
          "args": ["C:/path/to/ContextualAgentRulesHub/mcp-server/run_server.py"]
        }
      }
    }
    

Custom Instructions for MCP Client Configuration

As part of your MCP server configuration, you should add the following optimized custom instruction block that leverages the context feature:

When starting a new task:
1. First, use the cotextual-agent-rules-hub MCP server's GetAllContexts tool to discover available contexts
2. Unless the task explicitly states which context to use, ask the user to select from the available contexts or indicate that none should be used
3. Use GetAllRulesMetadata with the appropriate contextFilter if the user selected a specific context, or without a filter for general tasks
4. Review the rules metadata and identify ALL rules relevant to your task based on language, tags, and descriptions
5. Use GetRuleContentById to retrieve the content of ALL relevant rules
6. Apply these rules throughout your work on the task

This context-aware approach ensures you always have access to general best practices while also incorporating project-specific guidelines when explicitly requested.

Environment Configuration

The MCP server can be configured using environment variables:

VariableDescriptionDefault
RulesLoaderOptions:0:SourceTypeSource type for rules loadingYamlFile
RulesLoaderOptions:0:PathPath to rules directory./rules
AGENT_RULES_VALIDATIONEnable rule validationtrue
AGENT_RULES_LOG_LEVELLogging level (DEBUG, INFO, WARNING, ERROR)INFO

Multiple Sources Configuration

You can configure multiple rule sources by using indexed environment variables. Add additional sources using RulesLoaderOptions:1:, RulesLoaderOptions:2:, etc.

Example with multiple sources:

# First source - Local YAML files
RulesLoaderOptions:0:SourceType=YamlFile
RulesLoaderOptions:0:Path=C:/path/to/ContextualAgentRulesHub/rules

# Second source - Additional rule directory
RulesLoaderOptions:1:SourceType=YamlFile
RulesLoaderOptions:1:Path=C:/path/to/additional/rules

# Third source - Team shared rules
RulesLoaderOptions:2:SourceType=YamlFile
RulesLoaderOptions:2:Path=\\shared\network\path\team-rules

In MCP client configuration:

{
  "mcpServers": {
    "cotextual-agent-rules-hub": {
      "command": "python",
      "args": ["C:/path/to/ContextualAgentRulesHub/mcp-server/run_server.py"],
      "env": {
        "RulesLoaderOptions:0:SourceType": "YamlFile",
        "RulesLoaderOptions:0:Path": "C:/path/to/ContextualAgentRulesHub/rules",
        "RulesLoaderOptions:1:SourceType": "YamlFile",
        "RulesLoaderOptions:1:Path": "C:/path/to/additional/rules"
      }
    }
  }
}

Available MCP Tools

The server exposes three main tools:

GetAllContexts

  • Purpose: Retrieve all available contexts in the system
  • Parameters: None
  • Returns: JSON array of context strings
  • Usage: Query this first to discover available contexts for your work

Example Response:

[
  "TheProject",
  "mcp-server",
  "frontend-app"
]

GetAllRulesMetadata

  • Purpose: Retrieve metadata for all available rules
  • Parameters:
    • contextFilter (optional): Filter rules by context
  • Returns: JSON array of rule metadata objects
  • Usage: Query this to discover available rules, optionally filtered by context

Example Response:

[
  {
    "ruleId": "csharp-standards-rule",
    "description": "This rule checks for adherence to C# coding standards",
    "language": "csharp",
    "tags": ["coding-standards", "best-practices"],
    "context": null,
    "source": {
      "sourceType": "File"
    }
  },
  {
    "ruleId": "theproject-python-guidelines",
    "description": "Python guidelines specific to TheProject",
    "language": "python",
    "tags": ["python", "theproject"],
    "context": "TheProject",
    "source": {
      "sourceType": "File"
    }
  }
]

GetRuleContentById

  • Purpose: Get the full content of a specific rule
  • Parameters:
    • ruleId (string): The unique identifier of the rule
  • Returns: Rule content as markdown/text
  • Usage: Retrieve specific rule content after identifying relevant rules

Example Usage:

{
  "ruleId": "csharp-standards-rule"
}

Testing the MCP Server

Manual Testing

  1. Start the server directly:

    cd ContextualAgentRulesHub
    python mcp-server/run_server.py
    
  2. Test with included script:

    python test_mcp_server.py
    

Integration Testing

  1. Configure your MCP client with the server settings above

  2. Query available contexts:

    • Use the GetAllContexts tool to see all available contexts
  3. Query available rules:

    • Use the GetAllRulesMetadata tool to see all general rules
    • Use GetAllRulesMetadata with a context filter to see context-specific rules
    • Verify that rules are loaded from your rules/ directory
  4. Retrieve rule content:

    • Use GetRuleContentById with a rule ID from the metadata response
    • Verify that the full rule content is returned

Troubleshooting

  • Server won't start: Check Python path and dependencies
  • No rules loaded: Verify the RulesLoaderOptions:0:Path points to your rules directory
  • Permission errors: Ensure the Python process has read access to the rules directory
  • Connection issues: Check MCP client configuration and server logs
  • Context filtering not working: Ensure rules have the context field properly set in YAML files

Quick Start

Running the Demo

python simple_demo.py

This will demonstrate:

  • Loading rules from YAML files
  • Filtering by language, tags, and context
  • Content retrieval
  • Metadata indexing

Basic Usage (Direct API)

from src.bootstrap.agent_rules_bootstrapper import AgentRulesBootstrapper

# Bootstrap the rule system from environment configuration
bootstrapper = AgentRulesBootstrapper.from_environment()
repository = bootstrapper.bootstrap()

# Query rules
all_rules = repository.get_all_rules()
csharp_rules = repository.get_rules_by_language("csharp")
testing_rules = repository.get_rules_by_tag("testing")

# Query with context
theproject_rules = repository.get_rules_by_criteria(context="TheProject")  # Gets general + TheProject rules
general_rules = repository.get_rules_by_criteria()  # Gets only general rules

# Get available contexts
contexts = repository.get_available_contexts()

# Get rule content
content = repository.get_rule_content("csharp-standards-rule")
print(content)

The recommended way to use this system is through the MCP server, which provides tools that AI agents can use:

# Configure your MCP client to connect to the server
# Then use the tools through your AI agent:

# 1. Get available contexts
contexts = use_mcp_tool("GetAllContexts")

# 2. Get all available rules (with optional context filter)
metadata = use_mcp_tool("GetAllRulesMetadata", {"contextFilter": "TheProject"})

# 3. Get specific rule content  
content = use_mcp_tool("GetRuleContentById", {"ruleId": "csharp-standards-rule"})

Rule Format

Index File (rules/index.yaml) - Deprecated

Note: The index file is no longer required. Rules are now loaded directly from individual YAML files.

Rule Content File (rules/python-pep8-standards.yaml)

id: python-pep8-standards
description: "Python PEP8 coding standards and formatting guidelines"
language: python
context: null  # Optional: null for general rules, or specify a context like "TheProject"
tags:
  - coding-standards
  - pep8
  - formatting
  - best-practices
rule: |
  # Python PEP8 Standards Guide
  
  ## Indentation
  - Use 4 spaces per indentation level
  - Never mix tabs and spaces
  
  ## Line Length
  - Limit all lines to a maximum of 79 characters
  
  [... detailed rule content ...]

Context-Specific Rule Example

id: theproject-api-guidelines
description: "API development guidelines specific to TheProject"
language: python
context: TheProject  # This rule only appears when context filter is "TheProject"
tags:
  - api
  - theproject
  - rest
  - guidelines
rule: |
  # TheProject API Development Guidelines
  
  ## API Versioning
  - All APIs must use semantic versioning
  - Version must be included in URL path: /api/v1/
  
  [... TheProject-specific guidelines ...]

Core Components

Data Models

  • Rule: Contains metadata (ID, description, language, tags, context) and content
  • Source: Defines storage configuration for different source types
  • RuleIndex: Provides efficient indexing and querying capabilities

Source Types

  • FileSource: Reads rules from YAML files with index-based metadata
  • DatabaseSource: (Future) Database-backed rule storage
  • GitSource: (Future) Git repository-based rule storage
  • APISource: (Future) API-based rule retrieval

Repository Features

  • Multi-source aggregation: Combine rules from multiple sources
  • Lazy loading: Content loaded only when requested
  • Efficient querying: Index-based lookups for fast performance
  • Flexible filtering: Language, tags, context, and text-based search
  • Context awareness: Smart filtering based on project context

API Reference

RuleRepository

Query Methods

  • get_all_rules() - Get all rules
  • get_rules_by_language(language) - Filter by programming language
  • get_rules_by_tag(tag) - Filter by single tag
  • get_rules_by_tags_any(tags) - Filter by any of multiple tags (OR logic)
  • get_rules_by_tags_all(tags) - Filter by all tags (AND logic)
  • search_rules(query) - Text search in descriptions
  • get_rules_by_criteria(language, tags, tags_mode, description_query, context) - Complex multi-criteria queries with context support
  • get_available_contexts() - Get list of all available contexts

Content Methods

  • get_rule(rule_id) - Get rule metadata
  • get_rule_content(rule_id) - Get rule content with lazy loading

Management Methods

  • discover_rules() - Scan and index all rules from sources
  • add_source(source) - Add new rule source
  • refresh() - Reload all rules from sources
  • get_repository_stats() - Get statistics about the repository including context distribution

Extending the System

Adding New Source Types

  1. Implement the RuleSource interface:

    from src.sources.base import RuleSource
    
    class CustomSource(RuleSource):
        def load_rules_metadata(self) -> List[Rule]:
            # Implementation
            pass
        
        def load_rule_content(self, rule_id: str) -> str:
            # Implementation
            pass
        
        def validate_source(self) -> bool:
            # Implementation
            pass
    
  2. Register with the repository:

    custom_source = CustomSource(config)
    repository.add_source(custom_source)
    

Adding New Rule Types

Simply add new YAML files following the established format:

  1. Create content file rules/your-rule-id.yaml
  2. Include appropriate language, tags, and context for categorization
  3. Rules are automatically discovered on next server start

Example Rules Included

  1. python-pep8-standards: Python coding standards and formatting
  2. python-testing-guide: Python testing best practices with pytest
  3. git-workflow-guide: Git workflow and branching strategies
  4. code-review-standards: Code review guidelines and best practices
  5. mcp-server-specific-rule: MCP server development guidelines (context: mcp-server)

Requirements

  • Python 3.8+
  • PyYAML 6.0+
  • fastmcp (for MCP server)

Implementation Status

Completed Features:

  • MCP Server Implementation: Fully functional FastMCP server with three tools
  • Context-Based Filtering: Support for project-specific rule organization
  • Agent Rule System: Complete rule management with lazy loading
  • YAML File Support: Load rules from YAML files with metadata
  • Bootstrap System: Environment-based configuration and initialization
  • Rule Repository: In-memory storage with efficient querying
  • Content Sources: Pluggable architecture for different source types
  • Integration Layer: Bridge between MCP server and rule system
  • Testing Scripts: Automated testing and validation
  • Comprehensive Documentation: Setup, configuration, and usage guides

MCP Tools Available:

  • GetAllContexts: Discover available contexts
  • GetAllRulesMetadata: Retrieve rule index for discovery with optional context filtering
  • GetRuleContentById: Get specific rule content by ID

🔄 Future Enhancements:

  • Database source implementation
  • Git repository source implementation
  • API source implementation
  • Rule validation enhancements
  • Performance optimization for large rule sets
  • Advanced querying capabilities
  • Rule versioning system
  • Rule inheritance and composition

Contributing

  1. Follow Python PEP8 standards (see included rule for details)
  2. Add tests for new functionality
  3. Update documentation for API changes
  4. Use descriptive commit messages

License

[License information to be added]

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
WindsurfThe new purpose-built IDE to harness magic
CursorThe AI Code Editor
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
ChatWiseThe second fastest AI chatbot™
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Serper MCP ServerA Serper MCP Server
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
DeepChatYour AI Partner on Desktop
Tavily Mcp
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Playwright McpPlaywright MCP server
Amap Maps高德地图官方 MCP Server
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors