- ContextualAgentRulesHub
ContextualAgentRulesHub
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.
- Task Initiation: An agent (e.g., Cline) begins a new task with an optional context (e.g., "TheProject" for a specific project).
- Retrieve Available Contexts (Optional): The agent can query the
GetAllContextstool to discover available contexts. - Retrieve Rule Index: The agent queries the
rules-hubMCP server using theGetAllRulesMetadatatool, optionally providing a context filter. This provides an index of all available rules, including their IDs, descriptions, languages, tags, and contexts. - 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.
- Retrieve Rule Content: If relevant rules are identified, the agent uses the
GetRuleContentByIdtool for each relevant rule ID to fetch its specific content. - 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
- General Development: No context filter - get all general coding standards
- Project-Specific Work: Context filter "TheProject" - get general rules plus TheProject-specific guidelines
- MCP Server Development: Context filter "mcp-server" - get general rules plus MCP-specific standards
Installation
-
Clone the repository:
git clone <repository-url> cd ContextualAgentRulesHub -
Install dependencies:
pip install -r requirements.txt
MCP Server Configuration
Installation for MCP Usage
-
Install Python dependencies:
pip install -r mcp-server/requirements.txt -
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:
| Variable | Description | Default |
|---|---|---|
RulesLoaderOptions:0:SourceType | Source type for rules loading | YamlFile |
RulesLoaderOptions:0:Path | Path to rules directory | ./rules |
AGENT_RULES_VALIDATION | Enable rule validation | true |
AGENT_RULES_LOG_LEVEL | Logging 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
-
Start the server directly:
cd ContextualAgentRulesHub python mcp-server/run_server.py -
Test with included script:
python test_mcp_server.py
Integration Testing
-
Configure your MCP client with the server settings above
-
Query available contexts:
- Use the
GetAllContextstool to see all available contexts
- Use the
-
Query available rules:
- Use the
GetAllRulesMetadatatool to see all general rules - Use
GetAllRulesMetadatawith a context filter to see context-specific rules - Verify that rules are loaded from your
rules/directory
- Use the
-
Retrieve rule content:
- Use
GetRuleContentByIdwith a rule ID from the metadata response - Verify that the full rule content is returned
- Use
Troubleshooting
- Server won't start: Check Python path and dependencies
- No rules loaded: Verify the
RulesLoaderOptions:0:Pathpoints 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
contextfield 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)
MCP Usage (Recommended)
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 rulesget_rules_by_language(language)- Filter by programming languageget_rules_by_tag(tag)- Filter by single tagget_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 descriptionsget_rules_by_criteria(language, tags, tags_mode, description_query, context)- Complex multi-criteria queries with context supportget_available_contexts()- Get list of all available contexts
Content Methods
get_rule(rule_id)- Get rule metadataget_rule_content(rule_id)- Get rule content with lazy loading
Management Methods
discover_rules()- Scan and index all rules from sourcesadd_source(source)- Add new rule sourcerefresh()- Reload all rules from sourcesget_repository_stats()- Get statistics about the repository including context distribution
Extending the System
Adding New Source Types
-
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 -
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:
- Create content file
rules/your-rule-id.yaml - Include appropriate language, tags, and context for categorization
- Rules are automatically discovered on next server start
Example Rules Included
- python-pep8-standards: Python coding standards and formatting
- python-testing-guide: Python testing best practices with pytest
- git-workflow-guide: Git workflow and branching strategies
- code-review-standards: Code review guidelines and best practices
- 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 contextsGetAllRulesMetadata: Retrieve rule index for discovery with optional context filteringGetRuleContentById: 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
- Follow Python PEP8 standards (see included rule for details)
- Add tests for new functionality
- Update documentation for API changes
- Use descriptive commit messages
License
[License information to be added]