Spaces:
Running
Running
File size: 20,387 Bytes
aa98b19 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# MCP + LangGraph Hands-On Tutorial\n",
"\n",
"- Author: [Teddy Notes](https://youtube.com/c/teddynote)\n",
"- Lecture: [Fastcampus RAG trick notes](https://fastcampus.co.kr/data_online_teddy)\n",
"\n",
"**References**\n",
"- https://modelcontextprotocol.io/introduction\n",
"- https://github.com/langchain-ai/langchain-mcp-adapters"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## configure\n",
"\n",
"Refer to the installation instructions below to install `uv`.\n",
"\n",
"**How to install `uv`**\n",
"\n",
"```bash\n",
"# macOS/Linux\n",
"curl -LsSf https://astral.sh/uv/install.sh | sh\n",
"\n",
"# Windows (PowerShell)\n",
"irm https://astral.sh/uv/install.ps1 | iex\n",
"```\n",
"\n",
"Install **dependencies**\n",
"\n",
"```bash\n",
"uv pip install -r requirements.txt\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Gets the environment variables."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from dotenv import load_dotenv\n",
"\n",
"load_dotenv(override=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## MultiServerMCPClient"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run `mcp_server_remote.py` in advance. Open a terminal with the virtual environment activated and run the server.\n",
"\n",
"> Command\n",
"```bash\n",
"source .venv/bin/activate\n",
"python mcp_server_remote.py\n",
"```\n",
"\n",
"Create and terminate a temporary Session connection using `async with`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain_mcp_adapters.client import MultiServerMCPClient\n",
"from langgraph.prebuilt import create_react_agent\n",
"from utils import ainvoke_graph, astream_graph\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"model = ChatAnthropic(\n",
" model_name=\"claude-3-7-sonnet-latest\", temperature=0, max_tokens=20000\n",
")\n",
"\n",
"async with MultiServerMCPClient(\n",
" {\n",
" \"weather\": {\n",
" # Must match the server's port (port 8005)\n",
" \"url\": \"http://localhost:8005/sse\",\n",
" \"transport\": \"sse\",\n",
" }\n",
" }\n",
") as client:\n",
" print(client.get_tools())\n",
" agent = create_react_agent(model, client.get_tools())\n",
" answer = await astream_graph(\n",
" agent, {\"messages\": \"What's the weather like in Seoul?\"}\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You might notice that you can't access the tool because the session is closed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(agent, {\"messages\": \"What's the weather like in Seoul?\"})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's change that to accessing the tool while maintaining an Async Session."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 1. Create client\n",
"client = MultiServerMCPClient(\n",
" {\n",
" \"weather\": {\n",
" \"url\": \"http://localhost:8005/sse\",\n",
" \"transport\": \"sse\",\n",
" }\n",
" }\n",
")\n",
"\n",
"\n",
"# 2. Explicitly initialize connection (this part is necessary)\n",
"# Initialize\n",
"await client.__aenter__()\n",
"\n",
"# Now tools are loaded\n",
"print(client.get_tools()) # Tools are displayed"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an agent with langgraph(`create_react_agent`)."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# Create agent\n",
"agent = create_react_agent(model, client.get_tools())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run the graph to see the results."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(agent, {\"messages\": \"What's the weather like in Seoul?\"})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Stdio method\n",
"\n",
"The Stdio method is intended for use in a local environment.\n",
"\n",
"- Use standard input/output for communication"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from mcp import ClientSession, StdioServerParameters\n",
"from mcp.client.stdio import stdio_client\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_mcp_adapters.tools import load_mcp_tools\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"# Initialize Anthropic's Claude model\n",
"model = ChatAnthropic(\n",
" model_name=\"claude-3-7-sonnet-latest\", temperature=0, max_tokens=20000\n",
")\n",
"\n",
"# Set up StdIO server parameters\n",
"# - command: Path to Python interpreter\n",
"# - args: MCP server script to execute\n",
"server_params = StdioServerParameters(\n",
" command=\"./.venv/bin/python\",\n",
" args=[\"mcp_server_local.py\"],\n",
")\n",
"\n",
"# Use StdIO client to communicate with the server\n",
"async with stdio_client(server_params) as (read, write):\n",
" # Create client session\n",
" async with ClientSession(read, write) as session:\n",
" # Initialize connection\n",
" await session.initialize()\n",
"\n",
" # Load MCP tools\n",
" tools = await load_mcp_tools(session)\n",
" print(tools)\n",
"\n",
" # Create agent\n",
" agent = create_react_agent(model, tools)\n",
"\n",
" # Stream agent responses\n",
" await astream_graph(agent, {\"messages\": \"What's the weather like in Seoul?\"})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use MCP server with RAG deployed\n",
"\n",
"- File: `mcp_server_rag.py`\n",
"\n",
"Use the `mcp_server_rag.py` file that we built with langchain in advance.\n",
"\n",
"It uses stdio communication to get information about the tools, where it gets the `retriever` tool, which is the tool defined in `mcp_server_rag.py`. This file **doesn't** need to be running on the server beforehand."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from mcp import ClientSession, StdioServerParameters\n",
"from mcp.client.stdio import stdio_client\n",
"from langchain_mcp_adapters.tools import load_mcp_tools\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_anthropic import ChatAnthropic\n",
"from utils import astream_graph\n",
"\n",
"# Initialize Anthropic's Claude model\n",
"model = ChatAnthropic(\n",
" model_name=\"claude-3-7-sonnet-latest\", temperature=0, max_tokens=20000\n",
")\n",
"\n",
"# Set up StdIO server parameters for the RAG server\n",
"server_params = StdioServerParameters(\n",
" command=\"./.venv/bin/python\",\n",
" args=[\"./mcp_server_rag.py\"],\n",
")\n",
"\n",
"# Use StdIO client to communicate with the RAG server\n",
"async with stdio_client(server_params) as (read, write):\n",
" # Create client session\n",
" async with ClientSession(read, write) as session:\n",
" # Initialize connection\n",
" await session.initialize()\n",
"\n",
" # Load MCP tools (in this case, the retriever tool)\n",
" tools = await load_mcp_tools(session)\n",
"\n",
" # Create and run the agent\n",
" agent = create_react_agent(model, tools)\n",
"\n",
" # Stream agent responses\n",
" await astream_graph(\n",
" agent,\n",
" {\n",
" \"messages\": \"Search for the name of the generative AI developed by Samsung Electronics\"\n",
" },\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use a mix of SSE and Stdio methods\n",
"\n",
"- File: `mcp_server_rag.py` communicates over Stdio\n",
"- `langchain-dev-docs` communicates via SSE\n",
"\n",
"Use a mix of SSE and Stdio methods."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain_mcp_adapters.client import MultiServerMCPClient\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"# Initialize Anthropic's Claude model\n",
"model = ChatAnthropic(\n",
" model_name=\"claude-3-7-sonnet-latest\", temperature=0, max_tokens=20000\n",
")\n",
"\n",
"# 1. Create multi-server MCP client\n",
"client = MultiServerMCPClient(\n",
" {\n",
" \"document-retriever\": {\n",
" \"command\": \"./.venv/bin/python\",\n",
" # Update with the absolute path to mcp_server_rag.py file\n",
" \"args\": [\"./mcp_server_rag.py\"],\n",
" # Communicate via stdio (using standard input/output)\n",
" \"transport\": \"stdio\",\n",
" },\n",
" \"langchain-dev-docs\": {\n",
" # Make sure the SSE server is running\n",
" \"url\": \"https://teddynote.io/mcp/langchain/sse\",\n",
" # Communicate via SSE (Server-Sent Events)\n",
" \"transport\": \"sse\",\n",
" },\n",
" }\n",
")\n",
"\n",
"\n",
"# 2. Initialize connection explicitly through async context manager\n",
"await client.__aenter__()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an agent using `create_react_agent` in langgraph."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langchain_core.runnables import RunnableConfig\n",
"\n",
"prompt = (\n",
" \"You are a smart agent. \"\n",
" \"Use `retriever` tool to search on AI related documents and answer questions.\"\n",
" \"Use `langchain-dev-docs` tool to search on langchain / langgraph related documents and answer questions.\"\n",
" \"Answer in English.\"\n",
")\n",
"agent = create_react_agent(\n",
" model, client.get_tools(), prompt=prompt, checkpointer=MemorySaver()\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use the `retriever` tool defined in `mcp_server_rag.py` that you built to perform the search."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"config = RunnableConfig(recursion_limit=30, thread_id=1)\n",
"await astream_graph(\n",
" agent,\n",
" {\n",
" \"messages\": \"Use the `retriever` tool to search for the name of the generative AI developed by Samsung Electronics\"\n",
" },\n",
" config=config,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This time, we'll use the `langchain-dev-docs` tool to perform the search."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"config = RunnableConfig(recursion_limit=30, thread_id=1)\n",
"await astream_graph(\n",
" agent,\n",
" {\n",
" \"messages\": \"Please tell me about the definition of self-rag by referring to the langchain-dev-docs\"\n",
" },\n",
" config=config,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Use `MemorySaver` to maintain short-term memory, so multi-turn conversations are possible."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(\n",
" agent,\n",
" {\"messages\": \"Summarize the previous content in bullet points\"},\n",
" config=config,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## LangChain-integrated tools + MCP tools\n",
"\n",
"Here we confirm that tools integrated into LangChain can be used in conjunction with existing MCP-only tools."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
"\n",
"# Initialize the Tavily search tool (news type, news from the last 3 days)\n",
"tavily = TavilySearchResults(max_results=3, topic=\"news\", days=3)\n",
"\n",
"# Use it together with existing MCP tools\n",
"tools = client.get_tools() + [tavily]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an agent using `create_react_agent` in langgraph."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langchain_core.runnables import RunnableConfig\n",
"\n",
"prompt = \"You are a smart agent with various tools. Answer questions in English.\"\n",
"agent = create_react_agent(model, tools, prompt=prompt, checkpointer=MemorySaver())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Perform a search using the newly added `tavily` tool."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(\n",
" agent, {\"messages\": \"Tell me about today's news for me\"}, config=config\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that the `retriever` tool is working smoothly."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(\n",
" agent,\n",
" {\n",
" \"messages\": \"Use the `retriever` tool to search for the name of the generative AI developed by Samsung Electronics\"\n",
" },\n",
" config=config,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Smithery MCP Server\n",
"\n",
"- Link: https://smithery.ai/\n",
"\n",
"List of tools used:\n",
"\n",
"- Sequential Thinking: https://smithery.ai/server/@smithery-ai/server-sequential-thinking\n",
" - MCP server providing tools for dynamic and reflective problem-solving through structured thinking processes\n",
"- Desktop Commander: https://smithery.ai/server/@wonderwhy-er/desktop-commander\n",
" - Run terminal commands and manage files with various editing capabilities. Coding, shell and terminal, task automation\n",
"\n",
"**Note**\n",
"\n",
"- When importing tools provided by smithery in JSON format, you must set `\"transport\": \"stdio\"` as shown in the example below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain_mcp_adapters.client import MultiServerMCPClient\n",
"from langgraph.prebuilt import create_react_agent\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"# Initialize LLM model\n",
"model = ChatAnthropic(model=\"claude-3-7-sonnet-latest\", temperature=0, max_tokens=20000)\n",
"\n",
"# 1. Create client\n",
"client = MultiServerMCPClient(\n",
" {\n",
" \"server-sequential-thinking\": {\n",
" \"command\": \"npx\",\n",
" \"args\": [\n",
" \"-y\",\n",
" \"@smithery/cli@latest\",\n",
" \"run\",\n",
" \"@smithery-ai/server-sequential-thinking\",\n",
" \"--key\",\n",
" \"your_smithery_api_key\",\n",
" ],\n",
" \"transport\": \"stdio\", # Add communication using stdio method\n",
" },\n",
" \"desktop-commander\": {\n",
" \"command\": \"npx\",\n",
" \"args\": [\n",
" \"-y\",\n",
" \"@smithery/cli@latest\",\n",
" \"run\",\n",
" \"@wonderwhy-er/desktop-commander\",\n",
" \"--key\",\n",
" \"your_smithery_api_key\",\n",
" ],\n",
" \"transport\": \"stdio\", # Add communication using stdio method\n",
" },\n",
" \"document-retriever\": {\n",
" \"command\": \"./.venv/bin/python\",\n",
" # Update with the absolute path to the mcp_server_rag.py file\n",
" \"args\": [\"./mcp_server_rag.py\"],\n",
" # Communication using stdio (standard input/output)\n",
" \"transport\": \"stdio\",\n",
" },\n",
" }\n",
")\n",
"\n",
"\n",
"# 2. Explicitly initialize connection\n",
"await client.__aenter__()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an agent using `create_react_agent` in langgraph."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"from langgraph.checkpoint.memory import MemorySaver\n",
"from langchain_core.runnables import RunnableConfig\n",
"\n",
"# Set up configuration\n",
"config = RunnableConfig(recursion_limit=30, thread_id=3)\n",
"\n",
"# Create agent\n",
"agent = create_react_agent(model, client.get_tools(), checkpointer=MemorySaver())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`Desktop Commander` ๋๊ตฌ๋ฅผ ์ฌ์ฉํ์ฌ ํฐ๋ฏธ๋ ๋ช
๋ น์ ์คํํฉ๋๋ค."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(\n",
" agent,\n",
" {\n",
" \"messages\": \"Draw the folder structure including the current path as a tree. However, exclude the .venv folder from the output.\"\n",
" },\n",
" config=config,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll use the `Sequential Thinking` tool to see if we can accomplish a relatively complex task."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"await astream_graph(\n",
" agent,\n",
" {\n",
" \"messages\": (\n",
" \"Use the `retriever` tool to search for information about generative AI developed by Samsung Electronics, \"\n",
" \"and then use the `Sequential Thinking` tool to write a report.\"\n",
" )\n",
" },\n",
" config=config,\n",
")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|