Skip to content

Conversation

@xizhibei
Copy link
Contributor

@xizhibei xizhibei commented Dec 21, 2025

Summary

This feature introduces context-aware proxy mode, allowing MCP server configurations to use dynamic templates with project-specific context variables. This enables intelligent server configurations that adapt to different development environments, teams, and projects.

Key Changes

🎯 Core Features

  • Template Engine Integration: Handlebars-based template processing for MCP server configurations
  • Context Collection: Automatic gathering of project, user, environment, and git context
  • Dynamic Configuration: Server configurations can now use variables like {project.name}, {user.username}, {environment}, etc.
  • Conditional Server Enablement: Servers can be enabled/disabled based on environment or context conditions
  • Template Caching: Performance optimization with context-aware template caching

📁 New Files Added

  • src/types/context.ts - Context data type definitions
  • src/context/ - Context collection and management services
  • src/template/ - Template processing engine with Handlebars integration
  • mcp.json.example - Comprehensive examples showcasing template usage

🔧 Configuration Updates

  • Project Context: projectId, environment, team, custom variables
  • Template Settings: Validation, failure mode, caching configuration
  • Environment Integration: Automatic environment variable collection with prefix filtering
  • Git Information: Branch, commit, repository details for context awareness

🏗️ Architecture Enhancements

  • Proxy Transport: Enhanced to pass project configuration for context enrichment
  • Config Manager: Extended with template processing capabilities
  • Session Management: Added context data to session types for persistence

Template Examples

{
  "mcpTemplates": {
    "project-serena": {
      "command": "npx",
      "args": ["-y", "serena", "{project.path}"],
      "env": {
        "PROJECT_ID": "{project.custom.projectId}",
        "SESSION_ID": "{context.sessionId}",
        "GIT_BRANCH": "{project.git.branch?:main}"
      },
      "tags": ["filesystem", "search"]
    },
    "conditional-server": {
      "command": "node",
      "args": ["{project.path}/server.js"],
      "env": {
        "NODE_ENV": "{project.environment}",
        "DEBUG": "{?project.environment=development:true}"
      },
      "disabled": "{?project.environment=production}"
    }
  }
}

Available Template Variables

  • Project: {project.path}, {project.name}, {project.environment}, {project.custom.*}
  • User: {user.username}, {user.email}, {user.home}
  • Git: {project.git.branch}, {project.git.commit}, {project.git.repository}
  • Environment: {environment.variables.*}, {context.timestamp}
  • Functions: |upper, |lower, |truncate(10), |replace(from,to), |default(value)

Testing

  • ✅ Comprehensive unit tests for template processing and context collection
  • ✅ Integration tests for proxy transport with context enrichment
  • ✅ Error handling validation with graceful failure modes
  • ✅ Performance tests for template caching and context processing
  • ✅ End-to-end tests for complete template workflow

Breaking Changes

  • None - this is a purely additive feature that maintains backward compatibility

Migration Guide

  1. Add "context" section to your .1mcprc configuration file
  2. Define project-specific variables like projectId, environment, team
  3. Create mcpTemplates section in your MCP configuration
  4. Use template variables in server commands, arguments, and environment variables
  5. Restart 1MCP proxy to enable context-aware processing

Benefits

  • Environment-Aware: Servers automatically adapt to development/staging/production environments
  • Team Configurations: Different teams can have customized server setups
  • Dynamic Configuration: No more hardcoded paths or environment-specific configs
  • Centralized Context: Single source of truth for project metadata
  • Template Reusability: Share template configurations across projects and teams

- Updated the .1mcprc.example configuration to include a new context-aware proxy mode, allowing for project-specific context collection.
- Introduced a ContextCollector class to gather environment and project-specific context, including custom variables and Git information.
- Enhanced the proxy command to utilize the collected context, improving logging and configuration handling.
- Added a ConfigFieldProcessor for template processing, enabling dynamic variable substitution in configurations.
- Implemented various template functions and validation mechanisms to ensure safe and effective template usage.
- Added comprehensive tests for the new context handling and template processing features, ensuring reliability and correctness.
- Refactored contextCollector tests to improve mock handling and ensure proper context data collection.
- Added new tests for ConfigFieldProcessor and TemplateProcessor, covering various template processing scenarios and validation.
- Introduced TemplateUtils tests to validate variable parsing, function chaining, and error handling.
- Implemented context utility tests for session ID generation and timestamp formatting, ensuring reliability and correctness across utilities.
…anagement

- Added mcp.json.example to provide a template for configuration with context-aware settings.
- Enhanced the ConfigManager to support loading configurations with template processing, utilizing context data for dynamic variable substitution.
- Implemented GlobalContextManager to manage and provide context data across the application.
- Updated ServerManager to handle context-aware transport creation and template reprocessing on context changes.
- Introduced TemplateDetector for validating template syntax in configurations, ensuring proper usage and error handling.
- Added comprehensive tests for context management, template processing, and configuration loading to ensure reliability and correctness.
- Updated server setup to create only static transports at startup, with template servers instantiated per-client.
- Enhanced logging to clarify transport creation details, including static transport counts and context handling.
- Refactored context extraction to improve integration with HTTP requests, ensuring context data is correctly passed for template processing.
- Introduced new utility functions for context extraction from headers and query parameters, improving flexibility in context management.
- Added comprehensive tests for context handling and template processing to ensure reliability and correctness across the application.
- Introduced command validation to prevent injection attacks by allowing only a predefined set of commands.
- Implemented argument validation to detect dangerous patterns, enhancing overall security during command execution.
- Updated path sanitization to resolve paths to their canonical form and prevent path traversal vulnerabilities.
- Added checks to ensure paths are within allowed directories, improving safety in file operations.
- Enhanced tests to cover new security features and ensure robustness against potential vulnerabilities.
…leanup functionality

