Skip to main content

Model Context Protocol (MCP) To LangChain Tools Conversion Utility

Project description

MCP To LangChain Tools Conversion Utility License: MIT pypi version

A simple, lightweight library intended to simplify the use of Model Context Protocol (MCP) server tools with LangChain.

Its simplicity and extra features for stdio MCP servers can make it useful as a basis for your own customizations. However, it only supports text results of tool calls and does not support MCP features other than tools.

LangChain's official LangChain.js MCP Adapters library, which supports comprehensive integration with LangChain, has been released at:

You may want to consider using the above if you don't have specific needs for this library.

Introduction

This package is intended to simplify the use of Model Context Protocol (MCP) server tools with LangChain / Python.

Model Context Protocol (MCP) is the de facto industry standard that dramatically expands the scope of LLMs by enabling the integration of external tools and resources, including DBs, GitHub, Google Drive, Docker, Slack, Notion, Spotify, and more.

There are quite a few useful MCP servers already available:

This utility's goal is to make these massive numbers of MCP servers easily accessible from LangChain.

It contains a utility function convert_mcp_to_langchain_tools().
This async function handles parallel initialization of specified multiple MCP servers and converts their available tools into a list of LangChain-compatible tools.

For detailed information on how to use this library, please refer to the following document:

A typescript equivalent of this utility is available here

Prerequisites

  • Python 3.11+

Installation

pip install langchain-mcp-tools

API docs

Can be found here

Quick Start

A minimal but complete working usage example can be found in this example in the langchain-mcp-tools-py-usage repo

convert_mcp_to_langchain_tools() utility function accepts MCP server configurations that follow the same structure as Claude for Desktop, but only the contents of the mcpServers property, and is expressed as a dict, e.g.:

mcp_servers = {
    "filesystem": {
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
    },
    "fetch": {
        "command": "uvx",
        "args": ["mcp-server-fetch"]
    },
    "github": {
        "type": "http",
        "url": "https://api.githubcopilot.com/mcp/",
        "headers": {
            "Authorization": f"Bearer {os.environ.get('GITHUB_PERSONAL_ACCESS_TOKEN', '')}"
        }
    },
}

tools, cleanup = await convert_mcp_to_langchain_tools(
    mcp_servers
)

This utility function initializes all specified MCP servers in parallel, and returns LangChain Tools (tools: list[BaseTool]) by gathering available MCP tools from the servers, and by wrapping them into LangChain tools. It also returns an async callback function (cleanup: McpServerCleanupFn) to be invoked to close all MCP server sessions when finished.

The returned tools can be used with LangChain, e.g.:

# from langchain.chat_models import init_chat_model
llm = init_chat_model("anthropic:claude-sonnet-4-0")

# from langgraph.prebuilt import create_react_agent
agent = create_react_agent(
    llm,
    tools
)

For hands-on experimentation with MCP server integration, try this LangChain application built with the utility

For detailed information on how to use this library, please refer to the following document:
"Supercharging LangChain: Integrating 2000+ MCP with ReAct"

Building from Source

See README_DEV.md for details.

MCP Protocol Support

This library supports MCP Protocol version 2025-03-26 and maintains backwards compatibility with version 2024-11-05. It follows the official MCP specification for transport selection and backwards compatibility.

Features

stderr Redirection for Local MCP Server

A new key "errlog" has been introduced to specify a file-like object to which local (stdio) MCP server's stderr is redirected.

    log_path = f"mcp-server-{server_name}.log"
    log_file = open(log_path, "w")
    mcp_servers[server_name]["errlog"] = log_file

A usage example can be found here.
The key name errlog is derived from stdio_client()'s argument errlog.

Working Directory Configuration for Local MCP Servers

The working directory that is used when spawning a local (stdio) MCP server can be specified with the "cwd" key as follows:

    "local-server-name": {
        "command": "...",
        "args": [...],
        "cwd": "/working/directory"  # the working dir to be use by the server
    },

