{"id":26261849,"url":"https://github.com/langchain-ai/langchainjs-mcp-adapters","last_synced_at":"2026-01-19T21:53:56.037Z","repository":{"id":280505953,"uuid":"942240382","full_name":"langchain-ai/langchainjs-mcp-adapters","owner":"langchain-ai","description":"** THIS REPO HAS MOVED TO https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-mcp-adapters ** Adapters for integrating Model Context Protocol (MCP) tools with LangChain.js applications, supporting both stdio and SSE transports.","archived":true,"fork":false,"pushed_at":"2025-05-16T22:18:47.000Z","size":2350,"stargazers_count":243,"open_issues_count":0,"forks_count":34,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-31T15:05:33.062Z","etag":null,"topics":["agent-tools","ai-tools","javascript","langchain","langchainjs","llm-agents","llm-integration","llm-tools","mcp","model-context-protocol","openai-functions","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/langchain-ai.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-03-03T19:52:24.000Z","updated_at":"2025-10-17T18:23:21.000Z","dependencies_parsed_at":"2025-04-06T22:12:15.116Z","dependency_job_id":"ce91c1d2-a842-4a96-ab23-601d272918c3","html_url":"https://github.com/langchain-ai/langchainjs-mcp-adapters","commit_stats":null,"previous_names":["vrknetha/langchainjs-mcp-adapters","vbarda/langchainjs-mcp-adapters"],"tags_count":20,"template":false,"template_full_name":null,"purl":"pkg:github/langchain-ai/langchainjs-mcp-adapters","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-ai%2Flangchainjs-mcp-adapters","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-ai%2Flangchainjs-mcp-adapters/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-ai%2Flangchainjs-mcp-adapters/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-ai%2Flangchainjs-mcp-adapters/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/langchain-ai","download_url":"https://codeload.github.com/langchain-ai/langchainjs-mcp-adapters/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-ai%2Flangchainjs-mcp-adapters/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28586485,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T20:45:59.482Z","status":"ssl_error","status_checked_at":"2026-01-19T20:45:41.500Z","response_time":67,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent-tools","ai-tools","javascript","langchain","langchainjs","llm-agents","llm-integration","llm-tools","mcp","model-context-protocol","openai-functions","typescript"],"created_at":"2025-03-14T00:10:50.682Z","updated_at":"2026-01-19T21:53:56.019Z","avatar_url":"https://github.com/langchain-ai.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LangChain.js MCP Adapters\n\n[![npm version](https://img.shields.io/npm/v/@langchain/mcp-adapters.svg)](https://www.npmjs.com/package/@langchain/mcp-adapters)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nThis library provides a lightweight wrapper that makes [Anthropic Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) tools compatible with [LangChain.js](https://github.com/langchain-ai/langchainjs) and [LangGraph.js](https://github.com/langchain-ai/langgraphjs).\n\n## Features\n\n- 🔌 **Transport Options**\n\n  - Connect to MCP servers via stdio (local) or Streamable HTTP (remote)\n    - Streamable HTTP automatically falls back to SSE for compatibility with legacy MCP server implementations\n  - Support for custom headers in SSE connections for authentication\n  - Configurable reconnection strategies for both transport types\n\n- 🔄 **Multi-Server Management**\n\n  - Connect to multiple MCP servers simultaneously\n  - Auto-organize tools by server or access them as a flattened collection\n  - Convenient configuration via JSON file\n\n- 🧩 **Agent Integration**\n\n  - Compatible with LangChain.js and LangGraph.js\n  - Optimized for OpenAI, Anthropic, and Google models\n  - Supports rich content responses including text, images, and embedded resources\n\n- 🛠️ **Development Features**\n  - Uses `debug` package for debug logging\n  - Flexible configuration options\n  - Robust error handling\n\n## Installation\n\n```bash\nnpm install @langchain/mcp-adapters\n```\n\n### Optional Dependencies\n\nFor SSE connections with custom headers in Node.js (does not apply to Streamable HTTP):\n\n```bash\nnpm install eventsource\n```\n\nFor enhanced SSE header support (does not apply to Streamable HTTP):\n\n```bash\nnpm install extended-eventsource\n```\n\n# Example: Manage the MCP Client yourself\n\nThis example shows how you can manage your own MCP client and use it to get tools that you can pass to a LangGraph prebuilt ReAcT agent.\n\n```bash\nnpm install @langchain/mcp-adapters @langchain/langgraph @langchain/core @langchain/openai\n\nexport OPENAI_API_KEY=\u003cyour_api_key\u003e\n```\n\n## Client\n\n```ts\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { loadMcpTools } from \"@langchain/mcp-adapters\";\n\n// Initialize the ChatOpenAI model\nconst model = new ChatOpenAI({ modelName: \"gpt-4\" });\n\n// Automatically starts and connects to a MCP reference server\nconst transport = new StdioClientTransport({\n  command: \"npx\",\n  args: [\"-y\", \"@modelcontextprotocol/server-math\"],\n});\n\n// Initialize the client\nconst client = new Client({\n  name: \"math-client\",\n  version: \"1.0.0\",\n});\n\ntry {\n  // Connect to the transport\n  await client.connect(transport);\n\n  // Get tools with custom configuration\n  const tools = await loadMcpTools(\"math\", client, {\n    // Whether to throw errors if a tool fails to load (optional, default: true)\n    throwOnLoadError: true,\n    // Whether to prefix tool names with the server name (optional, default: false)\n    prefixToolNameWithServerName: false,\n    // Optional additional prefix for tool names (optional, default: \"\")\n    additionalToolNamePrefix: \"\",\n  });\n\n  // Create and run the agent\n  const agent = createReactAgent({ llm: model, tools });\n  const agentResponse = await agent.invoke({\n    messages: [{ role: \"user\", content: \"what's (3 + 5) x 12?\" }],\n  });\n  console.log(agentResponse);\n} catch (e) {\n  console.error(e);\n} finally {\n  // Clean up connection\n  await client.close();\n}\n```\n\n# Example: Connect to one or more servers via config\n\nThe library also allows you to connect to multiple MCP servers and load tools from them:\n\n## Client\n\n```ts\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { ChatOpenAI } from \"@langchain/openai\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n// Create client and connect to server\nconst client = new MultiServerMCPClient({\n  // Global tool configuration options\n  // Whether to throw on errors if a tool fails to load (optional, default: true)\n  throwOnLoadError: true,\n  // Whether to prefix tool names with the server name (optional, default: true)\n  prefixToolNameWithServerName: true,\n  // Optional additional prefix for tool names (optional, default: \"mcp\")\n  additionalToolNamePrefix: \"mcp\",\n\n  // Server configuration\n  mcpServers: {\n    // adds a STDIO connection to a server named \"math\"\n    math: {\n      transport: \"stdio\",\n      command: \"npx\",\n      args: [\"-y\", \"@modelcontextprotocol/server-math\"],\n      // Restart configuration for stdio transport\n      restart: {\n        enabled: true,\n        maxAttempts: 3,\n        delayMs: 1000,\n      },\n    },\n\n    // here's a filesystem server\n    filesystem: {\n      transport: \"stdio\",\n      command: \"npx\",\n      args: [\"-y\", \"@modelcontextprotocol/server-filesystem\"],\n    },\n\n    // Sreamable HTTP transport example, with auth headers and automatic SSE fallback disabled (defaults to enabled)\n    weather: {\n      url: \"https://example.com/weather/mcp\",\n      headers: {\n        Authorization: \"Bearer token123\",\n      }\n      automaticSSEFallback: false\n    },\n\n    // how to force SSE, for old servers that are known to only support SSE (streamable HTTP falls back automatically if unsure)\n    github: {\n      transport: \"sse\", // also works with \"type\" field instead of \"transport\"\n      url: \"https://example.com/mcp\",\n      reconnect: {\n        enabled: true,\n        maxAttempts: 5,\n        delayMs: 2000,\n      },\n    },\n  },\n});\n\nconst tools = await client.getTools();\n\n// Create an OpenAI model\nconst model = new ChatOpenAI({\n  modelName: \"gpt-4o\",\n  temperature: 0,\n});\n\n// Create the React agent\nconst agent = createReactAgent({\n  llm: model,\n  tools,\n});\n\n// Run the agent\ntry {\n  const mathResponse = await agent.invoke({\n    messages: [{ role: \"user\", content: \"what's (3 + 5) x 12?\" }],\n  });\n  console.log(mathResponse);\n} catch (error) {\n  console.error(\"Error during agent execution:\", error);\n  // Tools throw ToolException for tool-specific errors\n  if (error.name === \"ToolException\") {\n    console.error(\"Tool execution failed:\", error.message);\n  }\n}\n\nawait client.close();\n```\n\nFor more detailed examples, see the [examples](./examples) directory.\n\n## Tool Configuration Options\n\nWhen loading MCP tools either directly through `loadMcpTools` or via `MultiServerMCPClient`, you can configure the following options:\n\n| Option                         | Type    | Default | Description                                                                          |\n| ------------------------------ | ------- | ------- | ------------------------------------------------------------------------------------ |\n| `throwOnLoadError`             | boolean | `true`  | Whether to throw an error if a tool fails to load                                    |\n| `prefixToolNameWithServerName` | boolean | `true`  | If true, prefixes all tool names with the server name (e.g., `serverName__toolName`) |\n| `additionalToolNamePrefix`     | string  | `mcp`   | Additional prefix to add to tool names (e.g., `prefix__serverName__toolName`)        |\n\n## Response Handling\n\nMCP tools return results in the `content_and_artifact` format which can include:\n\n- **Text content**: Plain text responses\n- **Image content**: Base64-encoded images with MIME type\n- **Embedded resources**: Files, structured data, or other resources\n\nExample for handling different content types:\n\n```ts\nconst tool = tools.find((t) =\u003e t.name === \"mcp__math__calculate\");\nconst result = await tool.invoke({ expression: \"(3 + 5) * 12\" });\n\n// Result format: [content, artifacts]\n// - content: string | MessageContentComplex[]\n// - artifacts: EmbeddedResource[]\n\nconst [textContent, artifacts] = result;\n\n// Handle text content\nif (typeof textContent === \"string\") {\n  console.log(\"Result:\", textContent);\n} else {\n  // Handle complex content (text + images)\n  textContent.forEach((item) =\u003e {\n    if (item.type === \"text\") {\n      console.log(\"Text:\", item.text);\n    } else if (item.type === \"image_url\") {\n      console.log(\"Image URL:\", item.image_url.url);\n    }\n  });\n}\n\n// Handle artifacts if needed\nif (artifacts.length \u003e 0) {\n  console.log(\"Received artifacts:\", artifacts);\n}\n```\n\n## Reconnection Strategies\n\nBoth transport types support automatic reconnection:\n\n### Stdio Transport Restart\n\n```ts\n{\n  transport: \"stdio\",\n  command: \"npx\",\n  args: [\"-y\", \"@modelcontextprotocol/server-math\"],\n  restart: {\n    enabled: true,      // Enable automatic restart\n    maxAttempts: 3,     // Maximum restart attempts\n    delayMs: 1000       // Delay between attempts in ms\n  }\n}\n```\n\n### SSE Transport Reconnect\n\n```ts\n{\n  transport: \"sse\",\n  url: \"https://example.com/mcp-server\",\n  headers: { \"Authorization\": \"Bearer token123\" },\n  useNodeEventSource: true,\n  reconnect: {\n    enabled: true,      // Enable automatic reconnection\n    maxAttempts: 5,     // Maximum reconnection attempts\n    delayMs: 2000       // Delay between attempts in ms\n  }\n}\n```\n\n## Error Handling\n\nThe library provides different error types to help with debugging:\n\n- **MCPClientError**: For client connection and initialization issues\n- **ToolException**: For errors during tool execution\n- **ZodError**: For configuration validation errors (invalid connection settings, etc.)\n\nExample error handling:\n\n```ts\ntry {\n  const client = new MultiServerMCPClient({\n    math: {\n      transport: \"stdio\",\n      command: \"npx\",\n      args: [\"-y\", \"@modelcontextprotocol/server-math\"],\n    },\n  });\n\n  const tools = await client.getTools();\n  const result = await tools[0].invoke({ expression: \"1 + 2\" });\n} catch (error) {\n  if (error.name === \"MCPClientError\") {\n    // Handle connection issues\n    console.error(`Connection error (${error.serverName}):`, error.message);\n  } else if (error.name === \"ToolException\") {\n    // Handle tool execution errors\n    console.error(\"Tool execution failed:\", error.message);\n  } else if (error.name === \"ZodError\") {\n    // Handle configuration validation errors\n    console.error(\"Configuration error:\", error.issues);\n    // Zod errors contain detailed information about what went wrong\n    error.issues.forEach((issue) =\u003e {\n      console.error(`- Path: ${issue.path.join(\".\")}, Error: ${issue.message}`);\n    });\n  } else {\n    // Handle other errors\n    console.error(\"Unexpected error:\", error);\n  }\n}\n```\n\n### Common Zod Validation Errors\n\nThe library uses Zod for validating configuration. Here are some common validation errors:\n\n- **Missing required parameters**: For example, omitting `command` for stdio transport or `url` for SSE transport\n- **Invalid parameter types**: For example, providing a number where a string is expected\n- **Invalid connection configuration**: For example, using an invalid URL format for SSE transport\n\nExample Zod error for an invalid SSE URL:\n\n```json\n{\n  \"issues\": [\n    {\n      \"code\": \"invalid_string\",\n      \"validation\": \"url\",\n      \"path\": [\"mcpServers\", \"weather\", \"url\"],\n      \"message\": \"Invalid url\"\n    }\n  ],\n  \"name\": \"ZodError\"\n}\n```\n\n## Browser Environments\n\nWhen using in browsers:\n\n- EventSource API doesn't support custom headers for SSE\n- Consider using a proxy or pass authentication via query parameters to avoid leaking credentials to client\n- May require CORS configuration on the server side\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Connection Failures**:\n\n   - Verify the MCP server is running\n   - Check command paths and network connectivity\n\n2. **Tool Execution Errors**:\n\n   - Examine server logs for error messages\n   - Ensure input parameters match the expected schema\n\n3. **Headers Not Applied**:\n   - Install the recommended `extended-eventsource` package\n   - Set `useNodeEventSource: true` in SSE connections\n\n### Debug Logging\n\nThis package makes use of the [debug](https://www.npmjs.com/package/debug) package for debug logging.\n\nLogging is disabled by default, and can be enabled by setting the `DEBUG` environment variable as per\nthe instructions in the debug package.\n\nTo output all debug logs from this package:\n\n```bash\nDEBUG='@langchain/mcp-adapters:*'\n```\n\nTo output debug logs only from the `client` module:\n\n```bash\nDEBUG='@langchain/mcp-adapters:client'\n```\n\nTo output debug logs only from the `tools` module:\n\n```bash\nDEBUG='@langchain/mcp-adapters:tools'\n```\n\n## License\n\nMIT\n\n## Acknowledgements\n\nBig thanks to [@vrknetha](https://github.com/vrknetha), [@knacklabs](https://www.knacklabs.ai) for the initial implementation!\n\n## Contributing\n\nContributions are welcome! Please check out our [contributing guidelines](CONTRIBUTING.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flangchain-ai%2Flangchainjs-mcp-adapters","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flangchain-ai%2Flangchainjs-mcp-adapters","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flangchain-ai%2Flangchainjs-mcp-adapters/lists"}