{"id":25997103,"url":"https://github.com/vrknetha/langchainjs-mcp-adapters","last_synced_at":"2025-03-05T16:56:19.562Z","repository":{"id":280505953,"uuid":"942240382","full_name":"vrknetha/langchainjs-mcp-adapters","owner":"vrknetha","description":null,"archived":false,"fork":false,"pushed_at":"2025-03-03T20:30:57.000Z","size":0,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-03T20:31:08.378Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/vrknetha.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}},"created_at":"2025-03-03T19:52:24.000Z","updated_at":"2025-03-03T20:31:01.000Z","dependencies_parsed_at":"2025-03-03T20:42:13.269Z","dependency_job_id":null,"html_url":"https://github.com/vrknetha/langchainjs-mcp-adapters","commit_stats":null,"previous_names":["vrknetha/langchainjs-mcp-adapters"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vrknetha%2Flangchainjs-mcp-adapters","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vrknetha%2Flangchainjs-mcp-adapters/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vrknetha%2Flangchainjs-mcp-adapters/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vrknetha%2Flangchainjs-mcp-adapters/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vrknetha","download_url":"https://codeload.github.com/vrknetha/langchainjs-mcp-adapters/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242067694,"owners_count":20066750,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2025-03-05T16:56:19.103Z","updated_at":"2025-03-05T16:56:19.540Z","avatar_url":"https://github.com/vrknetha.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LangChain.js MCP Adapters\n\nThis package provides adapters for using [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol/specification) tools with LangChain.js. It enables seamless integration between LangChain.js and MCP servers, allowing you to use MCP tools in your LangChain applications.\n\n[![npm version](https://img.shields.io/npm/v/langchainjs-mcp-adapters.svg)](https://www.npmjs.com/package/langchainjs-mcp-adapters)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Features\n\n- Connect to MCP servers using stdio or SSE transports\n- Connect to multiple MCP servers simultaneously\n- Configure connections using a JSON configuration file\n- **Support for custom headers in SSE connections** (great for authentication!)\n- Integrate MCP tools with LangChain.js agents\n- Comprehensive logging capabilities\n\n## Installation\n\n```bash\nnpm install langchainjs-mcp-adapters\n```\n\nFor Node.js environments with SSE connections requiring headers, you need to install the optional dependency:\n\n```bash\nnpm install eventsource\n```\n\n## Prerequisites\n\n- Node.js \u003e= 18\n- For stdio transport: Python MCP servers require Python 3.8+\n- For SSE transport: A running MCP server with SSE endpoint\n- For SSE with headers in Node.js: The `eventsource` package\n\n## Usage\n\n### Connecting to an MCP Server\n\nYou can connect to an MCP server using either stdio or SSE transport:\n\n```typescript\nimport { MultiServerMCPClient } from 'langchainjs-mcp-adapters';\n\n// Create a client\nconst client = new MultiServerMCPClient();\n\n// Connect to a server using stdio\nawait client.connectToServerViaStdio(\n  'math-server', // A name to identify this server\n  'python', // Command to run\n  ['./math_server.py'] // Arguments for the command\n);\n\n// Connect to a server using SSE\nawait client.connectToServerViaSSE(\n  'weather-server', // A name to identify this server\n  'http://localhost:8000/sse' // URL of the SSE server\n);\n\n// Connect to a server using SSE with custom headers\nawait client.connectToServerViaSSE(\n  'auth-server', // A name to identify this server\n  'http://localhost:8000/sse', // URL of the SSE server\n  {\n    Authorization: 'Bearer your-token-here',\n    'X-Custom-Header': 'custom-value',\n  },\n  true // Use Node.js EventSource (requires eventsource package)\n);\n\n// Get all tools from all connected servers\nconst tools = client.getTools();\n\n// Use the tools\nconst result = await tools[0].invoke({ param1: 'value1', param2: 'value2' });\n\n// Close the client when done\nawait client.close();\n```\n\n### Initializing Multiple Connections\n\nYou can also initialize multiple connections at once:\n\n```typescript\nimport { MultiServerMCPClient } from 'langchainjs-mcp-adapters';\n\nconst client = new MultiServerMCPClient({\n  'math-server': {\n    command: 'python',\n    args: ['./math_server.py'],\n  },\n  'weather-server': {\n    transport: 'sse',\n    url: 'http://localhost:8000/sse',\n  },\n  'auth-server': {\n    transport: 'sse',\n    url: 'http://localhost:8000/sse',\n    headers: {\n      Authorization: 'Bearer your-token-here',\n      'X-Custom-Header': 'custom-value',\n    },\n    useNodeEventSource: true, // Use Node.js EventSource for headers support\n  },\n});\n\n// Initialize all connections\nawait client.initializeConnections();\n\n// Get all tools\nconst tools = client.getTools();\n\n// Close all connections when done\nawait client.close();\n```\n\n### Using Configuration File\n\nYou can define your MCP server configurations in a JSON file (`mcp.json`) and load them:\n\n```typescript\nimport { MultiServerMCPClient } from 'langchainjs-mcp-adapters';\n\n// Create a client from the config file\nconst client = MultiServerMCPClient.fromConfigFile();\n// Or specify a custom path: MultiServerMCPClient.fromConfigFile(\"./config/mcp.json\");\n\n// Initialize all connections\nawait client.initializeConnections();\n\n// Get all tools\nconst tools = client.getTools();\n\n// Close all connections when done\nawait client.close();\n```\n\nExample `mcp.json` file:\n\n```json\n{\n  \"servers\": {\n    \"math\": {\n      \"command\": \"python\",\n      \"args\": [\"./examples/math_server.py\"]\n    },\n    \"weather\": {\n      \"transport\": \"sse\",\n      \"url\": \"http://localhost:8000/sse\"\n    },\n    \"auth-server\": {\n      \"transport\": \"sse\",\n      \"url\": \"http://localhost:8000/sse\",\n      \"headers\": {\n        \"Authorization\": \"Bearer your-token-here\",\n        \"X-Custom-Header\": \"custom-value\"\n      },\n      \"useNodeEventSource\": true\n    }\n  }\n}\n```\n\nThe client will attempt to connect to all servers defined in the configuration file. If a server is not available, it will log an error and continue with the available servers. If no servers are available, it will throw an error.\n\n```typescript\n// Error handling when initializing connections\ntry {\n  const client = MultiServerMCPClient.fromConfigFile();\n  await client.initializeConnections();\n  // Use the client...\n} catch (error) {\n  console.error('Failed to connect to any servers:', error.message);\n}\n```\n\n### Using with LangChain Agents\n\nYou can use MCP tools with LangChain agents:\n\n```typescript\nimport { MultiServerMCPClient } from 'langchainjs-mcp-adapters';\nimport { ChatOpenAI } from '@langchain/openai';\nimport { createOpenAIFunctionsAgent, AgentExecutor } from 'langchain/agents';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\n\n// Create a client and connect to servers\nconst client = new MultiServerMCPClient();\nawait client.connectToServerViaStdio('math-server', 'python', ['./math_server.py']);\n\n// Get tools\nconst tools = client.getTools();\n\n// Create an agent\nconst model = new ChatOpenAI({ temperature: 0 });\nconst prompt = ChatPromptTemplate.fromMessages([\n  ['system', 'You are a helpful assistant that can use tools to solve problems.'],\n  ['human', '{input}'],\n]);\n\nconst agent = createOpenAIFunctionsAgent({\n  llm: model,\n  tools,\n  prompt,\n});\n\nconst agentExecutor = new AgentExecutor({\n  agent,\n  tools,\n});\n\n// Run the agent\nconst result = await agentExecutor.invoke({\n  input: 'What is 5 + 3?',\n});\n\nconsole.log(result.output);\n\n// Close the client when done\nawait client.close();\n```\n\n### Using with Google's Gemini Models\n\nThe package also supports integration with Google's Gemini models:\n\n```typescript\nimport { MultiServerMCPClient } from 'langchainjs-mcp-adapters';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { createGoogleGenerativeAIFunctionsAgent, AgentExecutor } from 'langchain/agents';\nimport { ChatPromptTemplate } from '@langchain/core/prompts';\n\n// Create a client and connect to servers\nconst client = new MultiServerMCPClient();\nawait client.connectToServerViaStdio('math-server', 'python', ['./math_server.py']);\n\n// Get tools\nconst tools = client.getTools();\n\n// Create a Gemini agent\nconst model = new ChatGoogleGenerativeAI({\n  modelName: 'gemini-pro',\n  apiKey: process.env.GOOGLE_API_KEY,\n});\n\n// Create and run the agent\n// ... similar to the OpenAI example\n```\n\n## Example MCP Servers\n\n### Math Server (stdio transport)\n\nHere's an example of a simple MCP server in Python using stdio transport:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\n\n# Create a server\nmcp = FastMCP(name=\"Math\")\n\n@mcp.tool()\ndef add(a: int, b: int) -\u003e int:\n    \"\"\"Add two integers and return the result.\"\"\"\n    return a + b\n\n@mcp.tool()\ndef multiply(a: int, b: int) -\u003e int:\n    \"\"\"Multiply two integers and return the result.\"\"\"\n    return a * b\n\n# Run the server with stdio transport\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n```\n\n### Weather Server (SSE transport)\n\nHere's an example of an MCP server using SSE transport:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\n\n# Create a server\nmcp = FastMCP(name=\"Weather\")\n\n@mcp.tool()\ndef get_temperature(city: str) -\u003e str:\n    \"\"\"Get the current temperature for a city.\"\"\"\n    # Mock implementation\n    temperatures = {\n        \"new york\": \"72°F\",\n        \"london\": \"65°F\",\n        \"tokyo\": \"25 degrees Celsius\",\n    }\n\n    city_lower = city.lower()\n    if city_lower in temperatures:\n        return f\"The current temperature in {city} is {temperatures[city_lower]}.\"\n    else:\n        return \"Temperature data not available for this city\"\n\n# Run the server with SSE transport\nif __name__ == \"__main__\":\n    mcp.run(transport=\"sse\")\n```\n\n## Running the Examples\n\nThe package includes several example files that demonstrate how to use MCP adapters:\n\n1. `math_example.ts` - Basic example using a math server with stdio transport\n2. `sse_example.ts` - Example using a weather server with SSE transport\n3. `multi_transport_example.ts` - Example connecting to multiple servers with different transport types\n4. `json_config_example.ts` - Example using server configurations from an `mcp.json` file\n5. `gemini_example.ts` - Example using Google's Gemini models\n6. `logging_example.ts` - Example demonstrating logging capabilities\n7. `sse_with_headers_example.ts` - Example showing how to use custom headers with SSE connections\n\nTo run the examples:\n\n```bash\n# First build the project\nnpm run build\n\n# Start the weather server with SSE transport\npython examples/weather_server.py\n\n# In another terminal, run the examples using Node.js\nnode dist/examples/math_example.js\nnode dist/examples/sse_example.js\nnode dist/examples/json_config_example.js\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Connection Failures**: Ensure the MCP server is running and accessible\n2. **Tool Execution Errors**: Check the server logs for error messages\n3. **Transport Issues**: Verify the transport configuration (stdio or SSE)\n4. **Headers Not Applied**: When using headers with SSE, make sure you've installed the `eventsource` package and set `useNodeEventSource` to true\n\n### Debugging\n\nEnable debug logging to get more information:\n\n```typescript\nimport { logger } from 'langchainjs-mcp-adapters';\n\n// Set logger level to debug\nlogger.level = 'debug';\n```\n\n## Development\n\nFor information about contributing to this project, including GitHub Actions workflows, npm publishing, and more, please see [CONTRIBUTING.md](CONTRIBUTING.md).\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvrknetha%2Flangchainjs-mcp-adapters","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvrknetha%2Flangchainjs-mcp-adapters","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvrknetha%2Flangchainjs-mcp-adapters/lists"}