|
| 1 | +/** |
| 2 | + * Calculator MCP Server with LangGraph Example |
| 3 | + * |
| 4 | + * This example demonstrates how to use the Calculator MCP server with LangGraph |
| 5 | + * to create a structured workflow for simple calculations. |
| 6 | + * |
| 7 | + * The graph-based approach allows: |
| 8 | + * 1. Clear separation of responsibilities (reasoning vs execution) |
| 9 | + * 2. Conditional routing based on tool calls |
| 10 | + * 3. Structured handling of complex multi-tool operations |
| 11 | + */ |
| 12 | + |
| 13 | +/* eslint-disable no-console */ |
| 14 | +import { ChatOpenAI } from "@langchain/openai"; |
| 15 | +import { |
| 16 | + StateGraph, |
| 17 | + END, |
| 18 | + START, |
| 19 | + MessagesAnnotation, |
| 20 | +} from "@langchain/langgraph"; |
| 21 | +import { ToolNode } from "@langchain/langgraph/prebuilt"; |
| 22 | +import { |
| 23 | + HumanMessage, |
| 24 | + AIMessage, |
| 25 | + SystemMessage, |
| 26 | + isHumanMessage, |
| 27 | +} from "@langchain/core/messages"; |
| 28 | +import dotenv from "dotenv"; |
| 29 | +import fs from "fs"; |
| 30 | +import path from "path"; |
| 31 | + |
| 32 | +import { main as calculatorServerMain } from "./calculator_server_shttp_sse.js"; |
| 33 | + |
| 34 | +// MCP client imports |
| 35 | +import { MultiServerMCPClient } from "../src/index.js"; |
| 36 | + |
| 37 | +// Load environment variables from .env file |
| 38 | +dotenv.config(); |
| 39 | + |
| 40 | +const transportType = |
| 41 | + process.env.MCP_TRANSPORT_TYPE === "sse" ? "sse" : "streamable"; |
| 42 | + |
| 43 | +export async function runExample(client?: MultiServerMCPClient) { |
| 44 | + try { |
| 45 | + console.log("Initializing MCP client..."); |
| 46 | + |
| 47 | + void calculatorServerMain(); |
| 48 | + |
| 49 | + // Wait for the server to start |
| 50 | + await new Promise((resolve) => { |
| 51 | + setTimeout(resolve, 100); |
| 52 | + }); |
| 53 | + |
| 54 | + // Create a client with configurations for the calculator server |
| 55 | + // eslint-disable-next-line no-param-reassign |
| 56 | + client = |
| 57 | + client ?? |
| 58 | + new MultiServerMCPClient({ |
| 59 | + calculator: { |
| 60 | + url: `http://localhost:3000/${ |
| 61 | + transportType === "sse" ? "sse" : "mcp" |
| 62 | + }`, |
| 63 | + }, |
| 64 | + }); |
| 65 | + |
| 66 | + console.log("Connected to server"); |
| 67 | + |
| 68 | + // Get all tools (flattened array is the default now) |
| 69 | + const mcpTools = await client.getTools(); |
| 70 | + |
| 71 | + if (mcpTools.length === 0) { |
| 72 | + throw new Error("No tools found"); |
| 73 | + } |
| 74 | + |
| 75 | + console.log( |
| 76 | + `Loaded ${mcpTools.length} MCP tools: ${mcpTools |
| 77 | + .map((tool) => tool.name) |
| 78 | + .join(", ")}` |
| 79 | + ); |
| 80 | + |
| 81 | + // Create an OpenAI model with tools attached |
| 82 | + const systemMessage = `You are an assistant that helps users with calculations. |
| 83 | +You have access to tools that can add, subtract, multiply, and divide numbers. Use |
| 84 | +these tools to answer the user's questions.`; |
| 85 | + |
| 86 | + const model = new ChatOpenAI({ |
| 87 | + modelName: process.env.OPENAI_MODEL_NAME || "gpt-4o-mini", |
| 88 | + temperature: 0.7, |
| 89 | + }).bindTools(mcpTools); |
| 90 | + |
| 91 | + // Create a tool node for the LangGraph |
| 92 | + const toolNode = new ToolNode(mcpTools); |
| 93 | + |
| 94 | + // ================================================ |
| 95 | + // Create a LangGraph agent flow |
| 96 | + // ================================================ |
| 97 | + console.log("\n=== CREATING LANGGRAPH AGENT FLOW ==="); |
| 98 | + |
| 99 | + // Define the function that calls the model |
| 100 | + const llmNode = async (state: typeof MessagesAnnotation.State) => { |
| 101 | + console.log(`Calling LLM with ${state.messages.length} messages`); |
| 102 | + |
| 103 | + // Add system message if it's the first call |
| 104 | + let { messages } = state; |
| 105 | + if (messages.length === 1 && isHumanMessage(messages[0])) { |
| 106 | + messages = [new SystemMessage(systemMessage), ...messages]; |
| 107 | + } |
| 108 | + |
| 109 | + const response = await model.invoke(messages); |
| 110 | + return { messages: [response] }; |
| 111 | + }; |
| 112 | + |
| 113 | + // Create a new graph with MessagesAnnotation |
| 114 | + const workflow = new StateGraph(MessagesAnnotation) |
| 115 | + |
| 116 | + // Add the nodes to the graph |
| 117 | + .addNode("llm", llmNode) |
| 118 | + .addNode("tools", toolNode) |
| 119 | + |
| 120 | + // Add edges - these define how nodes are connected |
| 121 | + .addEdge(START, "llm") |
| 122 | + .addEdge("tools", "llm") |
| 123 | + |
| 124 | + // Conditional routing to end or continue the tool loop |
| 125 | + .addConditionalEdges("llm", (state) => { |
| 126 | + const lastMessage = state.messages[state.messages.length - 1]; |
| 127 | + |
| 128 | + // Cast to AIMessage to access tool_calls property |
| 129 | + const aiMessage = lastMessage as AIMessage; |
| 130 | + if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) { |
| 131 | + console.log("Tool calls detected, routing to tools node"); |
| 132 | + |
| 133 | + // Log what tools are being called |
| 134 | + const toolNames = aiMessage.tool_calls |
| 135 | + .map((tc) => tc.name) |
| 136 | + .join(", "); |
| 137 | + console.log(`Tools being called: ${toolNames}`); |
| 138 | + |
| 139 | + return "tools"; |
| 140 | + } |
| 141 | + |
| 142 | + // If there are no tool calls, we're done |
| 143 | + console.log("No tool calls, ending the workflow"); |
| 144 | + return END; |
| 145 | + }); |
| 146 | + |
| 147 | + // Compile the graph |
| 148 | + const app = workflow.compile(); |
| 149 | + |
| 150 | + // Define examples to run |
| 151 | + const examples = [ |
| 152 | + { |
| 153 | + name: "Add 1 and 2", |
| 154 | + query: "What is 1 + 2?", |
| 155 | + }, |
| 156 | + { |
| 157 | + name: "Subtract 1 from 2", |
| 158 | + query: "What is 2 - 1?", |
| 159 | + }, |
| 160 | + { |
| 161 | + name: "Multiply 1 and 2", |
| 162 | + query: "What is 1 * 2?", |
| 163 | + }, |
| 164 | + { |
| 165 | + name: "Divide 1 by 2", |
| 166 | + query: "What is 1 / 2?", |
| 167 | + }, |
| 168 | + ]; |
| 169 | + |
| 170 | + // Run the examples |
| 171 | + console.log("\n=== RUNNING LANGGRAPH AGENT ==="); |
| 172 | + |
| 173 | + for (const example of examples) { |
| 174 | + console.log(`\n--- Example: ${example.name} ---`); |
| 175 | + console.log(`Query: ${example.query}`); |
| 176 | + |
| 177 | + // Run the LangGraph agent |
| 178 | + const result = await app.invoke({ |
| 179 | + messages: [new HumanMessage(example.query)], |
| 180 | + }); |
| 181 | + |
| 182 | + // Display the final answer |
| 183 | + const finalMessage = result.messages[result.messages.length - 1]; |
| 184 | + console.log(`\nResult: ${finalMessage.content}`); |
| 185 | + } |
| 186 | + } catch (error) { |
| 187 | + console.error("Error:", error); |
| 188 | + process.exit(1); // Exit with error code |
| 189 | + } finally { |
| 190 | + if (client) { |
| 191 | + await client.close(); |
| 192 | + console.log("Closed all MCP connections"); |
| 193 | + } |
| 194 | + |
| 195 | + // Exit process after a short delay to allow for cleanup |
| 196 | + setTimeout(() => { |
| 197 | + console.log("Example completed, exiting process."); |
| 198 | + process.exit(0); |
| 199 | + }, 500); |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +const isMainModule = import.meta.url === `file://${process.argv[1]}`; |
| 204 | + |
| 205 | +if (isMainModule) { |
| 206 | + runExample().catch((error) => console.error("Setup error:", error)); |
| 207 | +} |
0 commit comments