@h1deya/langchain-mcp-tools 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +71 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/langchain-mcp-tools.d.ts +20 -0
- package/dist/langchain-mcp-tools.js +133 -0
- package/dist/logger.d.ts +27 -0
- package/dist/logger.js +62 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 hideya
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# MCP Server To LangChain Tools Conversion Utility [](https://github.com/hideya/langchain-mcp-tools-ts/blob/main/LICENSE) [](https://www.npmjs.com/package/@h1deya/langchain-mcp-tools)
|
|
2
|
+
|
|
3
|
+
This package is intended to simplify the use of MCP server tools within LangChain.
|
|
4
|
+
|
|
5
|
+
It contains a utility function `convertMCPServersToLangChainTools()`
|
|
6
|
+
that initializes specified MCP servers,
|
|
7
|
+
and returns [LangChain Tools](https://js.langchain.com/docs/how_to/tool_calling/)
|
|
8
|
+
that wrap all the available MCP server tools.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm i @h1deya/langchain-mcp-tool
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quick Start
|
|
17
|
+
|
|
18
|
+
`convertMCPServersToLangChainTools()` utility function accepts MCP server configuration
|
|
19
|
+
in pretty much the same format as a JS Object interpretation of the JSON format used by
|
|
20
|
+
[Claude for Desktop](https://modelcontextprotocol.io/quickstart/user)
|
|
21
|
+
(it just needs the contents of the `mcpServers` property).
|
|
22
|
+
e.g.:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
const mcpServers: MCPServersConfig = {
|
|
26
|
+
filesystem: {
|
|
27
|
+
command: 'npx',
|
|
28
|
+
args: [
|
|
29
|
+
'-y',
|
|
30
|
+
'@modelcontextprotocol/server-filesystem',
|
|
31
|
+
'/Users/username/Desktop' // path to a directory to allow access to
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
fetch: {
|
|
35
|
+
command: 'uvx',
|
|
36
|
+
args: [
|
|
37
|
+
'mcp-server-fetch'
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const { tools, cleanup } = await convertMCPServersToLangChainTools(mcpServers);
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The utility function initializes all the MCP server connections concurrently,
|
|
46
|
+
and returns LangChain Tools (`tools: DynamicStructuredTool[]`)
|
|
47
|
+
by gathering all the available MCP server tools,
|
|
48
|
+
and by wrapping them into [LangChain Tools](https://js.langchain.com/docs/how_to/tool_calling/).
|
|
49
|
+
It also returns `cleanup` callback function
|
|
50
|
+
which is used to close all the connections to the MCP servers when finished.
|
|
51
|
+
|
|
52
|
+
The returned tools can be used with LangChain, e.g.:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const llm = new ChatAnthropic({ model: 'claude-3-5-haiku-latest' });
|
|
56
|
+
|
|
57
|
+
// import { createReactAgent } from '@langchain/langgraph/prebuilt';
|
|
58
|
+
const agent = createReactAgent({
|
|
59
|
+
llm,
|
|
60
|
+
tools
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
A simple and experimentable usage example can be found
|
|
64
|
+
[here](https://github.com/hideya/langchain-mcp-tools-ts-usage/blob/main/src/index.ts)
|
|
65
|
+
|
|
66
|
+
A more realistic usage example can be found
|
|
67
|
+
[here](https://github.com/hideya/langchain-mcp-client-ts)
|
|
68
|
+
|
|
69
|
+
## Limitations
|
|
70
|
+
|
|
71
|
+
Currently, only text results of tool calls are supported.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./langchain-mcp-tools.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./langchain-mcp-tools.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { DynamicStructuredTool } from '@langchain/core/tools';
|
|
2
|
+
interface MCPServerConfig {
|
|
3
|
+
command: string;
|
|
4
|
+
args: readonly string[];
|
|
5
|
+
env?: Readonly<Record<string, string>>;
|
|
6
|
+
}
|
|
7
|
+
export interface MCPServersConfig {
|
|
8
|
+
[key: string]: MCPServerConfig;
|
|
9
|
+
}
|
|
10
|
+
interface LogOptions {
|
|
11
|
+
logLevel?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
|
|
12
|
+
}
|
|
13
|
+
export interface MCPServerCleanupFunction {
|
|
14
|
+
(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export declare function convertMCPServersToLangChainTools(configs: MCPServersConfig, options?: LogOptions): Promise<{
|
|
17
|
+
tools: DynamicStructuredTool[];
|
|
18
|
+
cleanup: MCPServerCleanupFunction;
|
|
19
|
+
}>;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
2
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
3
|
+
import { CallToolResultSchema, ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
import { DynamicStructuredTool } from '@langchain/core/tools';
|
|
5
|
+
import { jsonSchemaToZod } from '@n8n/json-schema-to-zod';
|
|
6
|
+
import { Logger } from './logger.js';
|
|
7
|
+
// Custom error type for MCP server initialization failures
|
|
8
|
+
class MCPInitializationError extends Error {
|
|
9
|
+
serverName;
|
|
10
|
+
details;
|
|
11
|
+
constructor(serverName, message, details) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.serverName = serverName;
|
|
14
|
+
this.details = details;
|
|
15
|
+
this.name = 'MCPInitializationError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
// Primary function to convert multiple MCP servers to LangChain tools
|
|
19
|
+
export async function convertMCPServersToLangChainTools(configs, options) {
|
|
20
|
+
const allTools = [];
|
|
21
|
+
const cleanupCallbacks = [];
|
|
22
|
+
const logger = new Logger({ level: options?.logLevel || 'info' });
|
|
23
|
+
const serverInitPromises = Object.entries(configs).map(async ([name, config]) => {
|
|
24
|
+
const result = await convertMCPServerToLangChainTools(name, config, logger);
|
|
25
|
+
return { name, result };
|
|
26
|
+
});
|
|
27
|
+
// Track server names alongside their promises
|
|
28
|
+
const serverNames = Object.keys(configs);
|
|
29
|
+
// Concurrently initialize all the MCP servers
|
|
30
|
+
const results = await Promise.allSettled(serverInitPromises);
|
|
31
|
+
// Process successful initializations and log failures
|
|
32
|
+
results.forEach((result, index) => {
|
|
33
|
+
if (result.status === 'fulfilled') {
|
|
34
|
+
const { result: { tools, cleanup } } = result.value;
|
|
35
|
+
allTools.push(...tools);
|
|
36
|
+
cleanupCallbacks.push(cleanup);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
logger.error(`MCP server "${serverNames[index]}": failed to initialize: ${result.reason.details}`);
|
|
40
|
+
throw result.reason;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
async function cleanup() {
|
|
44
|
+
// Concurrently execute all the callbacks
|
|
45
|
+
const results = await Promise.allSettled(cleanupCallbacks.map(callback => callback()));
|
|
46
|
+
// Log any cleanup failures
|
|
47
|
+
const failures = results.filter(result => result.status === 'rejected');
|
|
48
|
+
failures.forEach((failure, index) => {
|
|
49
|
+
logger.error(`MCP server "${serverNames[index]}": failed to close: ${failure.reason}`);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
logger.info(`MCP servers initialized: ${allTools.length} tool(s) available in total`);
|
|
53
|
+
allTools.forEach((tool) => logger.debug(`- ${tool.name}`));
|
|
54
|
+
return { tools: allTools, cleanup };
|
|
55
|
+
}
|
|
56
|
+
// Convert a single MCP server into LangChain tools
|
|
57
|
+
async function convertMCPServerToLangChainTools(serverName, config, logger) {
|
|
58
|
+
let transport = null;
|
|
59
|
+
let client = null;
|
|
60
|
+
logger.info(`MCP server "${serverName}": initializing with: ${JSON.stringify(config)}`);
|
|
61
|
+
// NOTE: Some servers (e.g. Brave) seem to require PATH to be set.
|
|
62
|
+
// To avoid confusion, it was decided to automatically append it to the env
|
|
63
|
+
// if not explicitly set by the config.
|
|
64
|
+
const env = { ...config.env };
|
|
65
|
+
if (!env.PATH) {
|
|
66
|
+
env.PATH = process.env.PATH || '';
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
transport = new StdioClientTransport({
|
|
70
|
+
command: config.command,
|
|
71
|
+
args: config.args,
|
|
72
|
+
env: env,
|
|
73
|
+
});
|
|
74
|
+
client = new Client({
|
|
75
|
+
name: "mcp-client",
|
|
76
|
+
version: "0.0.1",
|
|
77
|
+
}, {
|
|
78
|
+
capabilities: {},
|
|
79
|
+
});
|
|
80
|
+
await client.connect(transport);
|
|
81
|
+
logger.info(`MCP server "${serverName}": connected`);
|
|
82
|
+
const toolsResponse = await client.request({ method: "tools/list" }, ListToolsResultSchema);
|
|
83
|
+
const tools = toolsResponse.tools.map((tool) => (new DynamicStructuredTool({
|
|
84
|
+
name: tool.name,
|
|
85
|
+
description: tool.description || '',
|
|
86
|
+
// FIXME
|
|
87
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
88
|
+
schema: jsonSchemaToZod(tool.inputSchema),
|
|
89
|
+
func: async (input) => {
|
|
90
|
+
logger.info(`MCP Tool "${tool.name}" received input:`, input);
|
|
91
|
+
// Execute tool call
|
|
92
|
+
const result = await client?.request({
|
|
93
|
+
method: "tools/call",
|
|
94
|
+
params: {
|
|
95
|
+
name: tool.name,
|
|
96
|
+
arguments: input,
|
|
97
|
+
},
|
|
98
|
+
}, CallToolResultSchema);
|
|
99
|
+
const roughLength = JSON.stringify(result).length;
|
|
100
|
+
logger.info(`MCP Tool "${tool.name}" received result (length: ${roughLength})`);
|
|
101
|
+
logger.debug('result:', result);
|
|
102
|
+
const filteredResult = result?.content
|
|
103
|
+
.filter(content => content.type === 'text')
|
|
104
|
+
.map(content => content.text)
|
|
105
|
+
.join('\n\n');
|
|
106
|
+
return filteredResult;
|
|
107
|
+
// return JSON.stringify(result.content);
|
|
108
|
+
},
|
|
109
|
+
})));
|
|
110
|
+
logger.info(`MCP server "${serverName}": ${tools.length} tool(s) available:`);
|
|
111
|
+
tools.forEach((tool) => logger.info(`- ${tool.name}`));
|
|
112
|
+
async function cleanup() {
|
|
113
|
+
if (transport) {
|
|
114
|
+
await transport.close();
|
|
115
|
+
logger.info(`MCP server "${serverName}": connection closed`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return { tools, cleanup };
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
// Proper cleanup in case of initialization error
|
|
122
|
+
if (transport) {
|
|
123
|
+
try {
|
|
124
|
+
await transport.close();
|
|
125
|
+
}
|
|
126
|
+
catch (cleanupError) {
|
|
127
|
+
// Log cleanup error but don't let it override the original error
|
|
128
|
+
logger.error(`Failed to cleanup during initialization error: ${cleanupError}`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
throw new MCPInitializationError(serverName, `Failed to initialize MCP server: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
132
|
+
}
|
|
133
|
+
}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
type LogLevelString = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
2
|
+
declare enum LogLevel {
|
|
3
|
+
TRACE = 0,
|
|
4
|
+
DEBUG = 1,
|
|
5
|
+
INFO = 2,
|
|
6
|
+
WARN = 3,
|
|
7
|
+
ERROR = 4,
|
|
8
|
+
FATAL = 5
|
|
9
|
+
}
|
|
10
|
+
declare class Logger {
|
|
11
|
+
private readonly level;
|
|
12
|
+
private static readonly RESET;
|
|
13
|
+
constructor({ level }?: {
|
|
14
|
+
level?: LogLevelString | LogLevel;
|
|
15
|
+
});
|
|
16
|
+
private parseLogLevel;
|
|
17
|
+
private log;
|
|
18
|
+
private formatValue;
|
|
19
|
+
private createLogMethod;
|
|
20
|
+
trace: (...args: unknown[]) => void;
|
|
21
|
+
debug: (...args: unknown[]) => void;
|
|
22
|
+
info: (...args: unknown[]) => void;
|
|
23
|
+
warn: (...args: unknown[]) => void;
|
|
24
|
+
error: (...args: unknown[]) => void;
|
|
25
|
+
fatal: (...args: unknown[]) => void;
|
|
26
|
+
}
|
|
27
|
+
export { Logger, LogLevel, LogLevelString };
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Simple logger
|
|
2
|
+
var LogLevel;
|
|
3
|
+
(function (LogLevel) {
|
|
4
|
+
LogLevel[LogLevel["TRACE"] = 0] = "TRACE";
|
|
5
|
+
LogLevel[LogLevel["DEBUG"] = 1] = "DEBUG";
|
|
6
|
+
LogLevel[LogLevel["INFO"] = 2] = "INFO";
|
|
7
|
+
LogLevel[LogLevel["WARN"] = 3] = "WARN";
|
|
8
|
+
LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
|
|
9
|
+
LogLevel[LogLevel["FATAL"] = 5] = "FATAL";
|
|
10
|
+
})(LogLevel || (LogLevel = {}));
|
|
11
|
+
const LOG_COLORS = {
|
|
12
|
+
[LogLevel.TRACE]: '\x1b[90m', // Gray
|
|
13
|
+
[LogLevel.DEBUG]: '\x1b[90m', // Gray
|
|
14
|
+
[LogLevel.INFO]: '\x1b[90m', // Gray
|
|
15
|
+
[LogLevel.WARN]: '\x1b[1;93m', // Bold bright yellow
|
|
16
|
+
[LogLevel.ERROR]: '\x1b[1;91m', // Bold bright red
|
|
17
|
+
[LogLevel.FATAL]: '\x1b[1;101m', // Red background, Bold text
|
|
18
|
+
};
|
|
19
|
+
const LOG_LEVEL_MAP = {
|
|
20
|
+
trace: LogLevel.TRACE,
|
|
21
|
+
debug: LogLevel.DEBUG,
|
|
22
|
+
info: LogLevel.INFO,
|
|
23
|
+
warn: LogLevel.WARN,
|
|
24
|
+
error: LogLevel.ERROR,
|
|
25
|
+
fatal: LogLevel.FATAL
|
|
26
|
+
};
|
|
27
|
+
class Logger {
|
|
28
|
+
level;
|
|
29
|
+
static RESET = '\x1b[0m';
|
|
30
|
+
constructor({ level = LogLevel.INFO } = {}) {
|
|
31
|
+
this.level = this.parseLogLevel(level);
|
|
32
|
+
}
|
|
33
|
+
parseLogLevel(level) {
|
|
34
|
+
if (typeof level === 'number')
|
|
35
|
+
return level;
|
|
36
|
+
return LOG_LEVEL_MAP[level.toLowerCase()];
|
|
37
|
+
}
|
|
38
|
+
log(level, ...args) {
|
|
39
|
+
if (level < this.level)
|
|
40
|
+
return;
|
|
41
|
+
const color = LOG_COLORS[level];
|
|
42
|
+
const levelStr = `[${LogLevel[level].toLowerCase()}]`;
|
|
43
|
+
console.log(`${color}${levelStr}${Logger.RESET}`, ...args.map(this.formatValue));
|
|
44
|
+
}
|
|
45
|
+
formatValue(value) {
|
|
46
|
+
if (value === null)
|
|
47
|
+
return 'null';
|
|
48
|
+
if (value === undefined)
|
|
49
|
+
return 'undefined';
|
|
50
|
+
return typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value);
|
|
51
|
+
}
|
|
52
|
+
createLogMethod(level) {
|
|
53
|
+
return (...args) => this.log(level, ...args);
|
|
54
|
+
}
|
|
55
|
+
trace = this.createLogMethod(LogLevel.TRACE);
|
|
56
|
+
debug = this.createLogMethod(LogLevel.DEBUG);
|
|
57
|
+
info = this.createLogMethod(LogLevel.INFO);
|
|
58
|
+
warn = this.createLogMethod(LogLevel.WARN);
|
|
59
|
+
error = this.createLogMethod(LogLevel.ERROR);
|
|
60
|
+
fatal = this.createLogMethod(LogLevel.FATAL);
|
|
61
|
+
}
|
|
62
|
+
export { Logger, LogLevel };
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@h1deya/langchain-mcp-tools",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A utility that wraps MCP servers into LangChain tools",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"modelcontextprotocol",
|
|
8
|
+
"mcp",
|
|
9
|
+
"mcp-client",
|
|
10
|
+
"langchain",
|
|
11
|
+
"tool-calling",
|
|
12
|
+
"typescript"
|
|
13
|
+
],
|
|
14
|
+
"author": "hideya kawahara",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/hideya/langchain-mcp-tools-ts.git"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsc",
|
|
31
|
+
"prepare": "npm run build",
|
|
32
|
+
"watch": "tsc --watch",
|
|
33
|
+
"lint": "eslint src",
|
|
34
|
+
"test": "vitest run",
|
|
35
|
+
"test:watch": "vitest",
|
|
36
|
+
"test:coverage": "vitest run --coverage",
|
|
37
|
+
"clean": "rm -rf dist coverage"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@langchain/core": "^0.3.27",
|
|
41
|
+
"@modelcontextprotocol/sdk": "^1.1.0",
|
|
42
|
+
"@n8n/json-schema-to-zod": "^1.1.0",
|
|
43
|
+
"zod": "^3.24.1"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@eslint/js": "^9.17.0",
|
|
47
|
+
"@types/node": "^22.10.5",
|
|
48
|
+
"@typescript-eslint/eslint-plugin": "^8.19.0",
|
|
49
|
+
"@typescript-eslint/parser": "^8.19.0",
|
|
50
|
+
"@vitest/coverage-v8": "^2.1.8",
|
|
51
|
+
"eslint": "^9.17.0",
|
|
52
|
+
"typescript": "^5.7.2",
|
|
53
|
+
"typescript-eslint": "^8.19.0",
|
|
54
|
+
"vitest": "^2.1.8"
|
|
55
|
+
}
|
|
56
|
+
}
|