MagicTunnel

repository·master·Indexed 42 days ago

https://github.com/magicbeansai/magictunnel

A tool discovery and management system that enables LLMs to interact with internal and external systems via HTTP and Model Context Protocol (MCP) interfaces. It features 'Smart Discovery' for natural language tool execution, semantic search using vector embeddings, and automated tool generation from OpenAPI, GraphQL, and gRPC specifications. Version 0.2.49.

Tokens
100.1K
Snippets
290
Records
392
Agent score
52%

What's inside MagicTunnel

  1. Overview of MagicTunnel Capabilities and Features

    master

    MagicTunnel is an intelligent agent orchestration bridge that provides a unified interface for managing multiple agent types and external Model Context Protocol (MCP) servers.

    Key functional areas include:

    Agent Routing

    Supports multiple agent types including Subprocess, HTTP, LLM, and WebSocket agents. It features Handlebars-style templating for parameter substitution and includes built-in timeout management and retry logic.

    MCP Specification Compliance

    • Resource Management: Read-only resource system with URI validation.
    • Prompt Templates: Management of templates with argument substitution.
    • Logging: RFC 5424 syslog-compliant logging with 8 severity levels. Log levels can be controlled dynamically via the /mcp/logging/setLevel HTTP endpoint.
    • Notifications: Event-driven system with resource subscriptions.
    • Communication: Full JSON-RPC 2.0 message handling via WebSockets and gRPC streaming.

    MCP Proxy Integration

    Allows connecting to external MCP servers via a WebSocket-based client. It includes a registry system for managing multiple connections, intelligent tool name mapping to resolve conflicts, and tool aggregation to provide a single unified interface for both local and remote tools.

    Capability Generation

    • GraphQL: 100% specification compliance, including SDL and introspection JSON parsing.
    • OpenAPI: Supports OpenAPI 3.0 and Swagger 2.0 (JSON/YAML). It handles full $ref resolution, complex nested objects, and various authentication methods (API Key, Bearer, Basic, OAuth).
  2. What is MagicTunnel?

    master

    MagicTunnel is an intelligent orchestration bridge designed to connect Model Context Protocol (MCP) clients (such as Claude, GPT-4, or custom agents) to internal systems and external APIs.

    Instead of requiring a full MCP server implementation for every individual capability, MagicTunnel allows you to define capabilities via simple configurations and route them through various agents and endpoints. It acts as a unified gateway that enables rapid capability discovery and intelligent orchestration across diverse sources.

  3. Supported API Protocols in MagicTunnel

    master

    MagicTunnel supports four primary communication protocols depending on your client's requirements:

    1. WebSocket (Primary): Uses JSON-RPC 2.0 at ws://localhost:3000/mcp/ws. Best for real-time, bidirectional communication and tool streaming.
    2. HTTP REST API: Uses standard HTTP/JSON at http://localhost:3000. Best for simple integrations, testing, and curl workflows.
    3. Server-Sent Events (SSE): Uses /mcp/stream. Best for one-way streaming and monitoring progress of long-running operations.
    4. gRPC Streaming: Uses the HTTP port + 1000 (default 4000). Best for high-performance, high-throughput microservice integrations using Protocol Buffers.
  4. What is the Smart Tool Discovery System?

    master

    The Smart Tool Discovery System is an abstraction layer in MagicTunnel that reduces a large number of individual MCP tools (N tools) into a single intelligent proxy tool named smart_tool_discovery.

    This solves the 'context overflow' problem in AI clients by preventing the exposure of 50+ individual tool definitions. Instead, the user sends natural language requests to the proxy, which then:

    1. Analyzes the request.
    2. Finds the best matching tool using hybrid search strategies.
    3. Maps natural language parameters to the required tool schema.
    4. Proxies the call to the actual tool.
    5. Returns results along with discovery metadata (like confidence scores and reasoning).
  5. What is Smart Discovery and how to use it

    master

    Smart Discovery is a natural language interface for MagicTunnel that allows you to find and execute tools without knowing their specific names or parameter schemas. Instead of calling a specific tool, you provide a natural language request describing your goal, and the system discovers and executes the appropriate tool.

    Core Request Structure

    When calling the smart_tool_discovery tool, you provide an arguments object containing:

    • request: A string describing the task (e.g., "read the config.yaml file").
    • context (optional): Additional details to improve discovery accuracy.
    • preferred_tools (optional): A list of tool names to prioritize.
    • confidence_threshold (optional): A float to control how strictly the system matches tools.
    • include_error_details (optional): A boolean to enable verbose error reporting.
    {
      "name": "smart_tool_discovery",
      "arguments": {
        "request": "read the config.yaml file"
      }
    }
  6. How MagicTunnel works as an MCP bridge

    master
    MagicTunnel acts as an intelligent bridge between any MCP (Model Context Protocol) client and various agents or endpoints. Instead of connecting a client directly to many disparate tools, the client connects to MagicTunnel, which provides a single, smart tool discovery interface. MagicTunnel can find the correct tool for a request, map the necessary parameters, and proxy the call to the underlying agent or endpoint automatically.
  7. Use parameter substitution in tools

    master

    You can inject parameters from the input_schema into tool arguments, URLs, or bodies using the {parameter_name} syntax.

    Supported patterns:

    • Simple substitution: {host}
    • Default values: {count|4} (uses 4 if count is missing)
    • Array indexing: {hosts[0]}
    • Conditional substitution: {verbose?--debug:--quiet} (if verbose is true, use --debug, else --quiet)
    # Examples of substitution patterns
    args: ["--host", "{host}", "--port", "{port}"]
    args: ["--count", "{count|4}", "--timeout", "{timeout|30}"]
    args: ["{hosts[0]}", "{hosts[1]}"]
    args: 
      - "--verbose"
      - "{verbose?--debug:--quiet}"
  8. How MagicTunnel's architecture works

    master

    MagicTunnel sits between an MCP Client and your Agents & Endpoints.

    1. MCP Client: Any standard-compliant client (e.g., Claude Desktop).
    2. MagicTunnel: The central gateway that manages a Capability Registry and performs Agent Routing.
    3. Agents & Endpoints: The actual execution layer, which includes:
      • Custom Agents: Local subprocesses, HTTP services, gRPC, GraphQL, LLMs, etc.
      • External MCP Servers: Existing MCP servers managed and proxied by MagicTunnel.

    This architecture allows for seamless tool discovery and conflict resolution between local custom agents and remote MCP servers.

    ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
    │   MCP Client    │───▶│  MagicTunnel    │───▶│  Agents &       │
    │  (Any Client)   │    │  (This Project) │    │  Endpoints      │
    └─────────────────┘    └─────────────────┘    └─────────────────┘
                                  │                        │
                                  ▼                        ▼
                           ┌─────────────────┐    ┌─────────────────┐
                           │ Capability      │    │ External MCP    │
                           │ Registry        │    │ Servers         │
                           └─────────────────┘    └─────────────────┘
  9. Understand Smart Discovery search strategies

    master

    MagicTunnel uses four distinct strategies to find the right tool for a request:

    1. Rule-based Search (Fast): Uses exact tool name matching, fuzzy fallback, keyword matching in descriptions, and category-based classification (e.g., network, file, database).
    2. Semantic Search (Intelligent): Uses vector similarity (embeddings) to match conceptual requests.
      • Supported Models: OpenAI (text-embedding-3-small, text-embedding-3-large), Ollama (nomic-embed-text), and fallbacks like all-MiniLM-L6-v2.
    3. LLM-based Search (Advanced): Uses AI models (OpenAI, Anthropic, Ollama) to perform complex reasoning and disambiguation.
    4. Hybrid Search (Recommended): A three-layer approach combining all three methods for production environments. It uses a weighted scoring system:
      • Semantic Search: 30% weight
      • Rule-Based Matching: 15% weight
      • LLM Intelligence: 55% weight

    Processing Flow: User Request $\rightarrow$ Semantic Search $\rightarrow$ Rule-Based Search $\rightarrow$ LLM Evaluation $\rightarrow$ Combined Scoring $\rightarrow$ Tool Selection.

  10. Manage Environment Variables and Loading Order

    master

    MagicTunnel uses environment files for managing API keys and deployment settings. You can use .env for base settings, .env.{environment} (e.g., .env.production) for specific environments, and .env.local for local overrides.

    Loading Order (later overrides earlier):

    1. .env
    2. .env.{environment}
    3. .env.local (git-ignored)
    4. System environment variables
    5. CLI arguments

    Environment Detection: The system determines the environment using MAGICTUNNEL_ENV (highest precedence), then ENV, then NODE_ENV. It defaults to "development".

    Running with a specific environment:

    MAGICTUNNEL_ENV=production cargo run --release --bin magictunnel
  11. Use Advanced Parameter Substitution in Routing

    master

    When configuring agent routing, you can use advanced parameter substitution to dynamically inject values into commands, URLs, or JSON bodies:

    • Basic Substitution: {{parameter_name}}
    • Conditional Logic: {{case_sensitive ? '' : '-i'}}
    • Array Iteration: {{#each items}}--include={{this}}{{/each}}
    • Environment Variables: {{env.API_KEY}}
    • Default Values: {{timeout || 30}}
    • Complex JSON: Dynamic object construction with nested substitution.
  12. How MagicTunnel integrates with the MCP ecosystem

    master

    MagicTunnel acts as a strategic gateway within the Model Context Protocol (MCP) ecosystem by performing a dual role: it functions as both an MCP Server and an MCP Client (Proxy).

    Dual Role Architecture

    1. As an MCP Server (Primary Role): MagicTunnel aggregates capabilities from multiple sources (such as non-MCP agents like Bash or APIs) into a single, unified MCP server. An MCP Client (like Claude or GPT) connects to MagicTunnel to access this aggregated Capability Registry.
    2. As an MCP Client (Proxy Role): MagicTunnel can act as a proxy for other existing MCP servers. It connects to external MCP servers (e.g., GitHub, filesystem, or database servers) and exposes their tools to the end-user's MCP Client through its own interface.

    This creates a hierarchical MCP architecture where MagicTunnel sits between the primary AI client and a variety of specialized tool providers.