The key name cwd is derived from Python SDK's StdioServerParameters.

Note: The library automatically adds the PATH environment variable to stdio servers if not explicitly provided to ensure servers can find required executables.

Transport Selection Priority

The library selects transports using the following priority order:

  1. Explicit transport/type field (must match URL protocol if URL provided)
  2. URL protocol auto-detection (http/https → StreamableHTTP → SSE, ws/wss → WebSocket)
  3. Command presence → Stdio transport
  4. Error if none of the above match

This ensures predictable behavior while allowing flexibility for different deployment scenarios.

Remote MCP Server Support

mcp_servers configuration for Streamable HTTP, SSE (Server-Sent Events) and Websocket servers are as follows:

    # Auto-detection: tries Streamable HTTP first, falls back to SSE on 4xx errors
    "auto-detect-server": {
       "url": f"http://{server_host}:{server_port}/..."
    },

    # Explicit Streamable HTTP
    "streamable-http-server": {
        "url": f"http://{server_host}:{server_port}/...",
        "transport": "streamable_http"
        # "type": "http"  # VSCode-style config also works instead of the above
    },

    # Explicit SSE
    "sse-server-name": {
        "url": f"http://{sse_server_host}:{sse_server_port}/...",
        "transport": "sse"  # or `"type": "sse"`
    },

    # WebSocket
    "ws-server-name": {
        "url": f"ws://${ws_server_host}:${ws_server_port}/..."
        # optionally `"transport": "ws"` or `"type": "ws"`
    },

The "headers" key can be used to pass HTTP headers to Streamable HTTP and SSE connection.

    "github": {
        "type": "http",
        "url": "https://api.githubcopilot.com/mcp/",
        "headers": {
            "Authorization": f"Bearer {os.environ.get('GITHUB_PERSONAL_ACCESS_TOKEN', '')}"
        }
    },

NOTE: When accessing the GitHub MCP server, GitHub PAT (Personal Access Token) alone is not enough; your GitHub account must have an active Copilot subscription or be assigned a Copilot license through your organization.

Auto-detection behavior (default):

  • For HTTP/HTTPS URLs without explicit transport, the library follows MCP specification recommendations
  • First attempts Streamable HTTP transport
  • If Streamable HTTP fails with a 4xx error, automatically falls back to SSE transport
  • Non-4xx errors (network issues, etc.) are re-thrown without fallback

