Skip to main content

mimory-mcp-focus-langchain

PyPI version Python 3.10+ License: MIT

LangChain integration for mimory-mcp-focus, providing focus capabilities to your LangChain MCP implementations.

Overview

mimory-mcp-focus-langchain extends LangChain's MCP (Model Context Protocol) integration with powerful focus capabilities. It allows you to:

  • Restrict tool access to specific MCP tools
  • Control parameter values with whitelists and ranges
  • Apply composite focus for complex tool-specific restrictions
  • Integrate seamlessly with LangChain's tool ecosystem

Installation

pip install mimory-mcp-focus-langchain

Dependencies

This package requires:

Quick Start

Basic Usage with FocusMultiServerMCPClient

import asyncio
from mim_mcp_focus_langchain import FocusMultiServerMCPClient
from langchain_mcp_adapters.sessions import Connection

async def main():
    # Define MCP server connections
    connections = {
        "everything": {
            "transport": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-everything"]
        },
        "time": {
            "transport": "stdio", 
            "command": "python",
            "args": ["-m", "mcp_server_time"]
        }
    }
    
    # Configure focus restrictions
    focus_configs = {
        "everything": {
            "focus_tools": ["echo", "add"],  # Only allow these tools
            "focus_params": {
                "message": ["hello", "world"],  # Restrict message values
                "a": ["range:1-10"]  # Restrict 'a' parameter to 1-10
            }
        },
        "time": {
            "focus_tools": ["get_current_time"],  # Only allow time tool
            "focus_params": {
                "timezone": ["America/New_York", "Europe/London"]  # Restrict timezones
            }
        }
    }
    
    # Create focus-enabled client
    client = FocusMultiServerMCPClient(connections, focus_configs)
    
    # Get tools with focus applied
    tools = await client.get_tools()
    
    # Use tools in your LangChain application
    for tool in tools:
        print(f"Tool: {tool.name} - {tool.description}")

if __name__ == "__main__":
    asyncio.run(main())

Using Core FocusClient with LangChain

import asyncio
from mimory_mcp_focus import focus_client_simple, focus_client_composite
from langchain_mcp_adapters.sessions import Connection, create_session
from langchain_mcp_adapters.tools import load_mcp_tools

async def main():
    # Create MCP connection
    connection = {
        "transport": "stdio",
        "command": "npx", 
        "args": ["-y", "@modelcontextprotocol/server-everything"]
    }
    
    # Create focus-enabled session
    async with create_session(connection) as session:
        await session.initialize()
        
        # Apply focus restrictions using simple focus
        focus_session = focus_client_simple(
            session,
            focus_tools=["echo", "add"],
            focus_params={
                "message": ["hello", "world"],
                "a": ["range:1-10"]
            },
            strict=False
        )
        
        # Load tools with focus applied
        tools = await load_mcp_tools(focus_session)
        
        # Use tools in LangChain
        for tool in tools:
            print(f"Tool: {tool.name}")

if __name__ == "__main__":
    asyncio.run(main())

Focus Configuration

Simple Focus

Restrict tools and parameters globally:

focus_config = {
    "focus_tools": ["tool1", "tool2"],  # Allowed tools
    "focus_params": {
        "param1": ["value1", "value2"],  # Allowed values
        "param2": ["range:1-100"]  # Numeric range
    },
    "focus_type": "simple",  # How the focus params are encoded
    "strict": False  # Whether to enforce strict mode
}

Composite Focus

Apply different restrictions per tool:

focus_config = {
    "focus": {
        "tool1": {
            "param1": ["value1", "value2"],
            "param2": ["range:1-10"]
        },
        "tool2": {
            "param3": ["value3", "value4"],
            "param4": ["value5"]
        }
    },
    "focus_type": "composite",  # How the focus params are encoded
    "strict": True
}

Focus Configuration Structure

The focus_config dictionary supports the following structure:

For Simple Focus (focus_type: "simple"):

  • focus_tools: List of allowed tool names (use ["*"] to allow all tools)
  • focus_params: Dictionary mapping parameter names to allowed values
  • focus_type: Must be "simple"
  • strict: Boolean indicating whether to enforce strict mode

For Composite Focus (focus_type: "composite"):

  • focus: Dictionary mapping tool names to their parameter restrictions
  • focus_type: Must be "composite"
  • strict: Boolean indicating whether to enforce strict mode

Parameter Value Formats:

  • Exact values: ["value1", "value2"]
  • Numeric ranges: ["range:1-100"] (inclusive)
  • Wildcard: ["*"] (allows any value)

API Reference

FocusMultiServerMCPClient

Main class for focus-enabled multi-server MCP operations.

Constructor

FocusMultiServerMCPClient(
    connections: Optional[Dict[str, Connection]] = None,
    focus_configs: Optional[Dict[str, Dict[str, Any]]] = None
)

Parameters:

  • connections: Dictionary mapping server names to connection configurations
  • focus_configs: Dictionary mapping server names to focus configurations

Methods

async get_tools(server_name: Optional[str] = None) -> List[BaseTool]

Get LangChain tools with focus restrictions applied.

Parameters:

  • server_name: Optional name of specific server. If None, returns tools from all servers.

