Skip to content
Back to search

langchain-mcp-adapters

LangChain πŸ”Œ MCP

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/langchain-ai--langchain-mcp-adapters/badge.svg)](/listings/langchain-ai--langchain-mcp-adapters)

HTML

<a href="/listings/langchain-ai--langchain-mcp-adapters"><img src="/api/listings/langchain-ai--langchain-mcp-adapters/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

pip install langchain-mcp-adapters

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md Β· README Β· 359 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # LangChain MCP Adapters
  2. > [!IMPORTANT]
  3. > ## This repository is no longer actively maintained
  4. >
  5. > MCP support has moved into LangChain under the [`langchain.mcp`](https://github.com/langchain-ai/langchain/tree/master/libs/langchain_v1/langchain/mcp) namespace. Please migrate to `langchain[mcp]` for ongoing development, fixes, and support.
  6. >
  7. > - [Read the announcement](https://www.langchain.com/blog/mcp-in-langchain-stateless-protocol-elicitation-and-more)
  8. > - [Follow the migration guide](https://docs.langchain.com/oss/python/migrate/langchain-mcp-adapters)
  9. > - [View the new source code](https://github.com/langchain-ai/langchain/tree/master/libs/langchain_v1/langchain/mcp)
  10. This library provides a lightweight wrapper that makes [Anthropic Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) tools compatible with [LangChain](https://github.com/langchain-ai/langchain) and [LangGraph](https://github.com/langchain-ai/langgraph).
  11. ![MCP](static/img/mcp.png)
  12. > [!note]
  13. > A JavaScript/TypeScript version of this library is also available at [langchainjs](https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-mcp-adapters/).
  14. ## Features
  15. - πŸ› οΈ Convert MCP tools into [LangChain tools](https://python.langchain.com/docs/concepts/tools/) that can be used with [LangGraph](https://github.com/langchain-ai/langgraph) agents
  16. - πŸ“¦ A client implementation that allows you to connect to multiple MCP servers and load tools from them
  17. ## Installation
  18. ```bash
  19. pip install langchain-mcp-adapters
  20. ```
  21. ## Quickstart
  22. Here is a simple example of using the MCP tools with a LangGraph agent.
  23. ```bash
  24. pip install langchain-mcp-adapters langgraph "langchain[openai]"
  25. export OPENAI_API_KEY=<your_api_key>
  26. ```
  27. ### Server
  28. First, let's create an MCP server that can add and multiply numbers.
  29. ```python
  30. # math_server.py
  31. from mcp.server.fastmcp import FastMCP
  32. mcp = FastMCP("Math")
  33. @mcp.tool()
  34. def add(a: int, b: int) -> int:
  35. """Add two numbers"""
  36. return a + b
  37. @mcp.tool()
  38. def multiply(a: int, b: int) -> int:
  39. """Multiply two numbers"""
  40. return a * b
  41. if __name__ == "__main__":
  42. mcp.run(transport="stdio")
  43. ```
  44. ### Client
  45. ```python
  46. # Create server parameters for stdio connection
  47. from mcp import ClientSession, StdioServerParameters
  48. from mcp.client.stdio import stdio_client
  49. from langchain_mcp_adapters.tools import load_mcp_tools
  50. from langchain.agents import create_agent
  51. server_params = StdioServerParameters(
  52. command="python",
  53. # Make sure to update to the full absolute path to your math_server.py file
  54. args=["/path/to/math_server.py"],
  55. )
  56. async with stdio_client(server_params) as (read, write):
  57. async with ClientSession(read, write) as session:
  58. # Initialize the connection
  59. await session.initialize()
  60. # Get tools
  61. tools = await load_mcp_tools(session)
  62. # Create and run the agent
  63. agent = create_agent("openai:gpt-4.1", tools)
  64. agent_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
  65. ```
  66. ## Multiple MCP Servers
  67. The library also allows you to connect to multiple MCP servers and load tools from them:
  68. ### Server
  69. ```python
  70. # math_server.py
  71. ...
  72. # weather_server.py
  73. from typing import List
  74. from mcp.server.fastmcp import FastMCP
  75. mcp = FastMCP("Weather")
  76. @mcp.tool()
  77. async def get_weather(location: str) -> str:
  78. """Get weather for location."""
  79. return "It's always sunny in New York"
  80. if __name__ == "__main__":
  81. mcp.run(transport="http")
  82. ```
  83. ```bash
  84. python weather_server.py
  85. ```
  86. ### Client
  87. ```python
  88. from langchain_mcp_adapters.client import MultiServerMCPClient
  89. from langchain.agents import create_agent
  90. client = MultiServerMCPClient(
  91. {
  92. "math": {
  93. "command": "python",
  94. # Make sure to update to the full absolute path to your math_server.py file
  95. "args": ["/path/to/math_server.py"],
  96. "transport": "stdio",
  97. },
  98. "weather": {
  99. # Make sure you start your weather server on port 8000
  100. "url": "http://localhost:8000/mcp",
  101. "transport": "http",
  102. }
  103. }
  104. )
  105. tools = await client.get_tools()
  106. agent = create_agent("openai:gpt-4.1", tools)
  107. math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
  108. weather_response = await agent.ainvoke({"messages": "what is the weather in nyc?"})
  109. ```
  110. > [!note]
  111. > Example above will start a new MCP `ClientSession` for each tool invocation. If you would like to explicitly start a session for a given server, you can do:
  112. >
  113. > ```python
  114. > from langchain_mcp_adapters.tools import load_mcp_tools
  115. >
  116. > client = MultiServerMCPClient({...})
  117. > async with client.session("math") as session:
  118. > tools = await load_mcp_tools(session)
  119. > ```
  120. ## Streamable HTTP
  121. MCP now supports [streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) transport.
  122. To start an [example](examples/servers/streamable-http-stateless/) streamable HTTP server, run the following:
  123. ```bash
  124. cd examples/servers/streamable-http-stateless/
  125. uv run mcp-simple-streamablehttp-stateless --port 3000
  126. ```
  127. Alternatively, you can use FastMCP directly (as in the examples above).
  128. To use it with Python MCP SDK `streamablehttp_client`:
  129. ```python
  130. # Use server from examples/servers/streamable-http-stateless/
  131. from mcp import ClientSession
  132. from mcp.client.streamable_http import streamablehttp_client
  133. from langchain.agents import create_agent
  134. from langchain_mcp_adapters.tools import load_mcp_tools
  135. async with streamablehttp_client("http://localhost:3000/mcp") as (read, write, _):
  136. async with ClientSession(read, write) as session:
  137. # Initialize the connection
  138. await session.initialize()
  139. # Get tools
  140. tools = await load_mcp_tools(session)
  141. agent = create_agent("openai:gpt-4.1", tools)
  142. math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
  143. ```
  144. Use it with `MultiServerMCPClient`:
  145. ```python
  146. # Use server from examples/servers/streamable-http-stateless/
  147. from langchain_mcp_adapters.client import MultiServerMCPClient
  148. from langchain.agents import create_agent
  149. client = MultiServerMCPClient(
  150. {
  151. "math": {
  152. "transport": "http",
  153. "url": "http://localhost:3000/mcp"
  154. },
  155. }
  156. )
  157. tools = await client.get_tools()
  158. agent = create_agent("openai:gpt-4.1", tools)
  159. math_response = await agent.ainvoke({"messages": "what's (3 + 5) x 12?"})
  160. ```
  161. ## Passing runtime headers
  162. When connecting to MCP servers, you can include custom headers (e.g., for authentication or tracing) using the `headers` field in the connection configuration. This is supported for the following transports:
  163. - `sse`
  164. - `http` (or `streamable_http`)
  165. ### Example: passing headers with `MultiServerMCPClient`
  166. ```python
  167. from langchain_mcp_adapters.client import MultiServerMCPClient
  168. from langchain.agents import create_agent
  169. client = MultiServerMCPClient(
  170. {
  171. "weather": {
  172. "transport": "http",
  173. "url": "http://localhost:8000/mcp",
  174. "headers": {
  175. "Authorization": "Bearer YOUR_TOKEN",
  176. "X-Custom-Header": "custom-value"
  177. },
  178. }
  179. }
  180. )
  181. tools = await client.get_tools()
  182. agent = create_agent("openai:gpt-4.1", tools)
  183. response = await agent.ainvoke({"messages": "what is the weather in nyc?"})
  184. ```
  185. > Only `sse` and `http` transports support runtime headers. These headers are passed with every HTTP request to the MCP server.
  186. ## Tool error handling
  187. MCP distinguishes a tool *execution* error (`CallToolResult(isError=True)`, e.g. "project not found") from a protocol/transport failure. By default, an execution error is returned to the model as a `ToolMessage` with `status="error"`, so the agent can see what went wrong and self-correct instead of the run crashing:
  188. ```python
  189. client = MultiServerMCPClient({...})
  190. tools = await client.get_tools() # handle_tool_errors=True by default
  191. ```
  192. To restore the legacy behavior β€” raising a `ToolException` on execution errors β€” set `handle_tool_errors=False`:
  193. ```python
  194. client = MultiServerMCPClient({...}, handle_tool_errors=False)
  195. # or, at the tool-loading level:
  196. tools = await load_mcp_tools(session, handle_tool_errors=False)
  197. ```
  198. > The error's content blocks are preserved verbatim on the `ToolMessage`. The one exception: if the MCP error has no content at all, a minimal placeholder text block is substituted so the tool message isn't empty (a fragile shape for some model providers) β€” this placeholder is adapter-generated, not server-provided error detail.
  199. >
  200. > Transport/session failures and content-conversion errors (e.g. unsupported audio content) always raise regardless of this setting; only MCP execution errors (`isError=True`) are governed by it.
  201. ## Using with LangGraph StateGraph
  202. ```python
  203. from langchain_mcp_adapters.client import MultiServerMCPClient
  204. from langgraph.graph import StateGraph, MessagesState, START
  205. from langgraph.prebuilt import ToolNode, tools_condition
  206. from langchain.chat_models import init_chat_model
  207. model = init_chat_model("openai:gpt-4.1")
  208. client = MultiServerMCPClient(
  209. {
  210. "math": {
  211. "command": "python",
  212. # Make sure to update to the full absolute path to your math_server.py file
  213. "args": ["./examples/math_server.py"],
  214. "transport": "stdio",
  215. },
  216. "weather": {
  217. # make sure you start your weather server on port 8000
  218. "url": "http://localhost:8000/mcp",
  219. "transport": "http",
  220. }
  221. }
  222. )
  223. tools = await client.get_tools()
  224. def call_model(state: MessagesState):
  225. response = model.bind_tools(tools).invoke(state["messages"])
  226. return {"messages": response}
  227. builder = StateGraph(MessagesState)
  228. builder.add_node(call_model)
  229. builder.add_node(ToolNode(tools))
  230. builder.add_edge(START, "call_model")
  231. builder.add_conditional_edges(
  232. "call_model",
  233. tools_condition,
  234. )
  235. builder.add_edge("tools", "call_model")
  236. graph = builder.compile()
  237. math_response = await graph.ainvoke({"messages": "what's (3 + 5) x 12?"})
  238. weather_response = await graph.ainvoke({"messages": "what is the weather in nyc?"})
  239. ```
  240. ## Using with LangGraph API Server
  241. > [!TIP]
  242. > Check out [this guide](https://langchain-ai.github.io/langgraph/tutorials/langgraph-platform/local-server/) on getting started with LangGraph API server.
  243. If you want to run a LangGraph agent that uses MCP tools in a LangGraph API server, you can use the following setup:
  244. ```python
  245. # graph.py
  246. from contextlib import asynccontextmanager
  247. from langchain_mcp_adapters.client import MultiServerMCPClient
  248. from langchain.agents import create_agent
  249. async def make_graph():
  250. client = MultiServerMCPClient(
  251. {
  252. "weather": {
  253. # make sure you start your weather server on port 8000
  254. "url": "http://localhost:8000/mcp",
  255. "transport": "http",
  256. },
  257. # ATTENTION: MCP's stdio transport was designed primarily to support applications running on a user's machine.
  258. # Before using stdio in a web server context, evaluate whether there's a more appropriate solution.
  259. # For example, do you actually need MCP? or can you get away with a simple `@tool`?
  260. "math": {
  261. "command": "python",
  262. # Make sure to update to the full absolute path to your math_server.py file
  263. "args": ["/path/to/math_server.py"],
  264. "transport": "stdio",
  265. },
  266. }
  267. )
  268. tools = await client.get_tools()
  269. agent = create_agent("openai:gpt-4.1", tools)
  270. return agent
  271. ```
  272. In your [`langgraph.json`](https://langchain-ai.github.io/langgraph/cloud/reference/cli/#configuration-file) make sure to specify `make_graph` as your graph entrypoint:
  273. ```json
  274. {
  275. "dependencies": ["."],
  276. "graphs": {
  277. "agent": "./graph.py:make_graph"
  278. }
  279. }
  280. ```

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.