Skip to main content
Model Context Protocol (MCP)은 애플리케이션이 LLM에 도구와 컨텍스트를 제공하는 방식을 표준화하는 개방형 프로토콜입니다. LangChain 에이전트는 langchain-mcp-adapters 라이브러리를 사용하여 MCP 서버에 정의된 도구를 사용할 수 있습니다.

설치

LangGraph에서 MCP 도구를 사용하려면 @langchain/mcp-adapters 라이브러리를 설치하세요:
npm install @langchain/mcp-adapters

전송 유형

MCP는 클라이언트-서버 통신을 위한 다양한 전송 메커니즘을 지원합니다:
  • stdio: 클라이언트가 서버를 서브프로세스로 실행하고 표준 입력/출력을 통해 통신합니다. 로컬 도구와 간단한 설정에 가장 적합합니다.
  • Streamable HTTP: 서버가 독립적인 프로세스로 실행되어 HTTP 요청을 처리합니다. 원격 연결과 여러 클라이언트를 지원합니다.
  • Server-Sent Events (SSE): 실시간 스트리밍 통신에 최적화된 streamable HTTP의 변형입니다.

MCP 도구 사용

@langchain/mcp-adapters는 에이전트가 하나 이상의 MCP 서버에 정의된 도구를 사용할 수 있도록 합니다.
여러 MCP 서버 접근
import { MultiServerMCPClient } from "@langchain/mcp-adapters";  
import { ChatAnthropic } from "@langchain/anthropic";
import { createAgent } from "langchain";

const client = new MultiServerMCPClient({  
    math: {
        transport: "stdio",  // Local subprocess communication
        command: "node",
        // Replace with absolute path to your math_server.js file
        args: ["/path/to/math_server.js"],
    },
    weather: {
        transport: "sse",  // Server-Sent Events for streaming
        // Ensure you start your weather server on port 8000
        url: "http://localhost:8000/mcp",
    },
});

const tools = await client.getTools();  
const agent = createAgent({
    model: "anthropic:claude-sonnet-4-5",
    tools,  
});

const mathResponse = await agent.invoke({
    messages: [{ role: "user", content: "what's (3 + 5) x 12?" }],
});

const weatherResponse = await agent.invoke({
    messages: [{ role: "user", content: "what is the weather in nyc?" }],
});
MultiServerMCPClient is stateless by default. Each tool invocation creates a fresh MCP ClientSession, executes the tool, and then cleans up.

Custom MCP servers

To create your own MCP servers, you can use the @modelcontextprotocol/sdk library. This library provides a simple way to define tools and run them as servers.
npm install @modelcontextprotocol/sdk
Use the following reference implementations to test your agent with MCP tool servers.
Math server (stdio transport)
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
    CallToolRequestSchema,
    ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

const server = new Server(
    {
        name: "math-server",
        version: "0.1.0",
    },
    {
        capabilities: {
        tools: {},
        },
    }
);

server.setRequestHandler(ListToolsRequestSchema, async () => {
    return {
        tools: [
        {
            name: "add",
            description: "Add two numbers",
            inputSchema: {
            type: "object",
            properties: {
                a: {
                type: "number",
                description: "First number",
                },
                b: {
                type: "number",
                description: "Second number",
                },
            },
            required: ["a", "b"],
            },
        },
        {
            name: "multiply",
            description: "Multiply two numbers",
            inputSchema: {
            type: "object",
            properties: {
                a: {
                type: "number",
                description: "First number",
                },
                b: {
                type: "number",
                description: "Second number",
                },
            },
            required: ["a", "b"],
            },
        },
        ],
    };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
    switch (request.params.name) {
        case "add": {
        const { a, b } = request.params.arguments as { a: number; b: number };
        return {
            content: [
            {
                type: "text",
                text: String(a + b),
            },
            ],
        };
        }
        case "multiply": {
        const { a, b } = request.params.arguments as { a: number; b: number };
        return {
            content: [
            {
                type: "text",
                text: String(a * b),
            },
            ],
        };
        }
        default:
        throw new Error(`Unknown tool: ${request.params.name}`);
    }
});

async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("Math MCP server running on stdio");
}

main();
Weather server (SSE transport)
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import {
    CallToolRequestSchema,
    ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import express from "express";

const app = express();
app.use(express.json());

const server = new Server(
    {
        name: "weather-server",
        version: "0.1.0",
    },
    {
        capabilities: {
        tools: {},
        },
    }
);

server.setRequestHandler(ListToolsRequestSchema, async () => {
    return {
        tools: [
        {
            name: "get_weather",
            description: "Get weather for location",
            inputSchema: {
            type: "object",
            properties: {
                location: {
                type: "string",
                description: "Location to get weather for",
                },
            },
            required: ["location"],
            },
        },
        ],
    };
});

server.setRequestHandler(CallToolRequestSchema, async (request) => {
    switch (request.params.name) {
        case "get_weather": {
        const { location } = request.params.arguments as { location: string };
        return {
            content: [
            {
                type: "text",
                text: `It's always sunny in ${location}`,
            },
            ],
        };
        }
        default:
        throw new Error(`Unknown tool: ${request.params.name}`);
    }
});

app.post("/mcp", async (req, res) => {
    const transport = new SSEServerTransport("/mcp", res);
    await server.connect(transport);
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
    console.log(`Weather MCP server running on port ${PORT}`);
});

Stateful tool usage

For stateful servers that maintain context between tool calls, use client.session() to create a persistent ClientSession.
Using MCP ClientSession for stateful tool usage
import { loadMCPTools } from "@langchain/mcp-adapters/tools.js";

const client = new MultiServerMCPClient({...});
const session = await client.session("math");
const tools = await loadMCPTools(session);

Additional resources


Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I