- Introduced a new method to retrieve template settings with default values, improving configuration handling for server instances.
- Updated instance key creation logic to utilize the new template settings for better clarity and maintainability.
- Implemented a periodic cleanup timer for idle template instances, enhancing resource management and preventing memory leaks.
- Refactored idle instance cleanup logic to consider template-specific idle timeouts, ensuring efficient resource utilization.
- Enhanced logging for cleanup operations to improve visibility into server management processes.
…agement

- Introduced ClientInstancePool to manage pooled client instances, improving resource utilization and management.
- Updated ServerManager to utilize ClientInstancePool for creating and managing client instances from templates.
- Refactored template processing to support context-aware client instance creation, enhancing flexibility and efficiency.
- Added comprehensive tests for ClientInstancePool and its integration with ServerManager, ensuring reliability and correctness.
- Removed deprecated TemplateServerFactory, streamlining the architecture and improving maintainability.
…nitialization improvements

- Added extensive mocking for internal tools and adapters to isolate tests and avoid loading heavy dependencies.
- Refactored test setup to use `beforeAll` for initialization and `afterAll` for cleanup, improving test efficiency.
- Updated individual tool execution tests to ensure proper mocking and validation of parameters, enhancing reliability.
- Improved error handling in tests to provide clearer feedback on expected failures when handlers are not mocked.
- Added ConnectionManager to handle transport connection lifecycle and manage inbound connections.
- Implemented MCPServerLifecycleManager for managing the lifecycle of MCP server instances, including start, stop, and restart functionalities.
- Refactored ServerManager to utilize the new ConnectionManager and MCPServerLifecycleManager, improving modularity and separation of concerns.
- Introduced TemplateConfigurationManager for managing template configurations with a circuit breaker pattern to handle errors gracefully.
- Enhanced TemplateServerManager to manage template-based server instances and client pools, including idle instance cleanup.
- Added comprehensive tests for the new components to ensure reliability and correctness across server management functionalities.
- Introduced support for HTTP and SSE transport templates in the TemplateProcessor, allowing dynamic variable substitution based on transport context.
- Enhanced TemplateValidator to include transport-specific validation rules, ensuring required and forbidden variables are correctly enforced for each transport type.
- Updated TemplateParser to inject transport information into the context, improving template processing capabilities.
- Added comprehensive tests for transport-specific template processing and validation, ensuring reliability and correctness across various scenarios.
- Refactored existing template processing logic to accommodate new transport features, enhancing overall modularity and maintainability.
…nfiguration management

- Replaced the existing template processing system with Handlebars for improved rendering capabilities and simplicity.
- Updated ConfigManager to utilize HandlebarsTemplateRenderer, allowing for dynamic variable substitution in configurations.
- Refactored template-related tests to align with the new Handlebars implementation, ensuring comprehensive coverage and reliability.
- Enhanced error handling in template processing to gracefully manage missing variables, improving robustness.
- Removed deprecated template processing components, streamlining the codebase and enhancing maintainability.
…text management

- Deleted ContextCollector implementation and its associated test file to simplify context handling.
- Updated context-related utilities and tests to remove references to the removed ContextCollector.
- Enhanced overall codebase maintainability by eliminating unused components.
…xt tests

- Changed template variable syntax from single braces to double braces for consistency across session context integration tests.
- Ensured that environment variables and command arguments utilize the updated syntax for proper variable substitution.
- Modified mock context paths and project names in HandlebarsTemplateRenderer tests to reflect a test environment.
- Ensured that rendered template arguments and environment variables are consistent with the updated mock context, improving test accuracy.
- Introduced new integration tests for cross-domain functionality, covering discovery, installation, and management flows.
- Validated end-to-end processes from server discovery to installation and management, ensuring robust handling of multi-step operations.
- Enhanced test coverage for discovery handlers, installation handlers, and management handlers, improving overall reliability and accuracy.
- Implemented detailed mock setups for adapters to facilitate thorough testing without external dependencies.
@xizhibei xizhibei changed the title Feat/proxy agent context feat: Add context-aware proxy mode with template support for MCP server configurations Dec 21, 2025
…ion management

- Added comprehensive tests for client information extraction from initialize requests in StdioProxyTransport.
- Implemented context metadata handling using the _meta field in JSON-RPC messages, improving transport communication.
- Updated context extraction utilities to support the new _meta field structure, ensuring robust context management.
- Refactored related tests to validate client information handling and context extraction, enhancing overall test coverage and reliability.
- Added sessionId and transport properties to StreamableSessionData and InboundConnectionConfig interfaces for improved session tracking.
- Updated context extraction in streamableHttpRoutes to utilize the new _meta field, ensuring consistent handling of session information.
- Refactored session persistence logic to include full context in session configuration, enhancing restoration capabilities.
…t restoration tests

- Introduced a new 'tags' option in the proxy command for improved server selection based on user-defined tags.
- Expanded session context restoration tests to validate handling of full, partial, and missing context scenarios, ensuring robust session management.
- Added end-to-end tests for session restoration, focusing on context validation and error handling, enhancing overall test coverage.
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