Returns:

  • List of LangChain tools with focus applied
async session(server_name: str, *, auto_initialize: bool = True) -> AsyncIterator[ClientSession]

Create a focus-enabled MCP session.

Parameters:

  • server_name: Name of the server to connect to
  • auto_initialize: Whether to automatically initialize the session

Returns:

  • Async context manager yielding a focus-enabled ClientSession

Examples

Example 1: Basic Tool Restriction

# examples/basic_restriction.py
import asyncio
from mim_mcp_focus_langchain import FocusMultiServerMCPClient

async def main():
    connections = {
        "everything": {
            "transport": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-everything"]
        }
    }
    
    focus_configs = {
        "everything": {
            "focus_tools": ["echo"],  # Only allow echo tool
            "focus_params": {
                "message": ["hello", "world", "test"]  # Restrict message values
            },
            "focus_type": "simple",
            "strict": False
        }
    }
    
    client = FocusMultiServerMCPClient(connections, focus_configs)
    tools = await client.get_tools()
    
    print("Available tools:")
    for tool in tools:
        print(f"- {tool.name}: {tool.description}")

if __name__ == "__main__":
    asyncio.run(main())

Example 2: Multi-Server with Composite Focus

# examples/multi_server_composite.py
import asyncio
from mim_mcp_focus_langchain import FocusMultiServerMCPClient

async def main():
    connections = {
        "everything": {
            "transport": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-everything"]
        },
        "time": {
            "transport": "stdio",
            "command": "python", 
            "args": ["-m", "mcp_server_time"]
        }
    }
    
    focus_configs = {
        "everything": {
            "focus": {
                "echo": {
                    "message": ["hello", "world"]
                },
                "add": {
                    "a": ["range:1-5"],
                    "b": ["range:1-5"]
                }
            },
            "focus_type": "composite",
            "strict": False
        },
        "time": {
            "focus_tools": ["get_current_time"],
            "focus_params": {
                "timezone": ["America/New_York", "Europe/London"]
            },
            "focus_type": "simple",
            "strict": False
        }
    }
    
    client = FocusMultiServerMCPClient(connections, focus_configs)
    tools = await client.get_tools()
    
    print("Available tools:")
    for tool in tools:
        print(f"- {tool.name}: {tool.description}")

if __name__ == "__main__":
    asyncio.run(main())

Example 3: Using with LangChain Agents

# examples/langchain_agent.py
import asyncio
from mim_mcp_focus_langchain import FocusMultiServerMCPClient
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_openai import ChatOpenAI

async def main():
    # Setup MCP connections with focus
    connections = {
        "everything": {
            "transport": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-everything"]
        }
    }
    
    focus_configs = {
        "everything": {
            "focus_tools": ["echo", "add"],
            "focus_params": {
                "message": ["hello", "world", "test"],
                "a": ["range:1-10"],
                "b": ["range:1-10"]
            },
            "focus_type": "simple",
            "strict": False
        }
    }
    
    # Create focus-enabled client
    client = FocusMultiServerMCPClient(connections, focus_configs)
    
    # Get tools
    tools = await client.get_tools()
    
    # Create LangChain agent
    llm = ChatOpenAI(model="gpt-4", temperature=0)
    agent = create_tool_calling_agent(llm, tools, "You are a helpful assistant with access to focused MCP tools.")
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    
    # Run agent
    result = await agent_executor.ainvoke({"input": "Echo 'hello' and add 5 + 3"})
    print(result)

if __name__ == "__main__":
    asyncio.run(main())

Error Handling

The library uses standard Python exceptions for error handling. Focus-related errors will be raised as appropriate exceptions that you can catch and handle as needed.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Travis McQueen - oss@mimory.io

Support

For support, please open an issue on GitHub.

Metadata

Release files for mimory-mcp-focus-langchain 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mimory-mcp-focus-langchain 0.1.0
File Size Uploaded Provenance
mimory_mcp_focus_langchain-0.1.0.tar.gz 12.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for mimory-mcp-focus-langchain 0.1.0
File Interpreter ABI Platform
mimory_mcp_focus_langchain-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 22.3 kB

Release files / mimory_mcp_focus_langchain-0.1.0.tar.gz

Download URL mimory_mcp_focus_langchain-0.1.0.tar.gz
Size 12.4 kB
Tags Source
SHA-256 checksum
How to use checksums
a066afc7d9e4a0a30827aa56a45cd61226b0e7384c19cfad25628408762fae1c
BLAKE2b-256 checksum
How to use checksums
5b3f4ff66c3b2d60d3ccfbe0063ae32b370f64e5ecc00845bd0e73e82e0483d4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Release files / mimory_mcp_focus_langchain-0.1.0-py3-none-any.whl

Download URL mimory_mcp_focus_langchain-0.1.0-py3-none-any.whl
Size 9.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
78ff58165bb746115d1c39e95ba31d1521a7d0da8ad1e60ad83b0eb25b307b7a
BLAKE2b-256 checksum
How to use checksums
e82cbf415478bc5249c88d4c8bc8dbf738aa1b3cd981299ee620dcad2f575501
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Security for mimory-mcp-focus-langchain 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page