Explicit transport selection:

  • Set "transport": "streamable_http" (or VSCode-style config "type": "http") to force Streamable HTTP (no fallback)
  • Set "transport": "sse" to force SSE transport
  • WebSocket URLs (ws:// or wss://) always use WebSocket transport

Streamable HTTP is the modern MCP transport that replaces the older HTTP+SSE transport. According to the official MCP documentation: "SSE as a standalone transport is deprecated as of protocol version 2025-03-26. It has been replaced by Streamable HTTP, which incorporates SSE as an optional streaming mechanism."

Authentication Support for Streamable HTTP Connections

The library supports OAuth 2.1 authentication for Streamable HTTP connections:

from mcp.client.auth import OAuthClientProvider
...

    # Create OAuth authentication provider
    oauth_auth = OAuthClientProvider(
        server_url="https://...",
        client_metadata=...,
        storage=...,
        redirect_handler=...,
        callback_handler=...,
    )

    # Test configuration with OAuth auth
    mcp_servers = {
        "secure-streamable-server": {
            "url": "https://.../mcp/",
            "auth": oauth_auth,
            "timeout": 30.0
        },
    }

Test implementations are provided:

Authentication Support for SSE Connections (Legacy)

The library also supports authentication for SSE connections to MCP servers. Note that SSE transport is deprecated; Streamable HTTP is the recommended approach.

Limitations

  • Tool Return Types: Currently, only text results of tool calls are supported. The library uses LangChain's response_format: 'content' (the default), which only supports text strings. While MCP tools can return multiple content types (text, images, etc.), this library currently filters and uses only text content.
  • MCP Features: Only MCP Tools are supported. Other MCP features like Resources, Prompts, and Sampling are not implemented.

Change Log

Can be found here

Appendix

Troubleshooting Authentication Issues

When authentication errors occur, they often generate massive logs that make it difficult to identify that authentication is the root cause.

To address this problem, this library performs authentication pre-validation for HTTP/HTTPS MCP servers before attempting the actual MCP connection. This ensures that clear error messages like Authentication failed (401 Unauthorized) or Authentication failed (403 Forbidden) appear at the end of the logs, rather than being buried in the middle of extensive error output.

Important: This pre-validation is specific to this library and not part of the official MCP specification. In rare cases, it may interfere with certain MCP server behaviors.

When and How to Disable Pre-validation

Set "__pre_validate_authentication": False in your server config if:

  • Using OAuth flows that require complex authentication handshakes
  • The MCP server doesn't accept simple HTTP POST requests for validation
  • You're experiencing false negatives in the auth validation

Example:

"oauth-server": {
    "url": "https://api.example.com/mcp/",
    "auth": oauth_provider,  # Complex OAuth provider
    "__pre_validate_authentication": False  # Skip the pre-validation
}

Debugging Authentication

  1. Check your tokens/credentials - Most auth failures are due to expired or incorrect tokens
  2. Verify token permissions - Some MCP servers require specific scopes (e.g., GitHub Copilot license)
  3. Test with curl - Try a simple HTTP request to verify your auth setup:
    curl -H "Authorization: Bearer your-token" https://api.example.com/mcp/
    

Transport Selection Issues

The library automatically selects the appropriate transport based on your configuration:

  1. Explicit transport field takes priority
  2. URL protocol detection (http/https → Streamable HTTP → SSE fallback, ws/wss → WebSocket)
  3. Command presence → stdio transport

Common Issues

  • Both url and command specified: Choose one approach per server
  • Transport/URL mismatch: e.g., "transport": "websocket" with "url": "https://..."
  • Missing required fields: Must have either url or command

Auto-detection vs Explicit

For HTTP servers, the library tries Streamable HTTP first, then falls back to SSE on 4xx errors (per MCP specification). Use explicit "transport" if you want to skip auto-detection.

Debug Mode

For detailed debugging, enable debug logging:

import logging
logging.getLogger("langchain_mcp_tools").setLevel(logging.DEBUG)

# Also useful for transport debugging:
logging.getLogger("mcp").setLevel(logging.DEBUG)

This will show:

  • Transport selection decisions
  • Authentication validation attempts
  • Tool discovery and conversion steps
  • Connection establishment details

For Developers

For deeper technical details about implementation challenges and solutions, see TECHNICAL.md.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

langchain_mcp_tools-0.2.6.tar.gz (25.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

langchain_mcp_tools-0.2.6-py3-none-any.whl (19.9 kB view details)

Uploaded Python 3

File details

Details for the file langchain_mcp_tools-0.2.6.tar.gz.

File metadata

  • Download URL: langchain_mcp_tools-0.2.6.tar.gz
  • Upload date:
  • Size: 25.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for langchain_mcp_tools-0.2.6.tar.gz
Algorithm Hash digest
SHA256 e46e40587f07cce9a9a8e07f758428d19b87441e11c0d7177b27cdfa562d2f5e
MD5 691512d84592fb520ae474ba6b429d17
BLAKE2b-256 9abda8c56d9591ca2e4958b43c93fc97097873ae9222d2637e4e6e30aa27d9ab

See more details on using hashes here.

File details

Details for the file langchain_mcp_tools-0.2.6-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_mcp_tools-0.2.6-py3-none-any.whl
Algorithm Hash digest
SHA256 87911e5b98f9ab60361716564526be022bcc587f08d97b253e7b8281f9014689
MD5 86a450a4853feccddb5dfc6d1fb19b26
BLAKE2b-256 67e789a8546f6226a54706f5983e466f0edcbfa6656d853e7567069c50d543e2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page